ngram
listlengths 0
67.8k
|
|---|
[
"= get_file_per_folder(folder) for d in sorted(files): norm = normalize_name_and_numbers(files[d]) for r in norm:",
"= normalize_name_and_numbers(files[d]) for r in norm: if r[-2] != r[-1]: pat = os.path.join(folder,",
"file names. \"\"\" import os import re from pyquickhelper.loghelper import noLOG from pyquickhelper.filehelper",
"]+[.][0-9]+) ?[-] ?([0-9]{2,3})[ .v_CF[]\") res = [] for fi in files: name =",
"ke: li[_] = 1 missing = [i for i, _ in enumerate(li) if",
"spl = f.replace(\"\\\\\", \"/\").split(\"/\") if deep == 1: te = spl[-2] fi =",
"d, r[-2]) fLOG(\"rename\", pat, \" in \", nee) neelast = os.path.split(nee)[-1] if neelast[0]",
"around file names. \"\"\" import os import re from pyquickhelper.loghelper import noLOG from",
"spl[-3:-1] fi = spl[-1] if te not in res: res[te] = [] res[te].append(fi)",
"\"{0} - {1}{2}\".format(nam, num, ext) if solution is None or len(nam) > len(solution[1]):",
"= spl[-3:-1] fi = spl[-1] if te not in res: res[te] = []",
"?([0-9]{2,3})[ .v_CF[]\") res = [] for fi in files: name = fi.lower().replace(\"_\", \"",
"is not None: res.append(solution) res.sort() return res def normalize_folder(folder, fLOG=noLOG): \"\"\" normalize the",
"name, original name) \"\"\" alls = [] files = get_file_per_folder(folder) for d in",
"tuple (number, normalized name, extension, suggested name, original name) \"\"\" exp = re.compile(",
"2), (exp2, 1), (exp3, 1)]: num = ex.search(name) if num: grs = num.groups()",
"1 or 2\") return res def normalize_name_and_numbers(files): \"\"\" tries to match names and",
"extract all folders in a folder and then all files in these folders",
"= num.groups() nam = grs[0].strip() num = grs[ind] words = nam.split() for i",
"+ nee + \")\") os.rename(pat, nee) alls.extend(norm) return alls def music_statistics(folder): \"\"\" provides",
"return alls def music_statistics(folder): \"\"\" provides statistics on a folder @param folder folder",
"music_statistics(folder): \"\"\" provides statistics on a folder @param folder folder @return dictionary {",
"match names and number in a file @param files list of files @return",
"\"last\": ..., \"missing\": } } \"\"\" res = {} files = get_file_per_folder(folder) for",
"(exp2, 1), (exp3, 1)]: num = ex.search(name) if num: grs = num.groups() nam",
"r[-1]) nee = os.path.join(folder, d, r[-2]) fLOG(\"rename\", pat, \" in \", nee) neelast",
"1: te = spl[-2] fi = spl[-1] if te not in res: res[te]",
"a folder @param folder folder @return dictionary { \"folder\": { \"last\": ..., \"missing\":",
"\"\"\" extract all folders in a folder and then all files in these",
"in files: spl = f.replace(\"\\\\\", \"/\").split(\"/\") if deep == 1: te = spl[-2]",
"in [(exp, 2), (exp2, 1), (exp3, 1)]: num = ex.search(name) if num: grs",
"+ 1)] for _ in ke: li[_] = 1 missing = [i for",
"res.append(solution) res.sort() return res def normalize_folder(folder, fLOG=noLOG): \"\"\" normalize the filename of a",
"te not in res: res[te] = [] res[te].append(fi) else: raise Exception(\"deep should be",
"v} li = [0 for i in range(ma + 1)] for _ in",
"extension, suggested name, original name) \"\"\" exp = re.compile( \"([0-9a-z;() ]+([-][a-z ]+)?) ?[-]",
"k, v in res.items(): mi, ma = min(v), max(v) ke = {_: 1",
"+ \"(\" + nee + \")\") os.rename(pat, nee) alls.extend(norm) return alls def music_statistics(folder):",
"of folders to considers before the filename @return dictionary \"\"\" files = explore_folder(folder)[1]",
"= {} for f in files: spl = f.replace(\"\\\\\", \"/\").split(\"/\") if deep ==",
"sorted(files): norm = normalize_name_and_numbers(files[d]) for r in norm: if r[-2] != r[-1]: pat",
"\"\"\" normalize the filename of a whole folder and subfolders @param folder folder",
"missing = [i for i, _ in enumerate(li) if _ == 0 and",
"+ neelast + \"(\" + nee + \")\") os.rename(pat, nee) alls.extend(norm) return alls",
"r[-2] != r[-1]: pat = os.path.join(folder, d, r[-1]) nee = os.path.join(folder, d, r[-2])",
"normalized name, extension, suggested name, original name) \"\"\" alls = [] files =",
"+ words[i][1:] nam = \" \".join(words) sugg = \"{0} - {1}{2}\".format(nam, num, ext)",
"res[te] = [] res[te].append(fi) else: raise Exception(\"deep should be 1 or 2\") return",
"re.compile(\"([a-z0-9 ]+[.][0-9]+) ?[-] ?([0-9]{2,3})[ .v_CF[]\") res = [] for fi in files: name",
"d in sorted(files): norm = normalize_name_and_numbers(files[d]) for r in norm: if r[-2] !=",
"folders to considers before the filename @return dictionary \"\"\" files = explore_folder(folder)[1] res",
"whole folder and subfolders @param folder folder @return list of tuple (number, normalized",
"the filename of a whole folder and subfolders @param folder folder @return list",
"_ in ke: li[_] = 1 missing = [i for i, _ in",
"folders in a folder and then all files in these folders @param folder",
"res[te] = [] res[te].append(fi) elif deep == 2: te = spl[-3:-1] fi =",
"2\") return res def normalize_name_and_numbers(files): \"\"\" tries to match names and number in",
"[] res[te].append(fi) else: raise Exception(\"deep should be 1 or 2\") return res def",
"if num: grs = num.groups() nam = grs[0].strip() num = grs[ind] words =",
"if deep == 1: te = spl[-2] fi = spl[-1] if te not",
"normalized name, extension, suggested name, original name) \"\"\" exp = re.compile( \"([0-9a-z;() ]+([-][a-z",
"alls def music_statistics(folder): \"\"\" provides statistics on a folder @param folder folder @return",
"files = get_file_per_folder(folder) for d in sorted(files): norm = normalize_name_and_numbers(files[d]) for r in",
"name, extension, suggested name, original name) \"\"\" alls = [] files = get_file_per_folder(folder)",
"in res: res[te] = [] res[te].append(fi) elif deep == 2: te = spl[-3:-1]",
"[(exp, 2), (exp2, 1), (exp3, 1)]: num = ex.search(name) if num: grs =",
"words[i] = words[i][0].upper() + words[i][1:] nam = \" \".join(words) sugg = \"{0} -",
"< 'A' or neelast[0] > 'Z': raise Exception(\"bad name for \" + neelast",
"neelast + \"(\" + nee + \")\") os.rename(pat, nee) alls.extend(norm) return alls def",
"for i in range(len(words)): words[i] = words[i][0].upper() + words[i][1:] nam = \" \".join(words)",
"elif deep == 2: te = spl[-3:-1] fi = spl[-1] if te not",
"not in res: res[te] = [] res[te].append(fi) elif deep == 2: te =",
"i, _ in enumerate(li) if _ == 0 and i >= mi] comp[k]",
"len(solution[1]): solution = (num, nam, ext, sugg, fi) if solution is not None:",
"considers before the filename @return dictionary \"\"\" files = explore_folder(folder)[1] res = {}",
"nee + \")\") os.rename(pat, nee) alls.extend(norm) return alls def music_statistics(folder): \"\"\" provides statistics",
"for k, v in res.items(): mi, ma = min(v), max(v) ke = {_:",
"sugg = \"{0} - {1}{2}\".format(nam, num, ext) if solution is None or len(nam)",
"@param folder folder @return list of tuple (number, normalized name, extension, suggested name,",
"@return dictionary { \"folder\": { \"last\": ..., \"missing\": } } \"\"\" res =",
"deep=1): \"\"\" extract all folders in a folder and then all files in",
"all folders in a folder and then all files in these folders @param",
"r[-2]) fLOG(\"rename\", pat, \" in \", nee) neelast = os.path.split(nee)[-1] if neelast[0] <",
"= {_: 1 for _ in v} li = [0 for i in",
"folder and subfolders @param folder folder @return list of tuple (number, normalized name,",
"deep == 1: te = spl[-2] fi = spl[-1] if te not in",
"ind in [(exp, 2), (exp2, 1), (exp3, 1)]: num = ex.search(name) if num:",
"{ \"folder\": { \"last\": ..., \"missing\": } } \"\"\" res = {} files",
"range(ma + 1)] for _ in ke: li[_] = 1 missing = [i",
"normalize_name_and_numbers(files[d]) for r in norm: if d not in res: res[d] = []",
"num.groups() nam = grs[0].strip() num = grs[ind] words = nam.split() for i in",
"neelast = os.path.split(nee)[-1] if neelast[0] < 'A' or neelast[0] > 'Z': raise Exception(\"bad",
"res.items(): mi, ma = min(v), max(v) ke = {_: 1 for _ in",
"return res def normalize_name_and_numbers(files): \"\"\" tries to match names and number in a",
"def get_file_per_folder(folder, deep=1): \"\"\" extract all folders in a folder and then all",
"= os.path.split(nee)[-1] if neelast[0] < 'A' or neelast[0] > 'Z': raise Exception(\"bad name",
"folder @param folder folder @return dictionary { \"folder\": { \"last\": ..., \"missing\": }",
"names. \"\"\" import os import re from pyquickhelper.loghelper import noLOG from pyquickhelper.filehelper import",
"get_file_per_folder(folder, deep=1): \"\"\" extract all folders in a folder and then all files",
"filename of a whole folder and subfolders @param folder folder @return list of",
".v_CF[]\") exp3 = re.compile(\"([a-z0-9 ]+[.][0-9]+) ?[-] ?([0-9]{2,3})[ .v_CF[]\") res = [] for fi",
"noLOG from pyquickhelper.filehelper import explore_folder def get_file_per_folder(folder, deep=1): \"\"\" extract all folders in",
"d not in res: res[d] = [] res[d].append(int(r[0])) comp = {} for k,",
"a whole folder and subfolders @param folder folder @return list of tuple (number,",
"or 2\") return res def normalize_name_and_numbers(files): \"\"\" tries to match names and number",
"file @param files list of files @return list of tuple (number, normalized name,",
"suggested name, original name) \"\"\" alls = [] files = get_file_per_folder(folder) for d",
"= \"{0} - {1}{2}\".format(nam, num, ext) if solution is None or len(nam) >",
"2: te = spl[-3:-1] fi = spl[-1] if te not in res: res[te]",
"res = [] for fi in files: name = fi.lower().replace(\"_\", \" \").replace(\"!\", \"",
"= spl[-1] if te not in res: res[te] = [] res[te].append(fi) elif deep",
"res[te].append(fi) elif deep == 2: te = spl[-3:-1] fi = spl[-1] if te",
"1 for _ in v} li = [0 for i in range(ma +",
"is None or len(nam) > len(solution[1]): solution = (num, nam, ext, sugg, fi)",
"pat = os.path.join(folder, d, r[-1]) nee = os.path.join(folder, d, r[-2]) fLOG(\"rename\", pat, \"",
"ex, ind in [(exp, 2), (exp2, 1), (exp3, 1)]: num = ex.search(name) if",
"to match names and number in a file @param files list of files",
"normalize_name_and_numbers(files[d]) for r in norm: if r[-2] != r[-1]: pat = os.path.join(folder, d,",
"for r in norm: if r[-2] != r[-1]: pat = os.path.join(folder, d, r[-1])",
"os.path.join(folder, d, r[-2]) fLOG(\"rename\", pat, \" in \", nee) neelast = os.path.split(nee)[-1] if",
"= re.compile(\"([0-9a-z;() ]+) episode ([0-9]{2,3})[ .v_CF[]\") exp3 = re.compile(\"([a-z0-9 ]+[.][0-9]+) ?[-] ?([0-9]{2,3})[ .v_CF[]\")",
"list of tuple (number, normalized name, extension, suggested name, original name) \"\"\" alls",
"these folders @param folder folder @param deep number of folders to considers before",
"\" \").replace(\"!\", \" \") ext = os.path.splitext(fi)[-1] solution = None for ex, ind",
"name for \" + neelast + \"(\" + nee + \")\") os.rename(pat, nee)",
"name, original name) \"\"\" exp = re.compile( \"([0-9a-z;() ]+([-][a-z ]+)?) ?[-] ?([0-9]{2,3})[ .v_CF[]\")",
"in res.items(): mi, ma = min(v), max(v) ke = {_: 1 for _",
"def normalize_name_and_numbers(files): \"\"\" tries to match names and number in a file @param",
"@return list of tuple (number, normalized name, extension, suggested name, original name) \"\"\"",
"i in range(len(words)): words[i] = words[i][0].upper() + words[i][1:] nam = \" \".join(words) sugg",
"1)] for _ in ke: li[_] = 1 missing = [i for i,",
"@brief Helpers around file names. \"\"\" import os import re from pyquickhelper.loghelper import",
"solution is None or len(nam) > len(solution[1]): solution = (num, nam, ext, sugg,",
"[] files = get_file_per_folder(folder) for d in sorted(files): norm = normalize_name_and_numbers(files[d]) for r",
"@file @brief Helpers around file names. \"\"\" import os import re from pyquickhelper.loghelper",
"original name) \"\"\" alls = [] files = get_file_per_folder(folder) for d in sorted(files):",
"folders @param folder folder @param deep number of folders to considers before the",
"deep number of folders to considers before the filename @return dictionary \"\"\" files",
"comp = {} for k, v in res.items(): mi, ma = min(v), max(v)",
"mi, ma = min(v), max(v) ke = {_: 1 for _ in v}",
"num = grs[ind] words = nam.split() for i in range(len(words)): words[i] = words[i][0].upper()",
"d, r[-1]) nee = os.path.join(folder, d, r[-2]) fLOG(\"rename\", pat, \" in \", nee)",
"pat, \" in \", nee) neelast = os.path.split(nee)[-1] if neelast[0] < 'A' or",
"episode ([0-9]{2,3})[ .v_CF[]\") exp3 = re.compile(\"([a-z0-9 ]+[.][0-9]+) ?[-] ?([0-9]{2,3})[ .v_CF[]\") res = []",
"Exception(\"deep should be 1 or 2\") return res def normalize_name_and_numbers(files): \"\"\" tries to",
"= [] for fi in files: name = fi.lower().replace(\"_\", \" \").replace(\"!\", \" \")",
"spl[-2] fi = spl[-1] if te not in res: res[te] = [] res[te].append(fi)",
"res: res[te] = [] res[te].append(fi) else: raise Exception(\"deep should be 1 or 2\")",
"norm: if d not in res: res[d] = [] res[d].append(int(r[0])) comp = {}",
"\"\"\" @file @brief Helpers around file names. \"\"\" import os import re from",
"spl[-1] if te not in res: res[te] = [] res[te].append(fi) else: raise Exception(\"deep",
"solution = (num, nam, ext, sugg, fi) if solution is not None: res.append(solution)",
"in a folder and then all files in these folders @param folder folder",
"\"\"\" files = explore_folder(folder)[1] res = {} for f in files: spl =",
"fi) if solution is not None: res.append(solution) res.sort() return res def normalize_folder(folder, fLOG=noLOG):",
"names and number in a file @param files list of files @return list",
"and subfolders @param folder folder @return list of tuple (number, normalized name, extension,",
"import explore_folder def get_file_per_folder(folder, deep=1): \"\"\" extract all folders in a folder and",
"provides statistics on a folder @param folder folder @return dictionary { \"folder\": {",
"files = explore_folder(folder)[1] res = {} for f in files: spl = f.replace(\"\\\\\",",
"== 2: te = spl[-3:-1] fi = spl[-1] if te not in res:",
"enumerate(li) if _ == 0 and i >= mi] comp[k] = {\"min\": mi,",
"list of tuple (number, normalized name, extension, suggested name, original name) \"\"\" exp",
"\"missing\": } } \"\"\" res = {} files = get_file_per_folder(folder) for d in",
"= nam.split() for i in range(len(words)): words[i] = words[i][0].upper() + words[i][1:] nam =",
"?[-] ?([0-9]{2,3})[ .v_CF[]\") res = [] for fi in files: name = fi.lower().replace(\"_\",",
"\"\"\" import os import re from pyquickhelper.loghelper import noLOG from pyquickhelper.filehelper import explore_folder",
"f.replace(\"\\\\\", \"/\").split(\"/\") if deep == 1: te = spl[-2] fi = spl[-1] if",
"?([0-9]{2,3})[ .v_CF[]\") exp2 = re.compile(\"([0-9a-z;() ]+) episode ([0-9]{2,3})[ .v_CF[]\") exp3 = re.compile(\"([a-z0-9 ]+[.][0-9]+)",
"} } \"\"\" res = {} files = get_file_per_folder(folder) for d in sorted(files):",
"not in res: res[te] = [] res[te].append(fi) else: raise Exception(\"deep should be 1",
"= [] res[te].append(fi) else: raise Exception(\"deep should be 1 or 2\") return res",
"else: raise Exception(\"deep should be 1 or 2\") return res def normalize_name_and_numbers(files): \"\"\"",
".v_CF[]\") exp2 = re.compile(\"([0-9a-z;() ]+) episode ([0-9]{2,3})[ .v_CF[]\") exp3 = re.compile(\"([a-z0-9 ]+[.][0-9]+) ?[-]",
"get_file_per_folder(folder) for d in sorted(files): norm = normalize_name_and_numbers(files[d]) for r in norm: if",
"i in range(ma + 1)] for _ in ke: li[_] = 1 missing",
"words[i][0].upper() + words[i][1:] nam = \" \".join(words) sugg = \"{0} - {1}{2}\".format(nam, num,",
"..., \"missing\": } } \"\"\" res = {} files = get_file_per_folder(folder) for d",
"[] res[d].append(int(r[0])) comp = {} for k, v in res.items(): mi, ma =",
"then all files in these folders @param folder folder @param deep number of",
"in files: name = fi.lower().replace(\"_\", \" \").replace(\"!\", \" \") ext = os.path.splitext(fi)[-1] solution",
"and number in a file @param files list of files @return list of",
"import os import re from pyquickhelper.loghelper import noLOG from pyquickhelper.filehelper import explore_folder def",
"\" in \", nee) neelast = os.path.split(nee)[-1] if neelast[0] < 'A' or neelast[0]",
"res = {} files = get_file_per_folder(folder) for d in sorted(files): norm = normalize_name_and_numbers(files[d])",
"= [0 for i in range(ma + 1)] for _ in ke: li[_]",
"nam = grs[0].strip() num = grs[ind] words = nam.split() for i in range(len(words)):",
"res def normalize_name_and_numbers(files): \"\"\" tries to match names and number in a file",
"num: grs = num.groups() nam = grs[0].strip() num = grs[ind] words = nam.split()",
"in range(ma + 1)] for _ in ke: li[_] = 1 missing =",
"res: res[te] = [] res[te].append(fi) elif deep == 2: te = spl[-3:-1] fi",
"not None: res.append(solution) res.sort() return res def normalize_folder(folder, fLOG=noLOG): \"\"\" normalize the filename",
"@param folder folder @return dictionary { \"folder\": { \"last\": ..., \"missing\": } }",
"min(v), max(v) ke = {_: 1 for _ in v} li = [0",
"if te not in res: res[te] = [] res[te].append(fi) else: raise Exception(\"deep should",
"if d not in res: res[d] = [] res[d].append(int(r[0])) comp = {} for",
"\"folder\": { \"last\": ..., \"missing\": } } \"\"\" res = {} files =",
"None or len(nam) > len(solution[1]): solution = (num, nam, ext, sugg, fi) if",
"all files in these folders @param folder folder @param deep number of folders",
"fLOG=noLOG): \"\"\" normalize the filename of a whole folder and subfolders @param folder",
"nam, ext, sugg, fi) if solution is not None: res.append(solution) res.sort() return res",
"normalize the filename of a whole folder and subfolders @param folder folder @return",
"neelast[0] > 'Z': raise Exception(\"bad name for \" + neelast + \"(\" +",
"exp = re.compile( \"([0-9a-z;() ]+([-][a-z ]+)?) ?[-] ?([0-9]{2,3})[ .v_CF[]\") exp2 = re.compile(\"([0-9a-z;() ]+)",
"None: res.append(solution) res.sort() return res def normalize_folder(folder, fLOG=noLOG): \"\"\" normalize the filename of",
"of tuple (number, normalized name, extension, suggested name, original name) \"\"\" alls =",
"in sorted(files): norm = normalize_name_and_numbers(files[d]) for r in norm: if r[-2] != r[-1]:",
"nee) alls.extend(norm) return alls def music_statistics(folder): \"\"\" provides statistics on a folder @param",
"in v} li = [0 for i in range(ma + 1)] for _",
"= min(v), max(v) ke = {_: 1 for _ in v} li =",
"= f.replace(\"\\\\\", \"/\").split(\"/\") if deep == 1: te = spl[-2] fi = spl[-1]",
"subfolders @param folder folder @return list of tuple (number, normalized name, extension, suggested",
"sorted(files): norm = normalize_name_and_numbers(files[d]) for r in norm: if d not in res:",
"explore_folder def get_file_per_folder(folder, deep=1): \"\"\" extract all folders in a folder and then",
"\"\"\" provides statistics on a folder @param folder folder @return dictionary { \"folder\":",
"== 0 and i >= mi] comp[k] = {\"min\": mi, \"max\": ma, \"missing\":",
"a folder and then all files in these folders @param folder folder @param",
"ext = os.path.splitext(fi)[-1] solution = None for ex, ind in [(exp, 2), (exp2,",
"for i, _ in enumerate(li) if _ == 0 and i >= mi]",
"num, ext) if solution is None or len(nam) > len(solution[1]): solution = (num,",
"= {} for k, v in res.items(): mi, ma = min(v), max(v) ke",
"for ex, ind in [(exp, 2), (exp2, 1), (exp3, 1)]: num = ex.search(name)",
"folder folder @return list of tuple (number, normalized name, extension, suggested name, original",
"= {} files = get_file_per_folder(folder) for d in sorted(files): norm = normalize_name_and_numbers(files[d]) for",
"[] res[te].append(fi) elif deep == 2: te = spl[-3:-1] fi = spl[-1] if",
"li = [0 for i in range(ma + 1)] for _ in ke:",
"if neelast[0] < 'A' or neelast[0] > 'Z': raise Exception(\"bad name for \"",
"]+([-][a-z ]+)?) ?[-] ?([0-9]{2,3})[ .v_CF[]\") exp2 = re.compile(\"([0-9a-z;() ]+) episode ([0-9]{2,3})[ .v_CF[]\") exp3",
"for r in norm: if d not in res: res[d] = [] res[d].append(int(r[0]))",
".v_CF[]\") res = [] for fi in files: name = fi.lower().replace(\"_\", \" \").replace(\"!\",",
"num = ex.search(name) if num: grs = num.groups() nam = grs[0].strip() num =",
"sugg, fi) if solution is not None: res.append(solution) res.sort() return res def normalize_folder(folder,",
"_ in enumerate(li) if _ == 0 and i >= mi] comp[k] =",
"in ke: li[_] = 1 missing = [i for i, _ in enumerate(li)",
"1 missing = [i for i, _ in enumerate(li) if _ == 0",
"import re from pyquickhelper.loghelper import noLOG from pyquickhelper.filehelper import explore_folder def get_file_per_folder(folder, deep=1):",
"\" \") ext = os.path.splitext(fi)[-1] solution = None for ex, ind in [(exp,",
"nam = \" \".join(words) sugg = \"{0} - {1}{2}\".format(nam, num, ext) if solution",
"folder @param deep number of folders to considers before the filename @return dictionary",
"{1}{2}\".format(nam, num, ext) if solution is None or len(nam) > len(solution[1]): solution =",
"range(len(words)): words[i] = words[i][0].upper() + words[i][1:] nam = \" \".join(words) sugg = \"{0}",
"= normalize_name_and_numbers(files[d]) for r in norm: if d not in res: res[d] =",
"in res: res[te] = [] res[te].append(fi) else: raise Exception(\"deep should be 1 or",
"?[-] ?([0-9]{2,3})[ .v_CF[]\") exp2 = re.compile(\"([0-9a-z;() ]+) episode ([0-9]{2,3})[ .v_CF[]\") exp3 = re.compile(\"([a-z0-9",
"(number, normalized name, extension, suggested name, original name) \"\"\" exp = re.compile( \"([0-9a-z;()",
"files: spl = f.replace(\"\\\\\", \"/\").split(\"/\") if deep == 1: te = spl[-2] fi",
"\"(\" + nee + \")\") os.rename(pat, nee) alls.extend(norm) return alls def music_statistics(folder): \"\"\"",
"fi in files: name = fi.lower().replace(\"_\", \" \").replace(\"!\", \" \") ext = os.path.splitext(fi)[-1]",
"\"\"\" res = {} files = get_file_per_folder(folder) for d in sorted(files): norm =",
"in a file @param files list of files @return list of tuple (number,",
"for d in sorted(files): norm = normalize_name_and_numbers(files[d]) for r in norm: if r[-2]",
"and then all files in these folders @param folder folder @param deep number",
"for _ in v} li = [0 for i in range(ma + 1)]",
"(num, nam, ext, sugg, fi) if solution is not None: res.append(solution) res.sort() return",
"of tuple (number, normalized name, extension, suggested name, original name) \"\"\" exp =",
"= ex.search(name) if num: grs = num.groups() nam = grs[0].strip() num = grs[ind]",
"'Z': raise Exception(\"bad name for \" + neelast + \"(\" + nee +",
"ext) if solution is None or len(nam) > len(solution[1]): solution = (num, nam,",
"\" \".join(words) sugg = \"{0} - {1}{2}\".format(nam, num, ext) if solution is None",
"r in norm: if r[-2] != r[-1]: pat = os.path.join(folder, d, r[-1]) nee",
"= [] res[te].append(fi) elif deep == 2: te = spl[-3:-1] fi = spl[-1]",
"d in sorted(files): norm = normalize_name_and_numbers(files[d]) for r in norm: if d not",
"Helpers around file names. \"\"\" import os import re from pyquickhelper.loghelper import noLOG",
"= os.path.splitext(fi)[-1] solution = None for ex, ind in [(exp, 2), (exp2, 1),",
"from pyquickhelper.loghelper import noLOG from pyquickhelper.filehelper import explore_folder def get_file_per_folder(folder, deep=1): \"\"\" extract",
"@param deep number of folders to considers before the filename @return dictionary \"\"\"",
"0 and i >= mi] comp[k] = {\"min\": mi, \"max\": ma, \"missing\": missing}",
"te = spl[-3:-1] fi = spl[-1] if te not in res: res[te] =",
"\"\"\" exp = re.compile( \"([0-9a-z;() ]+([-][a-z ]+)?) ?[-] ?([0-9]{2,3})[ .v_CF[]\") exp2 = re.compile(\"([0-9a-z;()",
"solution = None for ex, ind in [(exp, 2), (exp2, 1), (exp3, 1)]:",
"words[i][1:] nam = \" \".join(words) sugg = \"{0} - {1}{2}\".format(nam, num, ext) if",
"r in norm: if d not in res: res[d] = [] res[d].append(int(r[0])) comp",
"= [] res[d].append(int(r[0])) comp = {} for k, v in res.items(): mi, ma",
"deep == 2: te = spl[-3:-1] fi = spl[-1] if te not in",
"_ == 0 and i >= mi] comp[k] = {\"min\": mi, \"max\": ma,",
"filename @return dictionary \"\"\" files = explore_folder(folder)[1] res = {} for f in",
"= re.compile(\"([a-z0-9 ]+[.][0-9]+) ?[-] ?([0-9]{2,3})[ .v_CF[]\") res = [] for fi in files:",
"> len(solution[1]): solution = (num, nam, ext, sugg, fi) if solution is not",
"a file @param files list of files @return list of tuple (number, normalized",
"\", nee) neelast = os.path.split(nee)[-1] if neelast[0] < 'A' or neelast[0] > 'Z':",
"number in a file @param files list of files @return list of tuple",
"should be 1 or 2\") return res def normalize_name_and_numbers(files): \"\"\" tries to match",
"of a whole folder and subfolders @param folder folder @return list of tuple",
"= [i for i, _ in enumerate(li) if _ == 0 and i",
"if te not in res: res[te] = [] res[te].append(fi) elif deep == 2:",
"for fi in files: name = fi.lower().replace(\"_\", \" \").replace(\"!\", \" \") ext =",
"original name) \"\"\" exp = re.compile( \"([0-9a-z;() ]+([-][a-z ]+)?) ?[-] ?([0-9]{2,3})[ .v_CF[]\") exp2",
"{} for k, v in res.items(): mi, ma = min(v), max(v) ke =",
"def normalize_folder(folder, fLOG=noLOG): \"\"\" normalize the filename of a whole folder and subfolders",
"} \"\"\" res = {} files = get_file_per_folder(folder) for d in sorted(files): norm",
"or neelast[0] > 'Z': raise Exception(\"bad name for \" + neelast + \"(\"",
"re from pyquickhelper.loghelper import noLOG from pyquickhelper.filehelper import explore_folder def get_file_per_folder(folder, deep=1): \"\"\"",
"grs[ind] words = nam.split() for i in range(len(words)): words[i] = words[i][0].upper() + words[i][1:]",
"== 1: te = spl[-2] fi = spl[-1] if te not in res:",
"norm = normalize_name_and_numbers(files[d]) for r in norm: if d not in res: res[d]",
"alls = [] files = get_file_per_folder(folder) for d in sorted(files): norm = normalize_name_and_numbers(files[d])",
"@param folder folder @param deep number of folders to considers before the filename",
"and i >= mi] comp[k] = {\"min\": mi, \"max\": ma, \"missing\": missing} return",
"(number, normalized name, extension, suggested name, original name) \"\"\" alls = [] files",
"name) \"\"\" exp = re.compile( \"([0-9a-z;() ]+([-][a-z ]+)?) ?[-] ?([0-9]{2,3})[ .v_CF[]\") exp2 =",
"= spl[-2] fi = spl[-1] if te not in res: res[te] = []",
"number of folders to considers before the filename @return dictionary \"\"\" files =",
"{ \"last\": ..., \"missing\": } } \"\"\" res = {} files = get_file_per_folder(folder)",
"for \" + neelast + \"(\" + nee + \")\") os.rename(pat, nee) alls.extend(norm)",
"os import re from pyquickhelper.loghelper import noLOG from pyquickhelper.filehelper import explore_folder def get_file_per_folder(folder,",
"explore_folder(folder)[1] res = {} for f in files: spl = f.replace(\"\\\\\", \"/\").split(\"/\") if",
"exp3 = re.compile(\"([a-z0-9 ]+[.][0-9]+) ?[-] ?([0-9]{2,3})[ .v_CF[]\") res = [] for fi in",
"= (num, nam, ext, sugg, fi) if solution is not None: res.append(solution) res.sort()",
"= words[i][0].upper() + words[i][1:] nam = \" \".join(words) sugg = \"{0} - {1}{2}\".format(nam,",
"for d in sorted(files): norm = normalize_name_and_numbers(files[d]) for r in norm: if d",
"res[d].append(int(r[0])) comp = {} for k, v in res.items(): mi, ma = min(v),",
"folder folder @param deep number of folders to considers before the filename @return",
"ma = min(v), max(v) ke = {_: 1 for _ in v} li",
"- {1}{2}\".format(nam, num, ext) if solution is None or len(nam) > len(solution[1]): solution",
"{} files = get_file_per_folder(folder) for d in sorted(files): norm = normalize_name_and_numbers(files[d]) for r",
"for f in files: spl = f.replace(\"\\\\\", \"/\").split(\"/\") if deep == 1: te",
"None for ex, ind in [(exp, 2), (exp2, 1), (exp3, 1)]: num =",
"in sorted(files): norm = normalize_name_and_numbers(files[d]) for r in norm: if d not in",
"= None for ex, ind in [(exp, 2), (exp2, 1), (exp3, 1)]: num",
"]+)?) ?[-] ?([0-9]{2,3})[ .v_CF[]\") exp2 = re.compile(\"([0-9a-z;() ]+) episode ([0-9]{2,3})[ .v_CF[]\") exp3 =",
"{_: 1 for _ in v} li = [0 for i in range(ma",
"spl[-1] if te not in res: res[te] = [] res[te].append(fi) elif deep ==",
"nee = os.path.join(folder, d, r[-2]) fLOG(\"rename\", pat, \" in \", nee) neelast =",
"in norm: if d not in res: res[d] = [] res[d].append(int(r[0])) comp =",
"= grs[ind] words = nam.split() for i in range(len(words)): words[i] = words[i][0].upper() +",
"from pyquickhelper.filehelper import explore_folder def get_file_per_folder(folder, deep=1): \"\"\" extract all folders in a",
"\") ext = os.path.splitext(fi)[-1] solution = None for ex, ind in [(exp, 2),",
"words = nam.split() for i in range(len(words)): words[i] = words[i][0].upper() + words[i][1:] nam",
"os.path.split(nee)[-1] if neelast[0] < 'A' or neelast[0] > 'Z': raise Exception(\"bad name for",
"raise Exception(\"bad name for \" + neelast + \"(\" + nee + \")\")",
"folder folder @return dictionary { \"folder\": { \"last\": ..., \"missing\": } } \"\"\"",
"res.sort() return res def normalize_folder(folder, fLOG=noLOG): \"\"\" normalize the filename of a whole",
"tuple (number, normalized name, extension, suggested name, original name) \"\"\" alls = []",
"@param files list of files @return list of tuple (number, normalized name, extension,",
"ex.search(name) if num: grs = num.groups() nam = grs[0].strip() num = grs[ind] words",
"nee) neelast = os.path.split(nee)[-1] if neelast[0] < 'A' or neelast[0] > 'Z': raise",
"len(nam) > len(solution[1]): solution = (num, nam, ext, sugg, fi) if solution is",
"name = fi.lower().replace(\"_\", \" \").replace(\"!\", \" \") ext = os.path.splitext(fi)[-1] solution = None",
"([0-9]{2,3})[ .v_CF[]\") exp3 = re.compile(\"([a-z0-9 ]+[.][0-9]+) ?[-] ?([0-9]{2,3})[ .v_CF[]\") res = [] for",
"os.path.splitext(fi)[-1] solution = None for ex, ind in [(exp, 2), (exp2, 1), (exp3,",
"te = spl[-2] fi = spl[-1] if te not in res: res[te] =",
"dictionary \"\"\" files = explore_folder(folder)[1] res = {} for f in files: spl",
"re.compile( \"([0-9a-z;() ]+([-][a-z ]+)?) ?[-] ?([0-9]{2,3})[ .v_CF[]\") exp2 = re.compile(\"([0-9a-z;() ]+) episode ([0-9]{2,3})[",
"> 'Z': raise Exception(\"bad name for \" + neelast + \"(\" + nee",
"r[-1]: pat = os.path.join(folder, d, r[-1]) nee = os.path.join(folder, d, r[-2]) fLOG(\"rename\", pat,",
"[0 for i in range(ma + 1)] for _ in ke: li[_] =",
"files: name = fi.lower().replace(\"_\", \" \").replace(\"!\", \" \") ext = os.path.splitext(fi)[-1] solution =",
"res[d] = [] res[d].append(int(r[0])) comp = {} for k, v in res.items(): mi,",
"\"\"\" alls = [] files = get_file_per_folder(folder) for d in sorted(files): norm =",
"res def normalize_folder(folder, fLOG=noLOG): \"\"\" normalize the filename of a whole folder and",
"\"\"\" tries to match names and number in a file @param files list",
"os.path.join(folder, d, r[-1]) nee = os.path.join(folder, d, r[-2]) fLOG(\"rename\", pat, \" in \",",
"pyquickhelper.loghelper import noLOG from pyquickhelper.filehelper import explore_folder def get_file_per_folder(folder, deep=1): \"\"\" extract all",
"= \" \".join(words) sugg = \"{0} - {1}{2}\".format(nam, num, ext) if solution is",
"<filename>src/ensae_teaching_cs/homeblog/filename_helper.py \"\"\" @file @brief Helpers around file names. \"\"\" import os import re",
"name) \"\"\" alls = [] files = get_file_per_folder(folder) for d in sorted(files): norm",
"folder and then all files in these folders @param folder folder @param deep",
"{} for f in files: spl = f.replace(\"\\\\\", \"/\").split(\"/\") if deep == 1:",
"if r[-2] != r[-1]: pat = os.path.join(folder, d, r[-1]) nee = os.path.join(folder, d,",
"1)]: num = ex.search(name) if num: grs = num.groups() nam = grs[0].strip() num",
"or len(nam) > len(solution[1]): solution = (num, nam, ext, sugg, fi) if solution",
"name, extension, suggested name, original name) \"\"\" exp = re.compile( \"([0-9a-z;() ]+([-][a-z ]+)?)",
"not in res: res[d] = [] res[d].append(int(r[0])) comp = {} for k, v",
"i >= mi] comp[k] = {\"min\": mi, \"max\": ma, \"missing\": missing} return comp",
"if solution is not None: res.append(solution) res.sort() return res def normalize_folder(folder, fLOG=noLOG): \"\"\"",
"for i in range(ma + 1)] for _ in ke: li[_] = 1",
"= explore_folder(folder)[1] res = {} for f in files: spl = f.replace(\"\\\\\", \"/\").split(\"/\")",
"in these folders @param folder folder @param deep number of folders to considers",
"res[te].append(fi) else: raise Exception(\"deep should be 1 or 2\") return res def normalize_name_and_numbers(files):",
"files @return list of tuple (number, normalized name, extension, suggested name, original name)",
"for _ in ke: li[_] = 1 missing = [i for i, _",
"fLOG(\"rename\", pat, \" in \", nee) neelast = os.path.split(nee)[-1] if neelast[0] < 'A'",
"return res def normalize_folder(folder, fLOG=noLOG): \"\"\" normalize the filename of a whole folder",
"[i for i, _ in enumerate(li) if _ == 0 and i >=",
"= re.compile( \"([0-9a-z;() ]+([-][a-z ]+)?) ?[-] ?([0-9]{2,3})[ .v_CF[]\") exp2 = re.compile(\"([0-9a-z;() ]+) episode",
"extension, suggested name, original name) \"\"\" alls = [] files = get_file_per_folder(folder) for",
"'A' or neelast[0] > 'Z': raise Exception(\"bad name for \" + neelast +",
"(exp3, 1)]: num = ex.search(name) if num: grs = num.groups() nam = grs[0].strip()",
"in enumerate(li) if _ == 0 and i >= mi] comp[k] = {\"min\":",
"exp2 = re.compile(\"([0-9a-z;() ]+) episode ([0-9]{2,3})[ .v_CF[]\") exp3 = re.compile(\"([a-z0-9 ]+[.][0-9]+) ?[-] ?([0-9]{2,3})[",
"v in res.items(): mi, ma = min(v), max(v) ke = {_: 1 for",
"\")\") os.rename(pat, nee) alls.extend(norm) return alls def music_statistics(folder): \"\"\" provides statistics on a",
"+ \")\") os.rename(pat, nee) alls.extend(norm) return alls def music_statistics(folder): \"\"\" provides statistics on",
"alls.extend(norm) return alls def music_statistics(folder): \"\"\" provides statistics on a folder @param folder",
"\".join(words) sugg = \"{0} - {1}{2}\".format(nam, num, ext) if solution is None or",
"fi = spl[-1] if te not in res: res[te] = [] res[te].append(fi) elif",
"in \", nee) neelast = os.path.split(nee)[-1] if neelast[0] < 'A' or neelast[0] >",
"ke = {_: 1 for _ in v} li = [0 for i",
"= 1 missing = [i for i, _ in enumerate(li) if _ ==",
"def music_statistics(folder): \"\"\" provides statistics on a folder @param folder folder @return dictionary",
"]+) episode ([0-9]{2,3})[ .v_CF[]\") exp3 = re.compile(\"([a-z0-9 ]+[.][0-9]+) ?[-] ?([0-9]{2,3})[ .v_CF[]\") res =",
"grs = num.groups() nam = grs[0].strip() num = grs[ind] words = nam.split() for",
"fi.lower().replace(\"_\", \" \").replace(\"!\", \" \") ext = os.path.splitext(fi)[-1] solution = None for ex,",
"norm: if r[-2] != r[-1]: pat = os.path.join(folder, d, r[-1]) nee = os.path.join(folder,",
"\").replace(\"!\", \" \") ext = os.path.splitext(fi)[-1] solution = None for ex, ind in",
"= [] files = get_file_per_folder(folder) for d in sorted(files): norm = normalize_name_and_numbers(files[d]) for",
"on a folder @param folder folder @return dictionary { \"folder\": { \"last\": ...,",
"folder @return dictionary { \"folder\": { \"last\": ..., \"missing\": } } \"\"\" res",
"to considers before the filename @return dictionary \"\"\" files = explore_folder(folder)[1] res =",
"= fi.lower().replace(\"_\", \" \").replace(\"!\", \" \") ext = os.path.splitext(fi)[-1] solution = None for",
"res: res[d] = [] res[d].append(int(r[0])) comp = {} for k, v in res.items():",
"norm = normalize_name_and_numbers(files[d]) for r in norm: if r[-2] != r[-1]: pat =",
"f in files: spl = f.replace(\"\\\\\", \"/\").split(\"/\") if deep == 1: te =",
"re.compile(\"([0-9a-z;() ]+) episode ([0-9]{2,3})[ .v_CF[]\") exp3 = re.compile(\"([a-z0-9 ]+[.][0-9]+) ?[-] ?([0-9]{2,3})[ .v_CF[]\") res",
"of files @return list of tuple (number, normalized name, extension, suggested name, original",
"dictionary { \"folder\": { \"last\": ..., \"missing\": } } \"\"\" res = {}",
"= spl[-1] if te not in res: res[te] = [] res[te].append(fi) else: raise",
"nam.split() for i in range(len(words)): words[i] = words[i][0].upper() + words[i][1:] nam = \"",
"import noLOG from pyquickhelper.filehelper import explore_folder def get_file_per_folder(folder, deep=1): \"\"\" extract all folders",
"grs[0].strip() num = grs[ind] words = nam.split() for i in range(len(words)): words[i] =",
"te not in res: res[te] = [] res[te].append(fi) elif deep == 2: te",
"!= r[-1]: pat = os.path.join(folder, d, r[-1]) nee = os.path.join(folder, d, r[-2]) fLOG(\"rename\",",
"files list of files @return list of tuple (number, normalized name, extension, suggested",
"max(v) ke = {_: 1 for _ in v} li = [0 for",
"\"([0-9a-z;() ]+([-][a-z ]+)?) ?[-] ?([0-9]{2,3})[ .v_CF[]\") exp2 = re.compile(\"([0-9a-z;() ]+) episode ([0-9]{2,3})[ .v_CF[]\")",
"folder @return list of tuple (number, normalized name, extension, suggested name, original name)",
"list of files @return list of tuple (number, normalized name, extension, suggested name,",
"Exception(\"bad name for \" + neelast + \"(\" + nee + \")\") os.rename(pat,",
"\"/\").split(\"/\") if deep == 1: te = spl[-2] fi = spl[-1] if te",
"raise Exception(\"deep should be 1 or 2\") return res def normalize_name_and_numbers(files): \"\"\" tries",
"ext, sugg, fi) if solution is not None: res.append(solution) res.sort() return res def",
"_ in v} li = [0 for i in range(ma + 1)] for",
"suggested name, original name) \"\"\" exp = re.compile( \"([0-9a-z;() ]+([-][a-z ]+)?) ?[-] ?([0-9]{2,3})[",
"[] for fi in files: name = fi.lower().replace(\"_\", \" \").replace(\"!\", \" \") ext",
"1), (exp3, 1)]: num = ex.search(name) if num: grs = num.groups() nam =",
"in range(len(words)): words[i] = words[i][0].upper() + words[i][1:] nam = \" \".join(words) sugg =",
"tries to match names and number in a file @param files list of",
"fi = spl[-1] if te not in res: res[te] = [] res[te].append(fi) else:",
"in norm: if r[-2] != r[-1]: pat = os.path.join(folder, d, r[-1]) nee =",
"= grs[0].strip() num = grs[ind] words = nam.split() for i in range(len(words)): words[i]",
"statistics on a folder @param folder folder @return dictionary { \"folder\": { \"last\":",
"be 1 or 2\") return res def normalize_name_and_numbers(files): \"\"\" tries to match names",
"solution is not None: res.append(solution) res.sort() return res def normalize_folder(folder, fLOG=noLOG): \"\"\" normalize",
"normalize_folder(folder, fLOG=noLOG): \"\"\" normalize the filename of a whole folder and subfolders @param",
"os.rename(pat, nee) alls.extend(norm) return alls def music_statistics(folder): \"\"\" provides statistics on a folder",
"in res: res[d] = [] res[d].append(int(r[0])) comp = {} for k, v in",
"pyquickhelper.filehelper import explore_folder def get_file_per_folder(folder, deep=1): \"\"\" extract all folders in a folder",
"li[_] = 1 missing = [i for i, _ in enumerate(li) if _",
"= os.path.join(folder, d, r[-2]) fLOG(\"rename\", pat, \" in \", nee) neelast = os.path.split(nee)[-1]",
"normalize_name_and_numbers(files): \"\"\" tries to match names and number in a file @param files",
"files in these folders @param folder folder @param deep number of folders to",
"= os.path.join(folder, d, r[-1]) nee = os.path.join(folder, d, r[-2]) fLOG(\"rename\", pat, \" in",
"res = {} for f in files: spl = f.replace(\"\\\\\", \"/\").split(\"/\") if deep",
"if _ == 0 and i >= mi] comp[k] = {\"min\": mi, \"max\":",
"if solution is None or len(nam) > len(solution[1]): solution = (num, nam, ext,",
"\" + neelast + \"(\" + nee + \")\") os.rename(pat, nee) alls.extend(norm) return",
"before the filename @return dictionary \"\"\" files = explore_folder(folder)[1] res = {} for",
"neelast[0] < 'A' or neelast[0] > 'Z': raise Exception(\"bad name for \" +",
"@return dictionary \"\"\" files = explore_folder(folder)[1] res = {} for f in files:",
"the filename @return dictionary \"\"\" files = explore_folder(folder)[1] res = {} for f"
] |
[
"if not isinstance(x, stype): raise AssertionError(f\"{label} should be {stype}, {type(x)} instead\") def ert_multiTypes(x,",
"be greater than 0\") elif x < 0: raise AssertionError(f\"{label} should be greater",
"raise AssertionError(f\"{label} should be {stype}, {type(x)} instead\") def ert_multiTypes(x, types, label): cond =",
"import Callable def ert_type(x, stype, label): if not isinstance(x, stype): raise AssertionError(f\"{label} should",
"typing import Callable def ert_type(x, stype, label): if not isinstance(x, stype): raise AssertionError(f\"{label}",
"instead\") def ert_nonNeg(x, label, include_zero=False): if not include_zero: if x <= 0: raise",
"x < 0: raise AssertionError(f\"{label} should be greater than or equal to 0\")",
"{np.finfo(dtype).max}\", ] ) ) elif dtype.startswith(\"u\") or dtype.startswith(\"i\"): if x > np.iinfo(dtype).max: raise",
"[ \"expected to be lower than {dtype} max:\", f\"{x} < {np.finfo(dtype).max}\", ] )",
"{dtype} max:\", f\"{x} < {np.finfo(dtype).max}\", ] ) ) elif dtype.startswith(\"u\") or dtype.startswith(\"i\"): if",
"label): cond = any(isinstance(x, t) for t in types) if not cond: raise",
") else: logging.warning(f\"assert not implemented for dtype '{dtype}'\") def enable_rich_assert(fun: Callable) -> Callable:",
"x >= vmax: raise AssertionError(f\"expected {vmin}<={label}<{vmax}\") elif rightClose: if x <= vmin or",
"than or equal to 0\") def ert_inInterv(x, vmin, vmax, label, leftClose=False, rightClose=True): if",
"\"expected to be lower than {dtype} max:\", f\"{x} < {np.finfo(dtype).max}\", ] ) )",
"stype, label): if not isinstance(x, stype): raise AssertionError(f\"{label} should be {stype}, {type(x)} instead\")",
"np.iinfo(dtype).max: raise AssertionError( \" \".join( [ \"expected to be lower than {dtype} max:\",",
"import numpy as np # type: ignore import sys from typing import Callable",
"raise AssertionError(f\"expected {vmin}<{label}<={vmax}\") elif x <= vmin or x >= vmax: raise AssertionError(f\"expected",
"raise AssertionError(f\"expected {vmin}<={label}<{vmax}\") elif rightClose: if x <= vmin or x > vmax:",
"vmin or x > vmax: raise AssertionError(f\"expected {vmin}<={label}<={vmax}\") elif x < vmin or",
"should be {stype}, {type(x)} instead\") def ert_multiTypes(x, types, label): cond = any(isinstance(x, t)",
"AssertionError(f\"expected {vmin}<={label}<{vmax}\") elif rightClose: if x <= vmin or x > vmax: raise",
"lower than {dtype} max:\", f\"{x} < {np.finfo(dtype).max}\", ] ) ) elif dtype.startswith(\"u\") or",
"not implemented for dtype '{dtype}'\") def enable_rich_assert(fun: Callable) -> Callable: def wrapper(*args, **kwargs):",
"for t in types) if not cond: raise AssertionError(f\"{label} should be one of",
"if dtype.startswith(\"f\"): if x > np.finfo(dtype).max: raise AssertionError( \" \".join( [ \"expected to",
"**kwargs): try: return fun(*args, **kwargs) except AssertionError as e: logging.exception(e) sys.exit() return wrapper",
"{vmin}<{label}<{vmax}\") def ert_in_dtype(x, dtype): if dtype.startswith(\"f\"): if x > np.finfo(dtype).max: raise AssertionError( \"",
"than {dtype} max:\", f\"{x} < {np.finfo(dtype).max}\", ] ) ) elif dtype.startswith(\"u\") or dtype.startswith(\"i\"):",
"\".join( [ \"expected to be lower than {dtype} max:\", f\"{x} < {np.iinfo(dtype).max}\", ]",
"be one of {types}, {type(x)} instead\") def ert_nonNeg(x, label, include_zero=False): if not include_zero:",
"dtype.startswith(\"f\"): if x > np.finfo(dtype).max: raise AssertionError( \" \".join( [ \"expected to be",
"x <= 0: raise AssertionError(f\"{label} should be greater than 0\") elif x <",
"equal to 0\") def ert_inInterv(x, vmin, vmax, label, leftClose=False, rightClose=True): if leftClose: if",
"elif rightClose: if x <= vmin or x > vmax: raise AssertionError(f\"expected {vmin}<{label}<={vmax}\")",
"< 0: raise AssertionError(f\"{label} should be greater than or equal to 0\") def",
"f\"{x} < {np.finfo(dtype).max}\", ] ) ) elif dtype.startswith(\"u\") or dtype.startswith(\"i\"): if x >",
"sys from typing import Callable def ert_type(x, stype, label): if not isinstance(x, stype):",
"rightClose=True): if leftClose: if rightClose: if x < vmin or x > vmax:",
"in types) if not cond: raise AssertionError(f\"{label} should be one of {types}, {type(x)}",
"AssertionError(f\"{label} should be greater than 0\") elif x < 0: raise AssertionError(f\"{label} should",
"ert_inInterv(x, vmin, vmax, label, leftClose=False, rightClose=True): if leftClose: if rightClose: if x <",
"if x <= vmin or x > vmax: raise AssertionError(f\"expected {vmin}<{label}<={vmax}\") elif x",
"raise AssertionError(f\"{label} should be one of {types}, {type(x)} instead\") def ert_nonNeg(x, label, include_zero=False):",
"def ert_nonNeg(x, label, include_zero=False): if not include_zero: if x <= 0: raise AssertionError(f\"{label}",
"[ \"expected to be lower than {dtype} max:\", f\"{x} < {np.iinfo(dtype).max}\", ] )",
"import logging import numpy as np # type: ignore import sys from typing",
"def ert_type(x, stype, label): if not isinstance(x, stype): raise AssertionError(f\"{label} should be {stype},",
"if not cond: raise AssertionError(f\"{label} should be one of {types}, {type(x)} instead\") def",
"or x >= vmax: raise AssertionError(f\"expected {vmin}<{label}<{vmax}\") def ert_in_dtype(x, dtype): if dtype.startswith(\"f\"): if",
">= vmax: raise AssertionError(f\"expected {vmin}<{label}<{vmax}\") def ert_in_dtype(x, dtype): if dtype.startswith(\"f\"): if x >",
"\" \".join( [ \"expected to be lower than {dtype} max:\", f\"{x} < {np.finfo(dtype).max}\",",
"if x < vmin or x > vmax: raise AssertionError(f\"expected {vmin}<={label}<={vmax}\") elif x",
"not include_zero: if x <= 0: raise AssertionError(f\"{label} should be greater than 0\")",
"AssertionError(f\"expected {vmin}<={label}<={vmax}\") elif x < vmin or x >= vmax: raise AssertionError(f\"expected {vmin}<={label}<{vmax}\")",
") ) else: logging.warning(f\"assert not implemented for dtype '{dtype}'\") def enable_rich_assert(fun: Callable) ->",
"\"\"\" import logging import numpy as np # type: ignore import sys from",
"<NAME> @contact: <EMAIL> \"\"\" import logging import numpy as np # type: ignore",
"def wrapper(*args, **kwargs): try: return fun(*args, **kwargs) except AssertionError as e: logging.exception(e) sys.exit()",
"than {dtype} max:\", f\"{x} < {np.iinfo(dtype).max}\", ] ) ) else: logging.warning(f\"assert not implemented",
"be lower than {dtype} max:\", f\"{x} < {np.finfo(dtype).max}\", ] ) ) elif dtype.startswith(\"u\")",
"any(isinstance(x, t) for t in types) if not cond: raise AssertionError(f\"{label} should be",
"\"expected to be lower than {dtype} max:\", f\"{x} < {np.iinfo(dtype).max}\", ] ) )",
"be greater than or equal to 0\") def ert_inInterv(x, vmin, vmax, label, leftClose=False,",
"'{dtype}'\") def enable_rich_assert(fun: Callable) -> Callable: def wrapper(*args, **kwargs): try: return fun(*args, **kwargs)",
"of {types}, {type(x)} instead\") def ert_nonNeg(x, label, include_zero=False): if not include_zero: if x",
"vmin or x > vmax: raise AssertionError(f\"expected {vmin}<{label}<={vmax}\") elif x <= vmin or",
"t) for t in types) if not cond: raise AssertionError(f\"{label} should be one",
"raise AssertionError( \" \".join( [ \"expected to be lower than {dtype} max:\", f\"{x}",
") elif dtype.startswith(\"u\") or dtype.startswith(\"i\"): if x > np.iinfo(dtype).max: raise AssertionError( \" \".join(",
"to be lower than {dtype} max:\", f\"{x} < {np.iinfo(dtype).max}\", ] ) ) else:",
"or x > vmax: raise AssertionError(f\"expected {vmin}<={label}<={vmax}\") elif x < vmin or x",
"lower than {dtype} max:\", f\"{x} < {np.iinfo(dtype).max}\", ] ) ) else: logging.warning(f\"assert not",
"{dtype} max:\", f\"{x} < {np.iinfo(dtype).max}\", ] ) ) else: logging.warning(f\"assert not implemented for",
") ) elif dtype.startswith(\"u\") or dtype.startswith(\"i\"): if x > np.iinfo(dtype).max: raise AssertionError( \"",
"rightClose: if x <= vmin or x > vmax: raise AssertionError(f\"expected {vmin}<{label}<={vmax}\") elif",
"raise AssertionError(f\"expected {vmin}<{label}<{vmax}\") def ert_in_dtype(x, dtype): if dtype.startswith(\"f\"): if x > np.finfo(dtype).max: raise",
"0: raise AssertionError(f\"{label} should be greater than 0\") elif x < 0: raise",
"else: logging.warning(f\"assert not implemented for dtype '{dtype}'\") def enable_rich_assert(fun: Callable) -> Callable: def",
"logging import numpy as np # type: ignore import sys from typing import",
"AssertionError(f\"{label} should be one of {types}, {type(x)} instead\") def ert_nonNeg(x, label, include_zero=False): if",
"instead\") def ert_multiTypes(x, types, label): cond = any(isinstance(x, t) for t in types)",
"dtype): if dtype.startswith(\"f\"): if x > np.finfo(dtype).max: raise AssertionError( \" \".join( [ \"expected",
"leftClose: if rightClose: if x < vmin or x > vmax: raise AssertionError(f\"expected",
"or x >= vmax: raise AssertionError(f\"expected {vmin}<={label}<{vmax}\") elif rightClose: if x <= vmin",
"should be greater than 0\") elif x < 0: raise AssertionError(f\"{label} should be",
"< {np.finfo(dtype).max}\", ] ) ) elif dtype.startswith(\"u\") or dtype.startswith(\"i\"): if x > np.iinfo(dtype).max:",
"t in types) if not cond: raise AssertionError(f\"{label} should be one of {types},",
"dtype.startswith(\"i\"): if x > np.iinfo(dtype).max: raise AssertionError( \" \".join( [ \"expected to be",
"<= vmin or x >= vmax: raise AssertionError(f\"expected {vmin}<{label}<{vmax}\") def ert_in_dtype(x, dtype): if",
"x > vmax: raise AssertionError(f\"expected {vmin}<{label}<={vmax}\") elif x <= vmin or x >=",
"not cond: raise AssertionError(f\"{label} should be one of {types}, {type(x)} instead\") def ert_nonNeg(x,",
"ert_in_dtype(x, dtype): if dtype.startswith(\"f\"): if x > np.finfo(dtype).max: raise AssertionError( \" \".join( [",
"if x > np.iinfo(dtype).max: raise AssertionError( \" \".join( [ \"expected to be lower",
"x >= vmax: raise AssertionError(f\"expected {vmin}<{label}<{vmax}\") def ert_in_dtype(x, dtype): if dtype.startswith(\"f\"): if x",
"{type(x)} instead\") def ert_multiTypes(x, types, label): cond = any(isinstance(x, t) for t in",
"elif x <= vmin or x >= vmax: raise AssertionError(f\"expected {vmin}<{label}<{vmax}\") def ert_in_dtype(x,",
"<= 0: raise AssertionError(f\"{label} should be greater than 0\") elif x < 0:",
"Callable) -> Callable: def wrapper(*args, **kwargs): try: return fun(*args, **kwargs) except AssertionError as",
"np # type: ignore import sys from typing import Callable def ert_type(x, stype,",
"# type: ignore import sys from typing import Callable def ert_type(x, stype, label):",
"one of {types}, {type(x)} instead\") def ert_nonNeg(x, label, include_zero=False): if not include_zero: if",
"> np.finfo(dtype).max: raise AssertionError( \" \".join( [ \"expected to be lower than {dtype}",
"if rightClose: if x < vmin or x > vmax: raise AssertionError(f\"expected {vmin}<={label}<={vmax}\")",
"vmax: raise AssertionError(f\"expected {vmin}<={label}<={vmax}\") elif x < vmin or x >= vmax: raise",
"stype): raise AssertionError(f\"{label} should be {stype}, {type(x)} instead\") def ert_multiTypes(x, types, label): cond",
"def ert_multiTypes(x, types, label): cond = any(isinstance(x, t) for t in types) if",
"{vmin}<={label}<{vmax}\") elif rightClose: if x <= vmin or x > vmax: raise AssertionError(f\"expected",
"\"\"\" @author: <NAME> @contact: <EMAIL> \"\"\" import logging import numpy as np #",
"cond: raise AssertionError(f\"{label} should be one of {types}, {type(x)} instead\") def ert_nonNeg(x, label,",
"isinstance(x, stype): raise AssertionError(f\"{label} should be {stype}, {type(x)} instead\") def ert_multiTypes(x, types, label):",
"numpy as np # type: ignore import sys from typing import Callable def",
"{types}, {type(x)} instead\") def ert_nonNeg(x, label, include_zero=False): if not include_zero: if x <=",
"AssertionError(f\"{label} should be {stype}, {type(x)} instead\") def ert_multiTypes(x, types, label): cond = any(isinstance(x,",
"rightClose: if x < vmin or x > vmax: raise AssertionError(f\"expected {vmin}<={label}<={vmax}\") elif",
"elif dtype.startswith(\"u\") or dtype.startswith(\"i\"): if x > np.iinfo(dtype).max: raise AssertionError( \" \".join( [",
"if x > np.finfo(dtype).max: raise AssertionError( \" \".join( [ \"expected to be lower",
"cond = any(isinstance(x, t) for t in types) if not cond: raise AssertionError(f\"{label}",
"x <= vmin or x >= vmax: raise AssertionError(f\"expected {vmin}<{label}<{vmax}\") def ert_in_dtype(x, dtype):",
"should be one of {types}, {type(x)} instead\") def ert_nonNeg(x, label, include_zero=False): if not",
"for dtype '{dtype}'\") def enable_rich_assert(fun: Callable) -> Callable: def wrapper(*args, **kwargs): try: return",
"to 0\") def ert_inInterv(x, vmin, vmax, label, leftClose=False, rightClose=True): if leftClose: if rightClose:",
"elif x < 0: raise AssertionError(f\"{label} should be greater than or equal to",
"vmin or x >= vmax: raise AssertionError(f\"expected {vmin}<={label}<{vmax}\") elif rightClose: if x <=",
"AssertionError( \" \".join( [ \"expected to be lower than {dtype} max:\", f\"{x} <",
"{np.iinfo(dtype).max}\", ] ) ) else: logging.warning(f\"assert not implemented for dtype '{dtype}'\") def enable_rich_assert(fun:",
"leftClose=False, rightClose=True): if leftClose: if rightClose: if x < vmin or x >",
">= vmax: raise AssertionError(f\"expected {vmin}<={label}<{vmax}\") elif rightClose: if x <= vmin or x",
"< {np.iinfo(dtype).max}\", ] ) ) else: logging.warning(f\"assert not implemented for dtype '{dtype}'\") def",
"ignore import sys from typing import Callable def ert_type(x, stype, label): if not",
"as np # type: ignore import sys from typing import Callable def ert_type(x,",
"or dtype.startswith(\"i\"): if x > np.iinfo(dtype).max: raise AssertionError( \" \".join( [ \"expected to",
"than 0\") elif x < 0: raise AssertionError(f\"{label} should be greater than or",
"> np.iinfo(dtype).max: raise AssertionError( \" \".join( [ \"expected to be lower than {dtype}",
"@contact: <EMAIL> \"\"\" import logging import numpy as np # type: ignore import",
"0\") elif x < 0: raise AssertionError(f\"{label} should be greater than or equal",
"def ert_inInterv(x, vmin, vmax, label, leftClose=False, rightClose=True): if leftClose: if rightClose: if x",
"x > np.finfo(dtype).max: raise AssertionError( \" \".join( [ \"expected to be lower than",
"{type(x)} instead\") def ert_nonNeg(x, label, include_zero=False): if not include_zero: if x <= 0:",
"be lower than {dtype} max:\", f\"{x} < {np.iinfo(dtype).max}\", ] ) ) else: logging.warning(f\"assert",
"x < vmin or x >= vmax: raise AssertionError(f\"expected {vmin}<={label}<{vmax}\") elif rightClose: if",
"dtype '{dtype}'\") def enable_rich_assert(fun: Callable) -> Callable: def wrapper(*args, **kwargs): try: return fun(*args,",
"def ert_in_dtype(x, dtype): if dtype.startswith(\"f\"): if x > np.finfo(dtype).max: raise AssertionError( \" \".join(",
"include_zero: if x <= 0: raise AssertionError(f\"{label} should be greater than 0\") elif",
"<= vmin or x > vmax: raise AssertionError(f\"expected {vmin}<{label}<={vmax}\") elif x <= vmin",
"dtype.startswith(\"u\") or dtype.startswith(\"i\"): if x > np.iinfo(dtype).max: raise AssertionError( \" \".join( [ \"expected",
"label, include_zero=False): if not include_zero: if x <= 0: raise AssertionError(f\"{label} should be",
"be {stype}, {type(x)} instead\") def ert_multiTypes(x, types, label): cond = any(isinstance(x, t) for",
"x > vmax: raise AssertionError(f\"expected {vmin}<={label}<={vmax}\") elif x < vmin or x >=",
"types) if not cond: raise AssertionError(f\"{label} should be one of {types}, {type(x)} instead\")",
"vmin or x >= vmax: raise AssertionError(f\"expected {vmin}<{label}<{vmax}\") def ert_in_dtype(x, dtype): if dtype.startswith(\"f\"):",
"ert_multiTypes(x, types, label): cond = any(isinstance(x, t) for t in types) if not",
"logging.warning(f\"assert not implemented for dtype '{dtype}'\") def enable_rich_assert(fun: Callable) -> Callable: def wrapper(*args,",
"if not include_zero: if x <= 0: raise AssertionError(f\"{label} should be greater than",
"max:\", f\"{x} < {np.iinfo(dtype).max}\", ] ) ) else: logging.warning(f\"assert not implemented for dtype",
"types, label): cond = any(isinstance(x, t) for t in types) if not cond:",
"elif x < vmin or x >= vmax: raise AssertionError(f\"expected {vmin}<={label}<{vmax}\") elif rightClose:",
"ert_nonNeg(x, label, include_zero=False): if not include_zero: if x <= 0: raise AssertionError(f\"{label} should",
"if x <= 0: raise AssertionError(f\"{label} should be greater than 0\") elif x",
"to be lower than {dtype} max:\", f\"{x} < {np.finfo(dtype).max}\", ] ) ) elif",
"include_zero=False): if not include_zero: if x <= 0: raise AssertionError(f\"{label} should be greater",
"x > np.iinfo(dtype).max: raise AssertionError( \" \".join( [ \"expected to be lower than",
"vmin, vmax, label, leftClose=False, rightClose=True): if leftClose: if rightClose: if x < vmin",
"vmax: raise AssertionError(f\"expected {vmin}<{label}<={vmax}\") elif x <= vmin or x >= vmax: raise",
"max:\", f\"{x} < {np.finfo(dtype).max}\", ] ) ) elif dtype.startswith(\"u\") or dtype.startswith(\"i\"): if x",
"AssertionError(f\"expected {vmin}<{label}<{vmax}\") def ert_in_dtype(x, dtype): if dtype.startswith(\"f\"): if x > np.finfo(dtype).max: raise AssertionError(",
"vmax: raise AssertionError(f\"expected {vmin}<{label}<{vmax}\") def ert_in_dtype(x, dtype): if dtype.startswith(\"f\"): if x > np.finfo(dtype).max:",
"] ) ) elif dtype.startswith(\"u\") or dtype.startswith(\"i\"): if x > np.iinfo(dtype).max: raise AssertionError(",
"raise AssertionError(f\"expected {vmin}<={label}<={vmax}\") elif x < vmin or x >= vmax: raise AssertionError(f\"expected",
"{vmin}<{label}<={vmax}\") elif x <= vmin or x >= vmax: raise AssertionError(f\"expected {vmin}<{label}<{vmax}\") def",
"f\"{x} < {np.iinfo(dtype).max}\", ] ) ) else: logging.warning(f\"assert not implemented for dtype '{dtype}'\")",
"0: raise AssertionError(f\"{label} should be greater than or equal to 0\") def ert_inInterv(x,",
"np.finfo(dtype).max: raise AssertionError( \" \".join( [ \"expected to be lower than {dtype} max:\",",
"wrapper(*args, **kwargs): try: return fun(*args, **kwargs) except AssertionError as e: logging.exception(e) sys.exit() return",
"not isinstance(x, stype): raise AssertionError(f\"{label} should be {stype}, {type(x)} instead\") def ert_multiTypes(x, types,",
"raise AssertionError(f\"{label} should be greater than or equal to 0\") def ert_inInterv(x, vmin,",
"AssertionError(f\"{label} should be greater than or equal to 0\") def ert_inInterv(x, vmin, vmax,",
"raise AssertionError(f\"{label} should be greater than 0\") elif x < 0: raise AssertionError(f\"{label}",
"greater than or equal to 0\") def ert_inInterv(x, vmin, vmax, label, leftClose=False, rightClose=True):",
"ert_type(x, stype, label): if not isinstance(x, stype): raise AssertionError(f\"{label} should be {stype}, {type(x)}",
"AssertionError(f\"expected {vmin}<{label}<={vmax}\") elif x <= vmin or x >= vmax: raise AssertionError(f\"expected {vmin}<{label}<{vmax}\")",
"\".join( [ \"expected to be lower than {dtype} max:\", f\"{x} < {np.finfo(dtype).max}\", ]",
"< vmin or x >= vmax: raise AssertionError(f\"expected {vmin}<={label}<{vmax}\") elif rightClose: if x",
"-> Callable: def wrapper(*args, **kwargs): try: return fun(*args, **kwargs) except AssertionError as e:",
"type: ignore import sys from typing import Callable def ert_type(x, stype, label): if",
"label, leftClose=False, rightClose=True): if leftClose: if rightClose: if x < vmin or x",
"vmax: raise AssertionError(f\"expected {vmin}<={label}<{vmax}\") elif rightClose: if x <= vmin or x >",
"from typing import Callable def ert_type(x, stype, label): if not isinstance(x, stype): raise",
"greater than 0\") elif x < 0: raise AssertionError(f\"{label} should be greater than",
"\" \".join( [ \"expected to be lower than {dtype} max:\", f\"{x} < {np.iinfo(dtype).max}\",",
"implemented for dtype '{dtype}'\") def enable_rich_assert(fun: Callable) -> Callable: def wrapper(*args, **kwargs): try:",
"{stype}, {type(x)} instead\") def ert_multiTypes(x, types, label): cond = any(isinstance(x, t) for t",
"x < vmin or x > vmax: raise AssertionError(f\"expected {vmin}<={label}<={vmax}\") elif x <",
"enable_rich_assert(fun: Callable) -> Callable: def wrapper(*args, **kwargs): try: return fun(*args, **kwargs) except AssertionError",
"or equal to 0\") def ert_inInterv(x, vmin, vmax, label, leftClose=False, rightClose=True): if leftClose:",
"{vmin}<={label}<={vmax}\") elif x < vmin or x >= vmax: raise AssertionError(f\"expected {vmin}<={label}<{vmax}\") elif",
"> vmax: raise AssertionError(f\"expected {vmin}<={label}<={vmax}\") elif x < vmin or x >= vmax:",
"label): if not isinstance(x, stype): raise AssertionError(f\"{label} should be {stype}, {type(x)} instead\") def",
"x <= vmin or x > vmax: raise AssertionError(f\"expected {vmin}<{label}<={vmax}\") elif x <=",
"> vmax: raise AssertionError(f\"expected {vmin}<{label}<={vmax}\") elif x <= vmin or x >= vmax:",
"def enable_rich_assert(fun: Callable) -> Callable: def wrapper(*args, **kwargs): try: return fun(*args, **kwargs) except",
"< vmin or x > vmax: raise AssertionError(f\"expected {vmin}<={label}<={vmax}\") elif x < vmin",
"or x > vmax: raise AssertionError(f\"expected {vmin}<{label}<={vmax}\") elif x <= vmin or x",
"if leftClose: if rightClose: if x < vmin or x > vmax: raise",
"@author: <NAME> @contact: <EMAIL> \"\"\" import logging import numpy as np # type:",
"vmax, label, leftClose=False, rightClose=True): if leftClose: if rightClose: if x < vmin or",
"] ) ) else: logging.warning(f\"assert not implemented for dtype '{dtype}'\") def enable_rich_assert(fun: Callable)",
"import sys from typing import Callable def ert_type(x, stype, label): if not isinstance(x,",
"Callable def ert_type(x, stype, label): if not isinstance(x, stype): raise AssertionError(f\"{label} should be",
"Callable: def wrapper(*args, **kwargs): try: return fun(*args, **kwargs) except AssertionError as e: logging.exception(e)",
"= any(isinstance(x, t) for t in types) if not cond: raise AssertionError(f\"{label} should",
"<EMAIL> \"\"\" import logging import numpy as np # type: ignore import sys",
"0\") def ert_inInterv(x, vmin, vmax, label, leftClose=False, rightClose=True): if leftClose: if rightClose: if",
"should be greater than or equal to 0\") def ert_inInterv(x, vmin, vmax, label,"
] |
[
"method. \"\"\" def __init__(self, model): self.model = model def predict(self, X): \"\"\"Wraps the",
"files], key=str.lower) def apk(actual, predicted, k=3): \"\"\" Source: https://github.com/benhamner/Metrics/blob/master/Python/ml_metrics/average_precision.py \"\"\" if len(predicted) >",
"+= num_hits / (i + 1.0) if not actual: return 0.0 return score",
"y_pred, k=3) def draw_cv2(raw_strokes, size=256, lw=6, time_color=True): img = np.zeros((BASE_SIZE, BASE_SIZE), np.uint8) for",
"x = preprocess_input(x).astype(np.float32) y = keras.utils.to_categorical(df.y, num_classes=NCATS) yield x, y def df_to_image_array_xd(df, size,",
"= preprocess_input(x).astype(np.float32) return x class TTA_ModelWrapper(): \"\"\"A simple TTA wrapper for keras computer",
":, :] = draw_cv2(raw_strokes, size=size, lw=lw, time_color=time_color) x = preprocess_input(x).astype(np.float32) y = keras.utils.to_categorical(df.y,",
"= self.model.predict(np.flipud(X), batch_size=128, verbose=1) p = (p0 + p1) / 2 return np.array(p)",
"img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) if size != BASE_SIZE: return cv2.resize(img, (size, size)) else:",
"p in enumerate(predicted): if p in actual and p not in predicted[:i]: num_hits",
"draw_cv2( raw_strokes, size=size, lw=lw, time_color=time_color) x = preprocess_input(x).astype(np.float32) return x class TTA_ModelWrapper(): \"\"\"A",
"def df_to_image_array_xd(df, size, lw=6, time_color=True): df['drawing'] = df['drawing'].apply(ast.literal_eval) x = np.zeros((len(df), size, size,",
"not in predicted[:i]: num_hits += 1.0 score += num_hits / (i + 1.0)",
"p in zip(actual, predicted)]) def preds2catids(predictions): return pd.DataFrame(np.argsort(-predictions, axis=1)[:, :3], columns=['a', 'b', 'c'])",
"sorted([f2cat(f) for f in files], key=str.lower) def apk(actual, predicted, k=3): \"\"\" Source: https://github.com/benhamner/Metrics/blob/master/Python/ml_metrics/average_precision.py",
"The data to get predictions for. \"\"\" p0 = self.model.predict(X, batch_size=128, verbose=1) p1",
"vision models. Args: model (keras model): A fitted keras model with a predict",
"raw_strokes, size=size, lw=lw, time_color=time_color) x = preprocess_input(x).astype(np.float32) return x class TTA_ModelWrapper(): \"\"\"A simple",
"size=size, lw=lw, time_color=time_color) x = preprocess_input(x).astype(np.float32) return x class TTA_ModelWrapper(): \"\"\"A simple TTA",
"actual: return 0.0 return score / min(len(actual), k) def mapk(actual, predicted, k=3): \"\"\"",
"size=size, lw=lw, time_color=time_color) x = preprocess_input(x).astype(np.float32) y = keras.utils.to_categorical(df.y, num_classes=NCATS) yield x, y",
"in zip(actual, predicted)]) def preds2catids(predictions): return pd.DataFrame(np.argsort(-predictions, axis=1)[:, :3], columns=['a', 'b', 'c']) def",
"num_hits += 1.0 score += num_hits / (i + 1.0) if not actual:",
"score += num_hits / (i + 1.0) if not actual: return 0.0 return",
"get predictions for. \"\"\" p0 = self.model.predict(X, batch_size=128, verbose=1) p1 = self.model.predict(np.flipud(X), batch_size=128,",
"True: for k in np.random.permutation(ks): filename = os.path.join(DP_DIR, 'train_k{}.csv.gz'.format(k)) for df in pd.read_csv(filename,",
"p in actual and p not in predicted[:i]: num_hits += 1.0 score +=",
"'train_k{}.csv.gz'.format(k)) for df in pd.read_csv(filename, chunksize=batchsize): df['drawing'] = df['drawing'].apply(ast.literal_eval) x = np.zeros((len(df), size,",
"simple TTA wrapper for keras computer vision models. Args: model (keras model): A",
"for i in range(len(stroke[0]) - 1): color = 255 - min(t, 10) *",
"DP_DIR = './input/shuffle-csvs/' INPUT_DIR = './input/quickdraw-doodle-recognition/' BASE_SIZE = 256 NCSVS = 200 NCATS",
"and averages the results. Args: X (numpy array of dim 4): The data",
"os import cv2 import numpy as np import pandas as pd import tensorflow",
"-> str: return filename.split('.')[0] def list_all_categories(): files = os.listdir(os.path.join(INPUT_DIR, 'train_simplified')) return sorted([f2cat(f) for",
"df in pd.read_csv(filename, chunksize=batchsize): df['drawing'] = df['drawing'].apply(ast.literal_eval) x = np.zeros((len(df), size, size, 3))",
"import os import cv2 import numpy as np import pandas as pd import",
"preprocess_input(x).astype(np.float32) y = keras.utils.to_categorical(df.y, num_classes=NCATS) yield x, y def df_to_image_array_xd(df, size, lw=6, time_color=True):",
"= draw_cv2(raw_strokes, size=size, lw=lw, time_color=time_color) x = preprocess_input(x).astype(np.float32) y = keras.utils.to_categorical(df.y, num_classes=NCATS) yield",
"enumerate(predicted): if p in actual and p not in predicted[:i]: num_hits += 1.0",
"/ min(len(actual), k) def mapk(actual, predicted, k=3): \"\"\" Source: https://github.com/benhamner/Metrics/blob/master/Python/ml_metrics/average_precision.py \"\"\" return np.mean([apk(a,",
":, :] = draw_cv2( raw_strokes, size=size, lw=lw, time_color=time_color) x = preprocess_input(x).astype(np.float32) return x",
"'./input/shuffle-csvs/' INPUT_DIR = './input/quickdraw-doodle-recognition/' BASE_SIZE = 256 NCSVS = 200 NCATS = 340",
"def __init__(self, model): self.model = model def predict(self, X): \"\"\"Wraps the predict method",
"def apk(actual, predicted, k=3): \"\"\" Source: https://github.com/benhamner/Metrics/blob/master/Python/ml_metrics/average_precision.py \"\"\" if len(predicted) > k: predicted",
"lw=6, time_color=True): df['drawing'] = df['drawing'].apply(ast.literal_eval) x = np.zeros((len(df), size, size, 3)) for i,",
"keras computer vision models. Args: model (keras model): A fitted keras model with",
"size=256, lw=6, time_color=True): img = np.zeros((BASE_SIZE, BASE_SIZE), np.uint8) for t, stroke in enumerate(raw_strokes):",
"else 255 _ = cv2.line(img, (stroke[0][i], stroke[1][i]), (stroke[0][i + 1], stroke[1][i + 1]),",
"'train_simplified')) return sorted([f2cat(f) for f in files], key=str.lower) def apk(actual, predicted, k=3): \"\"\"",
"import Model, load_model DP_DIR = './input/shuffle-csvs/' INPUT_DIR = './input/quickdraw-doodle-recognition/' BASE_SIZE = 256 NCSVS",
"score / min(len(actual), k) def mapk(actual, predicted, k=3): \"\"\" Source: https://github.com/benhamner/Metrics/blob/master/Python/ml_metrics/average_precision.py \"\"\" return",
"lw=6, time_color=True): img = np.zeros((BASE_SIZE, BASE_SIZE), np.uint8) for t, stroke in enumerate(raw_strokes): for",
"p0 = self.model.predict(X, batch_size=128, verbose=1) p1 = self.model.predict(np.flipud(X), batch_size=128, verbose=1) p = (p0",
"x, y def df_to_image_array_xd(df, size, lw=6, time_color=True): df['drawing'] = df['drawing'].apply(ast.literal_eval) x = np.zeros((len(df),",
"= self.model.predict(X, batch_size=128, verbose=1) p1 = self.model.predict(np.flipud(X), batch_size=128, verbose=1) p = (p0 +",
"return cv2.resize(img, (size, size)) else: return img def image_generator_xd(size, batchsize, ks, lw=6, time_color=True):",
"return filename.split('.')[0] def list_all_categories(): files = os.listdir(os.path.join(INPUT_DIR, 'train_simplified')) return sorted([f2cat(f) for f in",
"color, lw) img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) if size != BASE_SIZE: return cv2.resize(img, (size,",
"def preds2catids(predictions): return pd.DataFrame(np.argsort(-predictions, axis=1)[:, :3], columns=['a', 'b', 'c']) def top_3_accuracy(y_true, y_pred): return",
"time_color=True): df['drawing'] = df['drawing'].apply(ast.literal_eval) x = np.zeros((len(df), size, size, 3)) for i, raw_strokes",
"= draw_cv2( raw_strokes, size=size, lw=lw, time_color=time_color) x = preprocess_input(x).astype(np.float32) return x class TTA_ModelWrapper():",
"return x class TTA_ModelWrapper(): \"\"\"A simple TTA wrapper for keras computer vision models.",
"computer vision models. Args: model (keras model): A fitted keras model with a",
"zip(actual, predicted)]) def preds2catids(predictions): return pd.DataFrame(np.argsort(-predictions, axis=1)[:, :3], columns=['a', 'b', 'c']) def top_3_accuracy(y_true,",
"255 - min(t, 10) * 13 if time_color else 255 _ = cv2.line(img,",
"for i, raw_strokes in enumerate(df.drawing.values): x[i, :, :, :] = draw_cv2( raw_strokes, size=size,",
"k=3): \"\"\" Source: https://github.com/benhamner/Metrics/blob/master/Python/ml_metrics/average_precision.py \"\"\" return np.mean([apk(a, p, k) for a, p in",
"df_to_image_array_xd(df, size, lw=6, time_color=True): df['drawing'] = df['drawing'].apply(ast.literal_eval) x = np.zeros((len(df), size, size, 3))",
"255 _ = cv2.line(img, (stroke[0][i], stroke[1][i]), (stroke[0][i + 1], stroke[1][i + 1]), color,",
"> k: predicted = predicted[:k] score = 0.0 num_hits = 0.0 for i,",
"Model, load_model DP_DIR = './input/shuffle-csvs/' INPUT_DIR = './input/quickdraw-doodle-recognition/' BASE_SIZE = 256 NCSVS =",
"in enumerate(df.drawing.values): x[i, :, :, :] = draw_cv2( raw_strokes, size=size, lw=lw, time_color=time_color) x",
"df['drawing'].apply(ast.literal_eval) x = np.zeros((len(df), size, size, 3)) for i, raw_strokes in enumerate(df.drawing.values): x[i,",
"\"\"\"A simple TTA wrapper for keras computer vision models. Args: model (keras model):",
"flips and averages the results. Args: X (numpy array of dim 4): The",
"\"\"\" if len(predicted) > k: predicted = predicted[:k] score = 0.0 num_hits =",
"tensorflow import keras from keras.applications.densenet import preprocess_input from keras.metrics import (categorical_accuracy, top_k_categorical_accuracy) from",
"predicted[:k] score = 0.0 num_hits = 0.0 for i, p in enumerate(predicted): if",
"self.model = model def predict(self, X): \"\"\"Wraps the predict method of the provided",
"predict(self, X): \"\"\"Wraps the predict method of the provided model. Augments the testdata",
":] = draw_cv2(raw_strokes, size=size, lw=lw, time_color=time_color) x = preprocess_input(x).astype(np.float32) y = keras.utils.to_categorical(df.y, num_classes=NCATS)",
"= 200 NCATS = 340 np.random.seed(seed=2018) tf.set_random_seed(seed=2018) def f2cat(filename: str) -> str: return",
"i in range(len(stroke[0]) - 1): color = 255 - min(t, 10) * 13",
"the results. Args: X (numpy array of dim 4): The data to get",
"num_classes=NCATS) yield x, y def df_to_image_array_xd(df, size, lw=6, time_color=True): df['drawing'] = df['drawing'].apply(ast.literal_eval) x",
"time_color=True): img = np.zeros((BASE_SIZE, BASE_SIZE), np.uint8) for t, stroke in enumerate(raw_strokes): for i",
"for k in np.random.permutation(ks): filename = os.path.join(DP_DIR, 'train_k{}.csv.gz'.format(k)) for df in pd.read_csv(filename, chunksize=batchsize):",
"apk(actual, predicted, k=3): \"\"\" Source: https://github.com/benhamner/Metrics/blob/master/Python/ml_metrics/average_precision.py \"\"\" if len(predicted) > k: predicted =",
"the provided model. Augments the testdata with horizontal and vertical flips and averages",
"score = 0.0 num_hits = 0.0 for i, p in enumerate(predicted): if p",
"return sorted([f2cat(f) for f in files], key=str.lower) def apk(actual, predicted, k=3): \"\"\" Source:",
"if len(predicted) > k: predicted = predicted[:k] score = 0.0 num_hits = 0.0",
"(stroke[0][i], stroke[1][i]), (stroke[0][i + 1], stroke[1][i + 1]), color, lw) img = cv2.cvtColor(img,",
"https://github.com/benhamner/Metrics/blob/master/Python/ml_metrics/average_precision.py \"\"\" if len(predicted) > k: predicted = predicted[:k] score = 0.0 num_hits",
"def f2cat(filename: str) -> str: return filename.split('.')[0] def list_all_categories(): files = os.listdir(os.path.join(INPUT_DIR, 'train_simplified'))",
"= df['drawing'].apply(ast.literal_eval) x = np.zeros((len(df), size, size, 3)) for i, raw_strokes in enumerate(df.drawing.values):",
"model): A fitted keras model with a predict method. \"\"\" def __init__(self, model):",
"np.mean([apk(a, p, k) for a, p in zip(actual, predicted)]) def preds2catids(predictions): return pd.DataFrame(np.argsort(-predictions,",
"'b', 'c']) def top_3_accuracy(y_true, y_pred): return top_k_categorical_accuracy(y_true, y_pred, k=3) def draw_cv2(raw_strokes, size=256, lw=6,",
"wrapper for keras computer vision models. Args: model (keras model): A fitted keras",
"in enumerate(df.drawing.values): x[i, :, :, :] = draw_cv2(raw_strokes, size=size, lw=lw, time_color=time_color) x =",
"size, 3)) for i, raw_strokes in enumerate(df.drawing.values): x[i, :, :, :] = draw_cv2(",
"df['drawing'] = df['drawing'].apply(ast.literal_eval) x = np.zeros((len(df), size, size, 3)) for i, raw_strokes in",
"\"\"\" def __init__(self, model): self.model = model def predict(self, X): \"\"\"Wraps the predict",
"provided model. Augments the testdata with horizontal and vertical flips and averages the",
"horizontal and vertical flips and averages the results. Args: X (numpy array of",
"def list_all_categories(): files = os.listdir(os.path.join(INPUT_DIR, 'train_simplified')) return sorted([f2cat(f) for f in files], key=str.lower)",
"pd.read_csv(filename, chunksize=batchsize): df['drawing'] = df['drawing'].apply(ast.literal_eval) x = np.zeros((len(df), size, size, 3)) for i,",
"size, size, 3)) for i, raw_strokes in enumerate(df.drawing.values): x[i, :, :, :] =",
"1], stroke[1][i + 1]), color, lw) img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) if size !=",
"+= 1.0 score += num_hits / (i + 1.0) if not actual: return",
"batch_size=128, verbose=1) p1 = self.model.predict(np.flipud(X), batch_size=128, verbose=1) p = (p0 + p1) /",
"top_k_categorical_accuracy(y_true, y_pred, k=3) def draw_cv2(raw_strokes, size=256, lw=6, time_color=True): img = np.zeros((BASE_SIZE, BASE_SIZE), np.uint8)",
"models. Args: model (keras model): A fitted keras model with a predict method.",
"files = os.listdir(os.path.join(INPUT_DIR, 'train_simplified')) return sorted([f2cat(f) for f in files], key=str.lower) def apk(actual,",
"_ = cv2.line(img, (stroke[0][i], stroke[1][i]), (stroke[0][i + 1], stroke[1][i + 1]), color, lw)",
"4): The data to get predictions for. \"\"\" p0 = self.model.predict(X, batch_size=128, verbose=1)",
"if time_color else 255 _ = cv2.line(img, (stroke[0][i], stroke[1][i]), (stroke[0][i + 1], stroke[1][i",
"and p not in predicted[:i]: num_hits += 1.0 score += num_hits / (i",
"image_generator_xd(size, batchsize, ks, lw=6, time_color=True): while True: for k in np.random.permutation(ks): filename =",
"raw_strokes in enumerate(df.drawing.values): x[i, :, :, :] = draw_cv2( raw_strokes, size=size, lw=lw, time_color=time_color)",
":] = draw_cv2( raw_strokes, size=size, lw=lw, time_color=time_color) x = preprocess_input(x).astype(np.float32) return x class",
"else: return img def image_generator_xd(size, batchsize, ks, lw=6, time_color=True): while True: for k",
"\"\"\" Source: https://github.com/benhamner/Metrics/blob/master/Python/ml_metrics/average_precision.py \"\"\" if len(predicted) > k: predicted = predicted[:k] score =",
"with a predict method. \"\"\" def __init__(self, model): self.model = model def predict(self,",
"NCSVS = 200 NCATS = 340 np.random.seed(seed=2018) tf.set_random_seed(seed=2018) def f2cat(filename: str) -> str:",
"p1 = self.model.predict(np.flipud(X), batch_size=128, verbose=1) p = (p0 + p1) / 2 return",
"1): color = 255 - min(t, 10) * 13 if time_color else 255",
"f in files], key=str.lower) def apk(actual, predicted, k=3): \"\"\" Source: https://github.com/benhamner/Metrics/blob/master/Python/ml_metrics/average_precision.py \"\"\" if",
"method of the provided model. Augments the testdata with horizontal and vertical flips",
"import (categorical_accuracy, top_k_categorical_accuracy) from keras.models import Model, load_model DP_DIR = './input/shuffle-csvs/' INPUT_DIR =",
"X (numpy array of dim 4): The data to get predictions for. \"\"\"",
"0.0 return score / min(len(actual), k) def mapk(actual, predicted, k=3): \"\"\" Source: https://github.com/benhamner/Metrics/blob/master/Python/ml_metrics/average_precision.py",
"os.listdir(os.path.join(INPUT_DIR, 'train_simplified')) return sorted([f2cat(f) for f in files], key=str.lower) def apk(actual, predicted, k=3):",
"X): \"\"\"Wraps the predict method of the provided model. Augments the testdata with",
"testdata with horizontal and vertical flips and averages the results. Args: X (numpy",
"= 256 NCSVS = 200 NCATS = 340 np.random.seed(seed=2018) tf.set_random_seed(seed=2018) def f2cat(filename: str)",
"(size, size)) else: return img def image_generator_xd(size, batchsize, ks, lw=6, time_color=True): while True:",
":3], columns=['a', 'b', 'c']) def top_3_accuracy(y_true, y_pred): return top_k_categorical_accuracy(y_true, y_pred, k=3) def draw_cv2(raw_strokes,",
"a, p in zip(actual, predicted)]) def preds2catids(predictions): return pd.DataFrame(np.argsort(-predictions, axis=1)[:, :3], columns=['a', 'b',",
"not actual: return 0.0 return score / min(len(actual), k) def mapk(actual, predicted, k=3):",
"keras.models import Model, load_model DP_DIR = './input/shuffle-csvs/' INPUT_DIR = './input/quickdraw-doodle-recognition/' BASE_SIZE = 256",
"(keras model): A fitted keras model with a predict method. \"\"\" def __init__(self,",
"if size != BASE_SIZE: return cv2.resize(img, (size, size)) else: return img def image_generator_xd(size,",
"x = preprocess_input(x).astype(np.float32) return x class TTA_ModelWrapper(): \"\"\"A simple TTA wrapper for keras",
"y = keras.utils.to_categorical(df.y, num_classes=NCATS) yield x, y def df_to_image_array_xd(df, size, lw=6, time_color=True): df['drawing']",
"str) -> str: return filename.split('.')[0] def list_all_categories(): files = os.listdir(os.path.join(INPUT_DIR, 'train_simplified')) return sorted([f2cat(f)",
"from keras.metrics import (categorical_accuracy, top_k_categorical_accuracy) from keras.models import Model, load_model DP_DIR = './input/shuffle-csvs/'",
"np.random.permutation(ks): filename = os.path.join(DP_DIR, 'train_k{}.csv.gz'.format(k)) for df in pd.read_csv(filename, chunksize=batchsize): df['drawing'] = df['drawing'].apply(ast.literal_eval)",
"= keras.utils.to_categorical(df.y, num_classes=NCATS) yield x, y def df_to_image_array_xd(df, size, lw=6, time_color=True): df['drawing'] =",
"i, p in enumerate(predicted): if p in actual and p not in predicted[:i]:",
"and vertical flips and averages the results. Args: X (numpy array of dim",
"draw_cv2(raw_strokes, size=size, lw=lw, time_color=time_color) x = preprocess_input(x).astype(np.float32) y = keras.utils.to_categorical(df.y, num_classes=NCATS) yield x,",
"lw=lw, time_color=time_color) x = preprocess_input(x).astype(np.float32) y = keras.utils.to_categorical(df.y, num_classes=NCATS) yield x, y def",
"model with a predict method. \"\"\" def __init__(self, model): self.model = model def",
"of dim 4): The data to get predictions for. \"\"\" p0 = self.model.predict(X,",
"stroke in enumerate(raw_strokes): for i in range(len(stroke[0]) - 1): color = 255 -",
"f2cat(filename: str) -> str: return filename.split('.')[0] def list_all_categories(): files = os.listdir(os.path.join(INPUT_DIR, 'train_simplified')) return",
"256 NCSVS = 200 NCATS = 340 np.random.seed(seed=2018) tf.set_random_seed(seed=2018) def f2cat(filename: str) ->",
"/ (i + 1.0) if not actual: return 0.0 return score / min(len(actual),",
"return np.mean([apk(a, p, k) for a, p in zip(actual, predicted)]) def preds2catids(predictions): return",
"enumerate(raw_strokes): for i in range(len(stroke[0]) - 1): color = 255 - min(t, 10)",
"i, raw_strokes in enumerate(df.drawing.values): x[i, :, :, :] = draw_cv2(raw_strokes, size=size, lw=lw, time_color=time_color)",
"predict method of the provided model. Augments the testdata with horizontal and vertical",
"averages the results. Args: X (numpy array of dim 4): The data to",
"x[i, :, :, :] = draw_cv2( raw_strokes, size=size, lw=lw, time_color=time_color) x = preprocess_input(x).astype(np.float32)",
"k) def mapk(actual, predicted, k=3): \"\"\" Source: https://github.com/benhamner/Metrics/blob/master/Python/ml_metrics/average_precision.py \"\"\" return np.mean([apk(a, p, k)",
"load_model DP_DIR = './input/shuffle-csvs/' INPUT_DIR = './input/quickdraw-doodle-recognition/' BASE_SIZE = 256 NCSVS = 200",
"lw) img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) if size != BASE_SIZE: return cv2.resize(img, (size, size))",
"def mapk(actual, predicted, k=3): \"\"\" Source: https://github.com/benhamner/Metrics/blob/master/Python/ml_metrics/average_precision.py \"\"\" return np.mean([apk(a, p, k) for",
"Augments the testdata with horizontal and vertical flips and averages the results. Args:",
"keras.applications.densenet import preprocess_input from keras.metrics import (categorical_accuracy, top_k_categorical_accuracy) from keras.models import Model, load_model",
"TTA wrapper for keras computer vision models. Args: model (keras model): A fitted",
"time_color else 255 _ = cv2.line(img, (stroke[0][i], stroke[1][i]), (stroke[0][i + 1], stroke[1][i +",
"lw=6, time_color=True): while True: for k in np.random.permutation(ks): filename = os.path.join(DP_DIR, 'train_k{}.csv.gz'.format(k)) for",
"to get predictions for. \"\"\" p0 = self.model.predict(X, batch_size=128, verbose=1) p1 = self.model.predict(np.flipud(X),",
"for. \"\"\" p0 = self.model.predict(X, batch_size=128, verbose=1) p1 = self.model.predict(np.flipud(X), batch_size=128, verbose=1) p",
"enumerate(df.drawing.values): x[i, :, :, :] = draw_cv2( raw_strokes, size=size, lw=lw, time_color=time_color) x =",
"= os.listdir(os.path.join(INPUT_DIR, 'train_simplified')) return sorted([f2cat(f) for f in files], key=str.lower) def apk(actual, predicted,",
"tensorflow as tf from tensorflow import keras from keras.applications.densenet import preprocess_input from keras.metrics",
"range(len(stroke[0]) - 1): color = 255 - min(t, 10) * 13 if time_color",
"vertical flips and averages the results. Args: X (numpy array of dim 4):",
"INPUT_DIR = './input/quickdraw-doodle-recognition/' BASE_SIZE = 256 NCSVS = 200 NCATS = 340 np.random.seed(seed=2018)",
"k: predicted = predicted[:k] score = 0.0 num_hits = 0.0 for i, p",
"= model def predict(self, X): \"\"\"Wraps the predict method of the provided model.",
"+ 1], stroke[1][i + 1]), color, lw) img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) if size",
"np.zeros((BASE_SIZE, BASE_SIZE), np.uint8) for t, stroke in enumerate(raw_strokes): for i in range(len(stroke[0]) -",
"cv2.COLOR_GRAY2RGB) if size != BASE_SIZE: return cv2.resize(img, (size, size)) else: return img def",
"dim 4): The data to get predictions for. \"\"\" p0 = self.model.predict(X, batch_size=128,",
"the predict method of the provided model. Augments the testdata with horizontal and",
"import preprocess_input from keras.metrics import (categorical_accuracy, top_k_categorical_accuracy) from keras.models import Model, load_model DP_DIR",
"__init__(self, model): self.model = model def predict(self, X): \"\"\"Wraps the predict method of",
"ast import os import cv2 import numpy as np import pandas as pd",
"= cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) if size != BASE_SIZE: return cv2.resize(img, (size, size)) else: return",
"predicted = predicted[:k] score = 0.0 num_hits = 0.0 for i, p in",
"return score / min(len(actual), k) def mapk(actual, predicted, k=3): \"\"\" Source: https://github.com/benhamner/Metrics/blob/master/Python/ml_metrics/average_precision.py \"\"\"",
"def predict(self, X): \"\"\"Wraps the predict method of the provided model. Augments the",
"(stroke[0][i + 1], stroke[1][i + 1]), color, lw) img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) if",
"import cv2 import numpy as np import pandas as pd import tensorflow as",
"while True: for k in np.random.permutation(ks): filename = os.path.join(DP_DIR, 'train_k{}.csv.gz'.format(k)) for df in",
"k=3): \"\"\" Source: https://github.com/benhamner/Metrics/blob/master/Python/ml_metrics/average_precision.py \"\"\" if len(predicted) > k: predicted = predicted[:k] score",
"predict method. \"\"\" def __init__(self, model): self.model = model def predict(self, X): \"\"\"Wraps",
"i, raw_strokes in enumerate(df.drawing.values): x[i, :, :, :] = draw_cv2( raw_strokes, size=size, lw=lw,",
"predicted[:i]: num_hits += 1.0 score += num_hits / (i + 1.0) if not",
"return 0.0 return score / min(len(actual), k) def mapk(actual, predicted, k=3): \"\"\" Source:",
"results. Args: X (numpy array of dim 4): The data to get predictions",
"= preprocess_input(x).astype(np.float32) y = keras.utils.to_categorical(df.y, num_classes=NCATS) yield x, y def df_to_image_array_xd(df, size, lw=6,",
"fitted keras model with a predict method. \"\"\" def __init__(self, model): self.model =",
"\"\"\"Wraps the predict method of the provided model. Augments the testdata with horizontal",
"- 1): color = 255 - min(t, 10) * 13 if time_color else",
"\"\"\" p0 = self.model.predict(X, batch_size=128, verbose=1) p1 = self.model.predict(np.flipud(X), batch_size=128, verbose=1) p =",
"def top_3_accuracy(y_true, y_pred): return top_k_categorical_accuracy(y_true, y_pred, k=3) def draw_cv2(raw_strokes, size=256, lw=6, time_color=True): img",
"in predicted[:i]: num_hits += 1.0 score += num_hits / (i + 1.0) if",
"min(t, 10) * 13 if time_color else 255 _ = cv2.line(img, (stroke[0][i], stroke[1][i]),",
"lw=lw, time_color=time_color) x = preprocess_input(x).astype(np.float32) return x class TTA_ModelWrapper(): \"\"\"A simple TTA wrapper",
"keras.utils.to_categorical(df.y, num_classes=NCATS) yield x, y def df_to_image_array_xd(df, size, lw=6, time_color=True): df['drawing'] = df['drawing'].apply(ast.literal_eval)",
"cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) if size != BASE_SIZE: return cv2.resize(img, (size, size)) else: return img",
"data to get predictions for. \"\"\" p0 = self.model.predict(X, batch_size=128, verbose=1) p1 =",
"for i, p in enumerate(predicted): if p in actual and p not in",
"for i, raw_strokes in enumerate(df.drawing.values): x[i, :, :, :] = draw_cv2(raw_strokes, size=size, lw=lw,",
"0.0 num_hits = 0.0 for i, p in enumerate(predicted): if p in actual",
"p not in predicted[:i]: num_hits += 1.0 score += num_hits / (i +",
"list_all_categories(): files = os.listdir(os.path.join(INPUT_DIR, 'train_simplified')) return sorted([f2cat(f) for f in files], key=str.lower) def",
"a predict method. \"\"\" def __init__(self, model): self.model = model def predict(self, X):",
"BASE_SIZE = 256 NCSVS = 200 NCATS = 340 np.random.seed(seed=2018) tf.set_random_seed(seed=2018) def f2cat(filename:",
"= 340 np.random.seed(seed=2018) tf.set_random_seed(seed=2018) def f2cat(filename: str) -> str: return filename.split('.')[0] def list_all_categories():",
"chunksize=batchsize): df['drawing'] = df['drawing'].apply(ast.literal_eval) x = np.zeros((len(df), size, size, 3)) for i, raw_strokes",
"+ 1.0) if not actual: return 0.0 return score / min(len(actual), k) def",
"numpy as np import pandas as pd import tensorflow as tf from tensorflow",
"cv2.line(img, (stroke[0][i], stroke[1][i]), (stroke[0][i + 1], stroke[1][i + 1]), color, lw) img =",
"as tf from tensorflow import keras from keras.applications.densenet import preprocess_input from keras.metrics import",
"time_color=time_color) x = preprocess_input(x).astype(np.float32) return x class TTA_ModelWrapper(): \"\"\"A simple TTA wrapper for",
"model): self.model = model def predict(self, X): \"\"\"Wraps the predict method of the",
"y_pred): return top_k_categorical_accuracy(y_true, y_pred, k=3) def draw_cv2(raw_strokes, size=256, lw=6, time_color=True): img = np.zeros((BASE_SIZE,",
"in np.random.permutation(ks): filename = os.path.join(DP_DIR, 'train_k{}.csv.gz'.format(k)) for df in pd.read_csv(filename, chunksize=batchsize): df['drawing'] =",
"x[i, :, :, :] = draw_cv2(raw_strokes, size=size, lw=lw, time_color=time_color) x = preprocess_input(x).astype(np.float32) y",
"pd import tensorflow as tf from tensorflow import keras from keras.applications.densenet import preprocess_input",
"np.zeros((len(df), size, size, 3)) for i, raw_strokes in enumerate(df.drawing.values): x[i, :, :, :]",
"size)) else: return img def image_generator_xd(size, batchsize, ks, lw=6, time_color=True): while True: for",
"in range(len(stroke[0]) - 1): color = 255 - min(t, 10) * 13 if",
"\"\"\" Source: https://github.com/benhamner/Metrics/blob/master/Python/ml_metrics/average_precision.py \"\"\" return np.mean([apk(a, p, k) for a, p in zip(actual,",
"columns=['a', 'b', 'c']) def top_3_accuracy(y_true, y_pred): return top_k_categorical_accuracy(y_true, y_pred, k=3) def draw_cv2(raw_strokes, size=256,",
"= np.zeros((len(df), size, size, 3)) for i, raw_strokes in enumerate(df.drawing.values): x[i, :, :,",
"pandas as pd import tensorflow as tf from tensorflow import keras from keras.applications.densenet",
"k=3) def draw_cv2(raw_strokes, size=256, lw=6, time_color=True): img = np.zeros((BASE_SIZE, BASE_SIZE), np.uint8) for t,",
"top_3_accuracy(y_true, y_pred): return top_k_categorical_accuracy(y_true, y_pred, k=3) def draw_cv2(raw_strokes, size=256, lw=6, time_color=True): img =",
":, :, :] = draw_cv2(raw_strokes, size=size, lw=lw, time_color=time_color) x = preprocess_input(x).astype(np.float32) y =",
"p, k) for a, p in zip(actual, predicted)]) def preds2catids(predictions): return pd.DataFrame(np.argsort(-predictions, axis=1)[:,",
"as pd import tensorflow as tf from tensorflow import keras from keras.applications.densenet import",
"Args: model (keras model): A fitted keras model with a predict method. \"\"\"",
"preds2catids(predictions): return pd.DataFrame(np.argsort(-predictions, axis=1)[:, :3], columns=['a', 'b', 'c']) def top_3_accuracy(y_true, y_pred): return top_k_categorical_accuracy(y_true,",
"time_color=time_color) x = preprocess_input(x).astype(np.float32) y = keras.utils.to_categorical(df.y, num_classes=NCATS) yield x, y def df_to_image_array_xd(df,",
"model def predict(self, X): \"\"\"Wraps the predict method of the provided model. Augments",
"keras.metrics import (categorical_accuracy, top_k_categorical_accuracy) from keras.models import Model, load_model DP_DIR = './input/shuffle-csvs/' INPUT_DIR",
"= './input/quickdraw-doodle-recognition/' BASE_SIZE = 256 NCSVS = 200 NCATS = 340 np.random.seed(seed=2018) tf.set_random_seed(seed=2018)",
"the testdata with horizontal and vertical flips and averages the results. Args: X",
"return img def image_generator_xd(size, batchsize, ks, lw=6, time_color=True): while True: for k in",
"predicted, k=3): \"\"\" Source: https://github.com/benhamner/Metrics/blob/master/Python/ml_metrics/average_precision.py \"\"\" return np.mean([apk(a, p, k) for a, p",
"actual and p not in predicted[:i]: num_hits += 1.0 score += num_hits /",
"Args: X (numpy array of dim 4): The data to get predictions for.",
"(categorical_accuracy, top_k_categorical_accuracy) from keras.models import Model, load_model DP_DIR = './input/shuffle-csvs/' INPUT_DIR = './input/quickdraw-doodle-recognition/'",
"= np.zeros((BASE_SIZE, BASE_SIZE), np.uint8) for t, stroke in enumerate(raw_strokes): for i in range(len(stroke[0])",
"import keras from keras.applications.densenet import preprocess_input from keras.metrics import (categorical_accuracy, top_k_categorical_accuracy) from keras.models",
"num_hits = 0.0 for i, p in enumerate(predicted): if p in actual and",
"3)) for i, raw_strokes in enumerate(df.drawing.values): x[i, :, :, :] = draw_cv2(raw_strokes, size=size,",
"1.0 score += num_hits / (i + 1.0) if not actual: return 0.0",
"k in np.random.permutation(ks): filename = os.path.join(DP_DIR, 'train_k{}.csv.gz'.format(k)) for df in pd.read_csv(filename, chunksize=batchsize): df['drawing']",
"in pd.read_csv(filename, chunksize=batchsize): df['drawing'] = df['drawing'].apply(ast.literal_eval) x = np.zeros((len(df), size, size, 3)) for",
"import tensorflow as tf from tensorflow import keras from keras.applications.densenet import preprocess_input from",
"= './input/shuffle-csvs/' INPUT_DIR = './input/quickdraw-doodle-recognition/' BASE_SIZE = 256 NCSVS = 200 NCATS =",
"predicted)]) def preds2catids(predictions): return pd.DataFrame(np.argsort(-predictions, axis=1)[:, :3], columns=['a', 'b', 'c']) def top_3_accuracy(y_true, y_pred):",
"from keras.applications.densenet import preprocess_input from keras.metrics import (categorical_accuracy, top_k_categorical_accuracy) from keras.models import Model,",
"mapk(actual, predicted, k=3): \"\"\" Source: https://github.com/benhamner/Metrics/blob/master/Python/ml_metrics/average_precision.py \"\"\" return np.mean([apk(a, p, k) for a,",
"str: return filename.split('.')[0] def list_all_categories(): files = os.listdir(os.path.join(INPUT_DIR, 'train_simplified')) return sorted([f2cat(f) for f",
"= 0.0 for i, p in enumerate(predicted): if p in actual and p",
"\"\"\" return np.mean([apk(a, p, k) for a, p in zip(actual, predicted)]) def preds2catids(predictions):",
"predictions for. \"\"\" p0 = self.model.predict(X, batch_size=128, verbose=1) p1 = self.model.predict(np.flipud(X), batch_size=128, verbose=1)",
"filename = os.path.join(DP_DIR, 'train_k{}.csv.gz'.format(k)) for df in pd.read_csv(filename, chunksize=batchsize): df['drawing'] = df['drawing'].apply(ast.literal_eval) x",
"13 if time_color else 255 _ = cv2.line(img, (stroke[0][i], stroke[1][i]), (stroke[0][i + 1],",
"as np import pandas as pd import tensorflow as tf from tensorflow import",
"for t, stroke in enumerate(raw_strokes): for i in range(len(stroke[0]) - 1): color =",
"340 np.random.seed(seed=2018) tf.set_random_seed(seed=2018) def f2cat(filename: str) -> str: return filename.split('.')[0] def list_all_categories(): files",
"3)) for i, raw_strokes in enumerate(df.drawing.values): x[i, :, :, :] = draw_cv2( raw_strokes,",
"if not actual: return 0.0 return score / min(len(actual), k) def mapk(actual, predicted,",
"import numpy as np import pandas as pd import tensorflow as tf from",
":, :, :] = draw_cv2( raw_strokes, size=size, lw=lw, time_color=time_color) x = preprocess_input(x).astype(np.float32) return",
"TTA_ModelWrapper(): \"\"\"A simple TTA wrapper for keras computer vision models. Args: model (keras",
"draw_cv2(raw_strokes, size=256, lw=6, time_color=True): img = np.zeros((BASE_SIZE, BASE_SIZE), np.uint8) for t, stroke in",
"img = np.zeros((BASE_SIZE, BASE_SIZE), np.uint8) for t, stroke in enumerate(raw_strokes): for i in",
"stroke[1][i + 1]), color, lw) img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) if size != BASE_SIZE:",
"array of dim 4): The data to get predictions for. \"\"\" p0 =",
"import ast import os import cv2 import numpy as np import pandas as",
"filename.split('.')[0] def list_all_categories(): files = os.listdir(os.path.join(INPUT_DIR, 'train_simplified')) return sorted([f2cat(f) for f in files],",
"len(predicted) > k: predicted = predicted[:k] score = 0.0 num_hits = 0.0 for",
"yield x, y def df_to_image_array_xd(df, size, lw=6, time_color=True): df['drawing'] = df['drawing'].apply(ast.literal_eval) x =",
"0.0 for i, p in enumerate(predicted): if p in actual and p not",
"from tensorflow import keras from keras.applications.densenet import preprocess_input from keras.metrics import (categorical_accuracy, top_k_categorical_accuracy)",
"in enumerate(predicted): if p in actual and p not in predicted[:i]: num_hits +=",
"for df in pd.read_csv(filename, chunksize=batchsize): df['drawing'] = df['drawing'].apply(ast.literal_eval) x = np.zeros((len(df), size, size,",
"1]), color, lw) img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) if size != BASE_SIZE: return cv2.resize(img,",
"k) for a, p in zip(actual, predicted)]) def preds2catids(predictions): return pd.DataFrame(np.argsort(-predictions, axis=1)[:, :3],",
"preprocess_input from keras.metrics import (categorical_accuracy, top_k_categorical_accuracy) from keras.models import Model, load_model DP_DIR =",
"tf.set_random_seed(seed=2018) def f2cat(filename: str) -> str: return filename.split('.')[0] def list_all_categories(): files = os.listdir(os.path.join(INPUT_DIR,",
"for f in files], key=str.lower) def apk(actual, predicted, k=3): \"\"\" Source: https://github.com/benhamner/Metrics/blob/master/Python/ml_metrics/average_precision.py \"\"\"",
"def draw_cv2(raw_strokes, size=256, lw=6, time_color=True): img = np.zeros((BASE_SIZE, BASE_SIZE), np.uint8) for t, stroke",
"key=str.lower) def apk(actual, predicted, k=3): \"\"\" Source: https://github.com/benhamner/Metrics/blob/master/Python/ml_metrics/average_precision.py \"\"\" if len(predicted) > k:",
"stroke[1][i]), (stroke[0][i + 1], stroke[1][i + 1]), color, lw) img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)",
"NCATS = 340 np.random.seed(seed=2018) tf.set_random_seed(seed=2018) def f2cat(filename: str) -> str: return filename.split('.')[0] def",
"import pandas as pd import tensorflow as tf from tensorflow import keras from",
"size, 3)) for i, raw_strokes in enumerate(df.drawing.values): x[i, :, :, :] = draw_cv2(raw_strokes,",
"t, stroke in enumerate(raw_strokes): for i in range(len(stroke[0]) - 1): color = 255",
"min(len(actual), k) def mapk(actual, predicted, k=3): \"\"\" Source: https://github.com/benhamner/Metrics/blob/master/Python/ml_metrics/average_precision.py \"\"\" return np.mean([apk(a, p,",
"'./input/quickdraw-doodle-recognition/' BASE_SIZE = 256 NCSVS = 200 NCATS = 340 np.random.seed(seed=2018) tf.set_random_seed(seed=2018) def",
"enumerate(df.drawing.values): x[i, :, :, :] = draw_cv2(raw_strokes, size=size, lw=lw, time_color=time_color) x = preprocess_input(x).astype(np.float32)",
"axis=1)[:, :3], columns=['a', 'b', 'c']) def top_3_accuracy(y_true, y_pred): return top_k_categorical_accuracy(y_true, y_pred, k=3) def",
"!= BASE_SIZE: return cv2.resize(img, (size, size)) else: return img def image_generator_xd(size, batchsize, ks,",
"os.path.join(DP_DIR, 'train_k{}.csv.gz'.format(k)) for df in pd.read_csv(filename, chunksize=batchsize): df['drawing'] = df['drawing'].apply(ast.literal_eval) x = np.zeros((len(df),",
"= cv2.line(img, (stroke[0][i], stroke[1][i]), (stroke[0][i + 1], stroke[1][i + 1]), color, lw) img",
"+ 1]), color, lw) img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) if size != BASE_SIZE: return",
"x class TTA_ModelWrapper(): \"\"\"A simple TTA wrapper for keras computer vision models. Args:",
"raw_strokes in enumerate(df.drawing.values): x[i, :, :, :] = draw_cv2(raw_strokes, size=size, lw=lw, time_color=time_color) x",
"= 0.0 num_hits = 0.0 for i, p in enumerate(predicted): if p in",
"np.uint8) for t, stroke in enumerate(raw_strokes): for i in range(len(stroke[0]) - 1): color",
"https://github.com/benhamner/Metrics/blob/master/Python/ml_metrics/average_precision.py \"\"\" return np.mean([apk(a, p, k) for a, p in zip(actual, predicted)]) def",
"tf from tensorflow import keras from keras.applications.densenet import preprocess_input from keras.metrics import (categorical_accuracy,",
"ks, lw=6, time_color=True): while True: for k in np.random.permutation(ks): filename = os.path.join(DP_DIR, 'train_k{}.csv.gz'.format(k))",
"keras model with a predict method. \"\"\" def __init__(self, model): self.model = model",
"keras from keras.applications.densenet import preprocess_input from keras.metrics import (categorical_accuracy, top_k_categorical_accuracy) from keras.models import",
"for a, p in zip(actual, predicted)]) def preds2catids(predictions): return pd.DataFrame(np.argsort(-predictions, axis=1)[:, :3], columns=['a',",
"verbose=1) p1 = self.model.predict(np.flipud(X), batch_size=128, verbose=1) p = (p0 + p1) / 2",
"return pd.DataFrame(np.argsort(-predictions, axis=1)[:, :3], columns=['a', 'b', 'c']) def top_3_accuracy(y_true, y_pred): return top_k_categorical_accuracy(y_true, y_pred,",
"1.0) if not actual: return 0.0 return score / min(len(actual), k) def mapk(actual,",
"def image_generator_xd(size, batchsize, ks, lw=6, time_color=True): while True: for k in np.random.permutation(ks): filename",
"y def df_to_image_array_xd(df, size, lw=6, time_color=True): df['drawing'] = df['drawing'].apply(ast.literal_eval) x = np.zeros((len(df), size,",
"img def image_generator_xd(size, batchsize, ks, lw=6, time_color=True): while True: for k in np.random.permutation(ks):",
"batchsize, ks, lw=6, time_color=True): while True: for k in np.random.permutation(ks): filename = os.path.join(DP_DIR,",
"size != BASE_SIZE: return cv2.resize(img, (size, size)) else: return img def image_generator_xd(size, batchsize,",
"(i + 1.0) if not actual: return 0.0 return score / min(len(actual), k)",
"A fitted keras model with a predict method. \"\"\" def __init__(self, model): self.model",
"= predicted[:k] score = 0.0 num_hits = 0.0 for i, p in enumerate(predicted):",
"for keras computer vision models. Args: model (keras model): A fitted keras model",
"cv2 import numpy as np import pandas as pd import tensorflow as tf",
"np import pandas as pd import tensorflow as tf from tensorflow import keras",
"Source: https://github.com/benhamner/Metrics/blob/master/Python/ml_metrics/average_precision.py \"\"\" return np.mean([apk(a, p, k) for a, p in zip(actual, predicted)])",
"'c']) def top_3_accuracy(y_true, y_pred): return top_k_categorical_accuracy(y_true, y_pred, k=3) def draw_cv2(raw_strokes, size=256, lw=6, time_color=True):",
"cv2.resize(img, (size, size)) else: return img def image_generator_xd(size, batchsize, ks, lw=6, time_color=True): while",
"if p in actual and p not in predicted[:i]: num_hits += 1.0 score",
"BASE_SIZE: return cv2.resize(img, (size, size)) else: return img def image_generator_xd(size, batchsize, ks, lw=6,",
"size, lw=6, time_color=True): df['drawing'] = df['drawing'].apply(ast.literal_eval) x = np.zeros((len(df), size, size, 3)) for",
"preprocess_input(x).astype(np.float32) return x class TTA_ModelWrapper(): \"\"\"A simple TTA wrapper for keras computer vision",
"= os.path.join(DP_DIR, 'train_k{}.csv.gz'.format(k)) for df in pd.read_csv(filename, chunksize=batchsize): df['drawing'] = df['drawing'].apply(ast.literal_eval) x =",
"- min(t, 10) * 13 if time_color else 255 _ = cv2.line(img, (stroke[0][i],",
"model (keras model): A fitted keras model with a predict method. \"\"\" def",
"model. Augments the testdata with horizontal and vertical flips and averages the results.",
"np.random.seed(seed=2018) tf.set_random_seed(seed=2018) def f2cat(filename: str) -> str: return filename.split('.')[0] def list_all_categories(): files =",
"in files], key=str.lower) def apk(actual, predicted, k=3): \"\"\" Source: https://github.com/benhamner/Metrics/blob/master/Python/ml_metrics/average_precision.py \"\"\" if len(predicted)",
"color = 255 - min(t, 10) * 13 if time_color else 255 _",
"self.model.predict(X, batch_size=128, verbose=1) p1 = self.model.predict(np.flipud(X), batch_size=128, verbose=1) p = (p0 + p1)",
"from keras.models import Model, load_model DP_DIR = './input/shuffle-csvs/' INPUT_DIR = './input/quickdraw-doodle-recognition/' BASE_SIZE =",
"200 NCATS = 340 np.random.seed(seed=2018) tf.set_random_seed(seed=2018) def f2cat(filename: str) -> str: return filename.split('.')[0]",
"top_k_categorical_accuracy) from keras.models import Model, load_model DP_DIR = './input/shuffle-csvs/' INPUT_DIR = './input/quickdraw-doodle-recognition/' BASE_SIZE",
"class TTA_ModelWrapper(): \"\"\"A simple TTA wrapper for keras computer vision models. Args: model",
"(numpy array of dim 4): The data to get predictions for. \"\"\" p0",
"in enumerate(raw_strokes): for i in range(len(stroke[0]) - 1): color = 255 - min(t,",
"BASE_SIZE), np.uint8) for t, stroke in enumerate(raw_strokes): for i in range(len(stroke[0]) - 1):",
"with horizontal and vertical flips and averages the results. Args: X (numpy array",
"of the provided model. Augments the testdata with horizontal and vertical flips and",
"* 13 if time_color else 255 _ = cv2.line(img, (stroke[0][i], stroke[1][i]), (stroke[0][i +",
"x = np.zeros((len(df), size, size, 3)) for i, raw_strokes in enumerate(df.drawing.values): x[i, :,",
"time_color=True): while True: for k in np.random.permutation(ks): filename = os.path.join(DP_DIR, 'train_k{}.csv.gz'.format(k)) for df",
"pd.DataFrame(np.argsort(-predictions, axis=1)[:, :3], columns=['a', 'b', 'c']) def top_3_accuracy(y_true, y_pred): return top_k_categorical_accuracy(y_true, y_pred, k=3)",
"10) * 13 if time_color else 255 _ = cv2.line(img, (stroke[0][i], stroke[1][i]), (stroke[0][i",
"in actual and p not in predicted[:i]: num_hits += 1.0 score += num_hits",
"Source: https://github.com/benhamner/Metrics/blob/master/Python/ml_metrics/average_precision.py \"\"\" if len(predicted) > k: predicted = predicted[:k] score = 0.0",
"num_hits / (i + 1.0) if not actual: return 0.0 return score /",
"predicted, k=3): \"\"\" Source: https://github.com/benhamner/Metrics/blob/master/Python/ml_metrics/average_precision.py \"\"\" if len(predicted) > k: predicted = predicted[:k]",
"= 255 - min(t, 10) * 13 if time_color else 255 _ =",
"return top_k_categorical_accuracy(y_true, y_pred, k=3) def draw_cv2(raw_strokes, size=256, lw=6, time_color=True): img = np.zeros((BASE_SIZE, BASE_SIZE),"
] |
[
"under the terms of the LGPLv3 or higher. from PyQt5.QtCore import Qt, pyqtSlot",
"in quality_changes_group_dict.values(): if quality_changes_group.quality_type not in available_quality_types: continue quality_group = quality_group_dict[quality_changes_group.quality_type] item =",
"= Qt.UserRole + 3 QualityChangesGroupRole = Qt.UserRole + 4 def __init__(self, parent =",
"# # This the QML model for the quality management page. # class",
"= [] for quality_changes_group in quality_changes_group_dict.values(): if quality_changes_group.quality_type not in available_quality_types: continue quality_group",
"indicating file name filters for a file # dialog. @pyqtSlot(str, result = \"QVariantList\")",
"[] # Create quality group items for quality_group in quality_group_dict.values(): if not quality_group.is_available:",
"quality_type, quality_group in quality_group_dict.items() if quality_group.is_available) if not available_quality_types and not quality_changes_group_dict: #",
"x[\"name\"].upper()) # Create quality_changes group items quality_changes_item_list = [] for quality_changes_group in quality_changes_group_dict.values():",
"write. The convenience meta-filters # \"All Supported Types\" and \"All Files\" are added",
"later. # ## Gets a list of the possible file filters that the",
"IO type # \\return A list of strings indicating file name filters for",
"= [] for plugin_id, meta_data in self._getIOPlugins(io_type): for io_plugin in meta_data[io_type]: filters.append(io_plugin[\"description\"] +",
"quality management page. # class QualityManagementModel(ListModel): NameRole = Qt.UserRole + 1 IsReadOnlyRole =",
"quality_group_dict = self._quality_manager.getQualityGroups(global_stack) quality_changes_group_dict = self._quality_manager.getQualityChangesGroups(global_stack) available_quality_types = set(quality_type for quality_type, quality_group in",
"catalog = i18nCatalog(\"uranium\") #TODO: This function should be in UM.Resources! filters = []",
"terms of the LGPLv3 or higher. from PyQt5.QtCore import Qt, pyqtSlot from UM.Qt.ListModel",
"possible file filters that the plugins have # registered they can read or",
"arbitrary files, if the user so prefers. return filters ## Gets a list",
"quality_group.name, \"is_read_only\": True, \"quality_group\": quality_group, \"quality_changes_group\": None} item_list.append(item) # Sort by quality names",
"meta-filters # \"All Supported Types\" and \"All Files\" are added when listing #",
"items by names and append to the item list quality_changes_item_list = sorted(quality_changes_item_list, key",
"= quality_group_dict[quality_changes_group.quality_type] item = {\"name\": quality_changes_group.name, \"is_read_only\": False, \"quality_group\": quality_group, \"quality_changes_group\": quality_changes_group} quality_changes_item_list.append(item)",
"= sorted(quality_changes_item_list, key = lambda x: x[\"name\"].upper()) item_list += quality_changes_item_list self.setItems(item_list) # TODO:",
"readers, but not when listing writers. # # \\param io_type \\type{str} name of",
"released under the terms of the LGPLv3 or higher. from PyQt5.QtCore import Qt,",
"<NAME>. # Cura is released under the terms of the LGPLv3 or higher.",
"group items for quality_group in quality_group_dict.values(): if not quality_group.is_available: continue item = {\"name\":",
"2018 <NAME>. # Cura is released under the terms of the LGPLv3 or",
"self.addRoleName(self.IsReadOnlyRole, \"is_read_only\") self.addRoleName(self.QualityGroupRole, \"quality_group\") self.addRoleName(self.QualityChangesGroupRole, \"quality_changes_group\") from cura.CuraApplication import CuraApplication self._container_registry = CuraApplication.getInstance().getContainerRegistry()",
"Types ({0})\", \" \".join(all_types))) filters.append(catalog.i18nc(\"@item:inlistbox\", \"All Files (*)\")) # Also allow arbitrary files,",
"item = {\"name\": quality_group.name, \"is_read_only\": True, \"quality_group\": quality_group, \"quality_changes_group\": None} item_list.append(item) # Sort",
"from UM.i18n import i18nCatalog catalog = i18nCatalog(\"uranium\") #TODO: This function should be in",
"quality_changes_item_list self.setItems(item_list) # TODO: Duplicated code here from InstanceContainersModel. Refactor and remove this",
"by quality names item_list = sorted(item_list, key = lambda x: x[\"name\"].upper()) # Create",
"\"is_read_only\") self.addRoleName(self.QualityGroupRole, \"quality_group\") self.addRoleName(self.QualityChangesGroupRole, \"quality_changes_group\") from cura.CuraApplication import CuraApplication self._container_registry = CuraApplication.getInstance().getContainerRegistry() self._machine_manager",
"# ## Gets a list of the possible file filters that the plugins",
"item_list = [] # Create quality group items for quality_group in quality_group_dict.values(): if",
"quality_changes group items quality_changes_item_list = [] for quality_changes_group in quality_changes_group_dict.values(): if quality_changes_group.quality_type not",
"# \"All Supported Types\" and \"All Files\" are added when listing # readers,",
"this later. # ## Gets a list of the possible file filters that",
"Supported Types\" and \"All Files\" are added when listing # readers, but not",
"quality_changes_group.quality_type not in available_quality_types: continue quality_group = quality_group_dict[quality_changes_group.quality_type] item = {\"name\": quality_changes_group.name, \"is_read_only\":",
"This the QML model for the quality management page. # class QualityManagementModel(ListModel): NameRole",
"all_types = [] for plugin_id, meta_data in self._getIOPlugins(io_type): for io_plugin in meta_data[io_type]: filters.append(io_plugin[\"description\"]",
"The convenience meta-filters # \"All Supported Types\" and \"All Files\" are added when",
"i18nCatalog(\"uranium\") #TODO: This function should be in UM.Resources! filters = [] all_types =",
"the needed IO type # \\return A list of strings indicating file name",
"TODO: Duplicated code here from InstanceContainersModel. Refactor and remove this later. # ##",
"if \"_reader\" in io_type: # if we're listing readers, add the option to",
"return quality_group_dict = self._quality_manager.getQualityGroups(global_stack) quality_changes_group_dict = self._quality_manager.getQualityChangesGroups(global_stack) available_quality_types = set(quality_type for quality_type, quality_group",
"option to show all supported files as the default option filters.insert(0, catalog.i18nc(\"@item:inlistbox\", \"All",
"Qt, pyqtSlot from UM.Qt.ListModel import ListModel from UM.Logger import Logger # # This",
"in active_plugin_ids: meta_data = pr.getMetaData(plugin_id) if io_type in meta_data: result.append( (plugin_id, meta_data) )",
"or higher. from PyQt5.QtCore import Qt, pyqtSlot from UM.Qt.ListModel import ListModel from UM.Logger",
"# This the QML model for the quality management page. # class QualityManagementModel(ListModel):",
"self.setItems(item_list) # TODO: Duplicated code here from InstanceContainersModel. Refactor and remove this later.",
"of the LGPLv3 or higher. from PyQt5.QtCore import Qt, pyqtSlot from UM.Qt.ListModel import",
"name filters for a file # dialog. @pyqtSlot(str, result = \"QVariantList\") def getFileNameFilters(self,",
"\"All Supported Types\" and \"All Files\" are added when listing # readers, but",
"name of the needed IO type # \\return A list of strings indicating",
"= self._machine_manager.activeMachine if not global_stack: self.setItems([]) return quality_group_dict = self._quality_manager.getQualityGroups(global_stack) quality_changes_group_dict = self._quality_manager.getQualityChangesGroups(global_stack)",
"Gets a list of the possible file filters that the plugins have #",
"for io_plugin in meta_data[io_type]: filters.append(io_plugin[\"description\"] + \" (*.\" + io_plugin[\"extension\"] + \")\") all_types.append(\"*.{0}\".format(io_plugin[\"extension\"]))",
"+ 4 def __init__(self, parent = None): super().__init__(parent) self.addRoleName(self.NameRole, \"name\") self.addRoleName(self.IsReadOnlyRole, \"is_read_only\") self.addRoleName(self.QualityGroupRole,",
"meta_data). def _getIOPlugins(self, io_type): from UM.PluginRegistry import PluginRegistry pr = PluginRegistry.getInstance() active_plugin_ids =",
"remove this later. # ## Gets a list of the possible file filters",
"type # \\return A list of strings indicating file name filters for a",
"Supported Types ({0})\", \" \".join(all_types))) filters.append(catalog.i18nc(\"@item:inlistbox\", \"All Files (*)\")) # Also allow arbitrary",
"Qt.UserRole + 2 QualityGroupRole = Qt.UserRole + 3 QualityChangesGroupRole = Qt.UserRole + 4",
"meta_data[io_type]: filters.append(io_plugin[\"description\"] + \" (*.\" + io_plugin[\"extension\"] + \")\") all_types.append(\"*.{0}\".format(io_plugin[\"extension\"])) if \"_reader\" in",
"quality_group in quality_group_dict.items() if quality_group.is_available) if not available_quality_types and not quality_changes_group_dict: # Nothing",
"filters that the plugins have # registered they can read or write. The",
"# Create quality_changes group items quality_changes_item_list = [] for quality_changes_group in quality_changes_group_dict.values(): if",
"in self._getIOPlugins(io_type): for io_plugin in meta_data[io_type]: filters.append(io_plugin[\"description\"] + \" (*.\" + io_plugin[\"extension\"] +",
"in meta_data[io_type]: filters.append(io_plugin[\"description\"] + \" (*.\" + io_plugin[\"extension\"] + \")\") all_types.append(\"*.{0}\".format(io_plugin[\"extension\"])) if \"_reader\"",
"self._quality_manager.qualitiesUpdated.connect(self._update) self._update() def _update(self): Logger.log(\"d\", \"Updating {model_class_name}.\".format(model_class_name = self.__class__.__name__)) global_stack = self._machine_manager.activeMachine if",
"prefers. return filters ## Gets a list of profile reader or writer plugins",
"List of tuples of (plugin_id, meta_data). def _getIOPlugins(self, io_type): from UM.PluginRegistry import PluginRegistry",
"quality_group, \"quality_changes_group\": None} item_list.append(item) # Sort by quality names item_list = sorted(item_list, key",
"list quality_changes_item_list = sorted(quality_changes_item_list, key = lambda x: x[\"name\"].upper()) item_list += quality_changes_item_list self.setItems(item_list)",
"## Gets a list of profile reader or writer plugins # \\return List",
"def _update(self): Logger.log(\"d\", \"Updating {model_class_name}.\".format(model_class_name = self.__class__.__name__)) global_stack = self._machine_manager.activeMachine if not global_stack:",
"= lambda x: x[\"name\"].upper()) # Create quality_changes group items quality_changes_item_list = [] for",
"dialog. @pyqtSlot(str, result = \"QVariantList\") def getFileNameFilters(self, io_type): from UM.i18n import i18nCatalog catalog",
"that the plugins have # registered they can read or write. The convenience",
"not quality_changes_group_dict: # Nothing to show self.setItems([]) return item_list = [] # Create",
"= self._quality_manager.getQualityGroups(global_stack) quality_changes_group_dict = self._quality_manager.getQualityChangesGroups(global_stack) available_quality_types = set(quality_type for quality_type, quality_group in quality_group_dict.items()",
"= Qt.UserRole + 2 QualityGroupRole = Qt.UserRole + 3 QualityChangesGroupRole = Qt.UserRole +",
"for plugin_id in active_plugin_ids: meta_data = pr.getMetaData(plugin_id) if io_type in meta_data: result.append( (plugin_id,",
"= Qt.UserRole + 1 IsReadOnlyRole = Qt.UserRole + 2 QualityGroupRole = Qt.UserRole +",
"CuraApplication.getInstance().getQualityManager() self._machine_manager.globalContainerChanged.connect(self._update) self._quality_manager.qualitiesUpdated.connect(self._update) self._update() def _update(self): Logger.log(\"d\", \"Updating {model_class_name}.\".format(model_class_name = self.__class__.__name__)) global_stack =",
"self._getIOPlugins(io_type): for io_plugin in meta_data[io_type]: filters.append(io_plugin[\"description\"] + \" (*.\" + io_plugin[\"extension\"] + \")\")",
"key = lambda x: x[\"name\"].upper()) # Create quality_changes group items quality_changes_item_list = []",
"# Sort by quality names item_list = sorted(item_list, key = lambda x: x[\"name\"].upper())",
"(plugin_id, meta_data). def _getIOPlugins(self, io_type): from UM.PluginRegistry import PluginRegistry pr = PluginRegistry.getInstance() active_plugin_ids",
"show self.setItems([]) return item_list = [] # Create quality group items for quality_group",
"pr.getActivePlugins() result = [] for plugin_id in active_plugin_ids: meta_data = pr.getMetaData(plugin_id) if io_type",
"convenience meta-filters # \"All Supported Types\" and \"All Files\" are added when listing",
"readers, add the option to show all supported files as the default option",
"[] for quality_changes_group in quality_changes_group_dict.values(): if quality_changes_group.quality_type not in available_quality_types: continue quality_group =",
"self._machine_manager.globalContainerChanged.connect(self._update) self._quality_manager.qualitiesUpdated.connect(self._update) self._update() def _update(self): Logger.log(\"d\", \"Updating {model_class_name}.\".format(model_class_name = self.__class__.__name__)) global_stack = self._machine_manager.activeMachine",
"QualityGroupRole = Qt.UserRole + 3 QualityChangesGroupRole = Qt.UserRole + 4 def __init__(self, parent",
"from UM.PluginRegistry import PluginRegistry pr = PluginRegistry.getInstance() active_plugin_ids = pr.getActivePlugins() result = []",
"+ 2 QualityGroupRole = Qt.UserRole + 3 QualityChangesGroupRole = Qt.UserRole + 4 def",
"\"All Supported Types ({0})\", \" \".join(all_types))) filters.append(catalog.i18nc(\"@item:inlistbox\", \"All Files (*)\")) # Also allow",
"of (plugin_id, meta_data). def _getIOPlugins(self, io_type): from UM.PluginRegistry import PluginRegistry pr = PluginRegistry.getInstance()",
"x: x[\"name\"].upper()) item_list += quality_changes_item_list self.setItems(item_list) # TODO: Duplicated code here from InstanceContainersModel.",
"for the quality management page. # class QualityManagementModel(ListModel): NameRole = Qt.UserRole + 1",
"all supported files as the default option filters.insert(0, catalog.i18nc(\"@item:inlistbox\", \"All Supported Types ({0})\",",
"= self._quality_manager.getQualityChangesGroups(global_stack) available_quality_types = set(quality_type for quality_type, quality_group in quality_group_dict.items() if quality_group.is_available) if",
"code here from InstanceContainersModel. Refactor and remove this later. # ## Gets a",
"pyqtSlot from UM.Qt.ListModel import ListModel from UM.Logger import Logger # # This the",
"# \\return List of tuples of (plugin_id, meta_data). def _getIOPlugins(self, io_type): from UM.PluginRegistry",
"all_types.append(\"*.{0}\".format(io_plugin[\"extension\"])) if \"_reader\" in io_type: # if we're listing readers, add the option",
"= Qt.UserRole + 4 def __init__(self, parent = None): super().__init__(parent) self.addRoleName(self.NameRole, \"name\") self.addRoleName(self.IsReadOnlyRole,",
"a list of profile reader or writer plugins # \\return List of tuples",
"= CuraApplication.getInstance().getQualityManager() self._machine_manager.globalContainerChanged.connect(self._update) self._quality_manager.qualitiesUpdated.connect(self._update) self._update() def _update(self): Logger.log(\"d\", \"Updating {model_class_name}.\".format(model_class_name = self.__class__.__name__)) global_stack",
"= PluginRegistry.getInstance() active_plugin_ids = pr.getActivePlugins() result = [] for plugin_id in active_plugin_ids: meta_data",
"import CuraApplication self._container_registry = CuraApplication.getInstance().getContainerRegistry() self._machine_manager = CuraApplication.getInstance().getMachineManager() self._extruder_manager = CuraApplication.getInstance().getExtruderManager() self._quality_manager =",
"\"All Files\" are added when listing # readers, but not when listing writers.",
"quality_changes_group_dict = self._quality_manager.getQualityChangesGroups(global_stack) available_quality_types = set(quality_type for quality_type, quality_group in quality_group_dict.items() if quality_group.is_available)",
"# # \\param io_type \\type{str} name of the needed IO type # \\return",
"listing writers. # # \\param io_type \\type{str} name of the needed IO type",
"self._machine_manager = CuraApplication.getInstance().getMachineManager() self._extruder_manager = CuraApplication.getInstance().getExtruderManager() self._quality_manager = CuraApplication.getInstance().getQualityManager() self._machine_manager.globalContainerChanged.connect(self._update) self._quality_manager.qualitiesUpdated.connect(self._update) self._update() def",
"self._update() def _update(self): Logger.log(\"d\", \"Updating {model_class_name}.\".format(model_class_name = self.__class__.__name__)) global_stack = self._machine_manager.activeMachine if not",
"(c) 2018 <NAME>. # Cura is released under the terms of the LGPLv3",
"model for the quality management page. # class QualityManagementModel(ListModel): NameRole = Qt.UserRole +",
"# class QualityManagementModel(ListModel): NameRole = Qt.UserRole + 1 IsReadOnlyRole = Qt.UserRole + 2",
"True, \"quality_group\": quality_group, \"quality_changes_group\": None} item_list.append(item) # Sort by quality names item_list =",
"\\type{str} name of the needed IO type # \\return A list of strings",
"in io_type: # if we're listing readers, add the option to show all",
"{\"name\": quality_group.name, \"is_read_only\": True, \"quality_group\": quality_group, \"quality_changes_group\": None} item_list.append(item) # Sort by quality",
"quality_changes_item_list = [] for quality_changes_group in quality_changes_group_dict.values(): if quality_changes_group.quality_type not in available_quality_types: continue",
"of the needed IO type # \\return A list of strings indicating file",
"of tuples of (plugin_id, meta_data). def _getIOPlugins(self, io_type): from UM.PluginRegistry import PluginRegistry pr",
"result = [] for plugin_id in active_plugin_ids: meta_data = pr.getMetaData(plugin_id) if io_type in",
"writer plugins # \\return List of tuples of (plugin_id, meta_data). def _getIOPlugins(self, io_type):",
"# Copyright (c) 2018 <NAME>. # Cura is released under the terms of",
"item_list += quality_changes_item_list self.setItems(item_list) # TODO: Duplicated code here from InstanceContainersModel. Refactor and",
"filters.append(io_plugin[\"description\"] + \" (*.\" + io_plugin[\"extension\"] + \")\") all_types.append(\"*.{0}\".format(io_plugin[\"extension\"])) if \"_reader\" in io_type:",
"\"Updating {model_class_name}.\".format(model_class_name = self.__class__.__name__)) global_stack = self._machine_manager.activeMachine if not global_stack: self.setItems([]) return quality_group_dict",
"not available_quality_types and not quality_changes_group_dict: # Nothing to show self.setItems([]) return item_list =",
"## Gets a list of the possible file filters that the plugins have",
"_getIOPlugins(self, io_type): from UM.PluginRegistry import PluginRegistry pr = PluginRegistry.getInstance() active_plugin_ids = pr.getActivePlugins() result",
"higher. from PyQt5.QtCore import Qt, pyqtSlot from UM.Qt.ListModel import ListModel from UM.Logger import",
"1 IsReadOnlyRole = Qt.UserRole + 2 QualityGroupRole = Qt.UserRole + 3 QualityChangesGroupRole =",
"{\"name\": quality_changes_group.name, \"is_read_only\": False, \"quality_group\": quality_group, \"quality_changes_group\": quality_changes_group} quality_changes_item_list.append(item) # Sort quality_changes items",
"x: x[\"name\"].upper()) # Create quality_changes group items quality_changes_item_list = [] for quality_changes_group in",
"\"quality_group\": quality_group, \"quality_changes_group\": quality_changes_group} quality_changes_item_list.append(item) # Sort quality_changes items by names and append",
"the possible file filters that the plugins have # registered they can read",
"in available_quality_types: continue quality_group = quality_group_dict[quality_changes_group.quality_type] item = {\"name\": quality_changes_group.name, \"is_read_only\": False, \"quality_group\":",
"\".join(all_types))) filters.append(catalog.i18nc(\"@item:inlistbox\", \"All Files (*)\")) # Also allow arbitrary files, if the user",
"pr = PluginRegistry.getInstance() active_plugin_ids = pr.getActivePlugins() result = [] for plugin_id in active_plugin_ids:",
"import i18nCatalog catalog = i18nCatalog(\"uranium\") #TODO: This function should be in UM.Resources! filters",
"continue quality_group = quality_group_dict[quality_changes_group.quality_type] item = {\"name\": quality_changes_group.name, \"is_read_only\": False, \"quality_group\": quality_group, \"quality_changes_group\":",
"= pr.getActivePlugins() result = [] for plugin_id in active_plugin_ids: meta_data = pr.getMetaData(plugin_id) if",
"the terms of the LGPLv3 or higher. from PyQt5.QtCore import Qt, pyqtSlot from",
"for quality_type, quality_group in quality_group_dict.items() if quality_group.is_available) if not available_quality_types and not quality_changes_group_dict:",
"# Sort quality_changes items by names and append to the item list quality_changes_item_list",
"not quality_group.is_available: continue item = {\"name\": quality_group.name, \"is_read_only\": True, \"quality_group\": quality_group, \"quality_changes_group\": None}",
"self._extruder_manager = CuraApplication.getInstance().getExtruderManager() self._quality_manager = CuraApplication.getInstance().getQualityManager() self._machine_manager.globalContainerChanged.connect(self._update) self._quality_manager.qualitiesUpdated.connect(self._update) self._update() def _update(self): Logger.log(\"d\", \"Updating",
"file # dialog. @pyqtSlot(str, result = \"QVariantList\") def getFileNameFilters(self, io_type): from UM.i18n import",
"in UM.Resources! filters = [] all_types = [] for plugin_id, meta_data in self._getIOPlugins(io_type):",
"Logger # # This the QML model for the quality management page. #",
"Duplicated code here from InstanceContainersModel. Refactor and remove this later. # ## Gets",
"= i18nCatalog(\"uranium\") #TODO: This function should be in UM.Resources! filters = [] all_types",
"QML model for the quality management page. # class QualityManagementModel(ListModel): NameRole = Qt.UserRole",
"[] for plugin_id, meta_data in self._getIOPlugins(io_type): for io_plugin in meta_data[io_type]: filters.append(io_plugin[\"description\"] + \"",
"\\param io_type \\type{str} name of the needed IO type # \\return A list",
"here from InstanceContainersModel. Refactor and remove this later. # ## Gets a list",
"of the possible file filters that the plugins have # registered they can",
"and not quality_changes_group_dict: # Nothing to show self.setItems([]) return item_list = [] #",
"= [] all_types = [] for plugin_id, meta_data in self._getIOPlugins(io_type): for io_plugin in",
"reader or writer plugins # \\return List of tuples of (plugin_id, meta_data). def",
"CuraApplication.getInstance().getContainerRegistry() self._machine_manager = CuraApplication.getInstance().getMachineManager() self._extruder_manager = CuraApplication.getInstance().getExtruderManager() self._quality_manager = CuraApplication.getInstance().getQualityManager() self._machine_manager.globalContainerChanged.connect(self._update) self._quality_manager.qualitiesUpdated.connect(self._update) self._update()",
"of profile reader or writer plugins # \\return List of tuples of (plugin_id,",
"item_list = sorted(item_list, key = lambda x: x[\"name\"].upper()) # Create quality_changes group items",
"+ 3 QualityChangesGroupRole = Qt.UserRole + 4 def __init__(self, parent = None): super().__init__(parent)",
"+ io_plugin[\"extension\"] + \")\") all_types.append(\"*.{0}\".format(io_plugin[\"extension\"])) if \"_reader\" in io_type: # if we're listing",
"sorted(quality_changes_item_list, key = lambda x: x[\"name\"].upper()) item_list += quality_changes_item_list self.setItems(item_list) # TODO: Duplicated",
"Cura is released under the terms of the LGPLv3 or higher. from PyQt5.QtCore",
"getFileNameFilters(self, io_type): from UM.i18n import i18nCatalog catalog = i18nCatalog(\"uranium\") #TODO: This function should",
"plugin_id in active_plugin_ids: meta_data = pr.getMetaData(plugin_id) if io_type in meta_data: result.append( (plugin_id, meta_data)",
"from UM.Logger import Logger # # This the QML model for the quality",
"Logger.log(\"d\", \"Updating {model_class_name}.\".format(model_class_name = self.__class__.__name__)) global_stack = self._machine_manager.activeMachine if not global_stack: self.setItems([]) return",
"# TODO: Duplicated code here from InstanceContainersModel. Refactor and remove this later. #",
"cura.CuraApplication import CuraApplication self._container_registry = CuraApplication.getInstance().getContainerRegistry() self._machine_manager = CuraApplication.getInstance().getMachineManager() self._extruder_manager = CuraApplication.getInstance().getExtruderManager() self._quality_manager",
"Files\" are added when listing # readers, but not when listing writers. #",
"quality_group_dict.items() if quality_group.is_available) if not available_quality_types and not quality_changes_group_dict: # Nothing to show",
"UM.Resources! filters = [] all_types = [] for plugin_id, meta_data in self._getIOPlugins(io_type): for",
"file name filters for a file # dialog. @pyqtSlot(str, result = \"QVariantList\") def",
"lambda x: x[\"name\"].upper()) item_list += quality_changes_item_list self.setItems(item_list) # TODO: Duplicated code here from",
"Qt.UserRole + 3 QualityChangesGroupRole = Qt.UserRole + 4 def __init__(self, parent = None):",
"to the item list quality_changes_item_list = sorted(quality_changes_item_list, key = lambda x: x[\"name\"].upper()) item_list",
"function should be in UM.Resources! filters = [] all_types = [] for plugin_id,",
"import Logger # # This the QML model for the quality management page.",
"the user so prefers. return filters ## Gets a list of profile reader",
"active_plugin_ids: meta_data = pr.getMetaData(plugin_id) if io_type in meta_data: result.append( (plugin_id, meta_data) ) return",
"UM.i18n import i18nCatalog catalog = i18nCatalog(\"uranium\") #TODO: This function should be in UM.Resources!",
"quality_changes_group_dict.values(): if quality_changes_group.quality_type not in available_quality_types: continue quality_group = quality_group_dict[quality_changes_group.quality_type] item = {\"name\":",
"(*)\")) # Also allow arbitrary files, if the user so prefers. return filters",
"= {\"name\": quality_changes_group.name, \"is_read_only\": False, \"quality_group\": quality_group, \"quality_changes_group\": quality_changes_group} quality_changes_item_list.append(item) # Sort quality_changes",
"if not quality_group.is_available: continue item = {\"name\": quality_group.name, \"is_read_only\": True, \"quality_group\": quality_group, \"quality_changes_group\":",
"\"All Files (*)\")) # Also allow arbitrary files, if the user so prefers.",
"QualityManagementModel(ListModel): NameRole = Qt.UserRole + 1 IsReadOnlyRole = Qt.UserRole + 2 QualityGroupRole =",
"add the option to show all supported files as the default option filters.insert(0,",
"Nothing to show self.setItems([]) return item_list = [] # Create quality group items",
"class QualityManagementModel(ListModel): NameRole = Qt.UserRole + 1 IsReadOnlyRole = Qt.UserRole + 2 QualityGroupRole",
"if quality_changes_group.quality_type not in available_quality_types: continue quality_group = quality_group_dict[quality_changes_group.quality_type] item = {\"name\": quality_changes_group.name,",
"when listing # readers, but not when listing writers. # # \\param io_type",
"names item_list = sorted(item_list, key = lambda x: x[\"name\"].upper()) # Create quality_changes group",
"\"quality_changes_group\") from cura.CuraApplication import CuraApplication self._container_registry = CuraApplication.getInstance().getContainerRegistry() self._machine_manager = CuraApplication.getInstance().getMachineManager() self._extruder_manager =",
"UM.PluginRegistry import PluginRegistry pr = PluginRegistry.getInstance() active_plugin_ids = pr.getActivePlugins() result = [] for",
"# dialog. @pyqtSlot(str, result = \"QVariantList\") def getFileNameFilters(self, io_type): from UM.i18n import i18nCatalog",
"a file # dialog. @pyqtSlot(str, result = \"QVariantList\") def getFileNameFilters(self, io_type): from UM.i18n",
"io_type): from UM.i18n import i18nCatalog catalog = i18nCatalog(\"uranium\") #TODO: This function should be",
"({0})\", \" \".join(all_types))) filters.append(catalog.i18nc(\"@item:inlistbox\", \"All Files (*)\")) # Also allow arbitrary files, if",
"\"name\") self.addRoleName(self.IsReadOnlyRole, \"is_read_only\") self.addRoleName(self.QualityGroupRole, \"quality_group\") self.addRoleName(self.QualityChangesGroupRole, \"quality_changes_group\") from cura.CuraApplication import CuraApplication self._container_registry =",
"parent = None): super().__init__(parent) self.addRoleName(self.NameRole, \"name\") self.addRoleName(self.IsReadOnlyRole, \"is_read_only\") self.addRoleName(self.QualityGroupRole, \"quality_group\") self.addRoleName(self.QualityChangesGroupRole, \"quality_changes_group\") from",
"items quality_changes_item_list = [] for quality_changes_group in quality_changes_group_dict.values(): if quality_changes_group.quality_type not in available_quality_types:",
"list of the possible file filters that the plugins have # registered they",
"are added when listing # readers, but not when listing writers. # #",
"global_stack = self._machine_manager.activeMachine if not global_stack: self.setItems([]) return quality_group_dict = self._quality_manager.getQualityGroups(global_stack) quality_changes_group_dict =",
"if not available_quality_types and not quality_changes_group_dict: # Nothing to show self.setItems([]) return item_list",
"# \\param io_type \\type{str} name of the needed IO type # \\return A",
"from InstanceContainersModel. Refactor and remove this later. # ## Gets a list of",
"Create quality_changes group items quality_changes_item_list = [] for quality_changes_group in quality_changes_group_dict.values(): if quality_changes_group.quality_type",
"Create quality group items for quality_group in quality_group_dict.values(): if not quality_group.is_available: continue item",
"listing readers, add the option to show all supported files as the default",
"2 QualityGroupRole = Qt.UserRole + 3 QualityChangesGroupRole = Qt.UserRole + 4 def __init__(self,",
"Refactor and remove this later. # ## Gets a list of the possible",
"catalog.i18nc(\"@item:inlistbox\", \"All Supported Types ({0})\", \" \".join(all_types))) filters.append(catalog.i18nc(\"@item:inlistbox\", \"All Files (*)\")) # Also",
"from UM.Qt.ListModel import ListModel from UM.Logger import Logger # # This the QML",
"quality_changes_group.name, \"is_read_only\": False, \"quality_group\": quality_group, \"quality_changes_group\": quality_changes_group} quality_changes_item_list.append(item) # Sort quality_changes items by",
"or write. The convenience meta-filters # \"All Supported Types\" and \"All Files\" are",
"they can read or write. The convenience meta-filters # \"All Supported Types\" and",
"but not when listing writers. # # \\param io_type \\type{str} name of the",
"items for quality_group in quality_group_dict.values(): if not quality_group.is_available: continue item = {\"name\": quality_group.name,",
"filters.insert(0, catalog.i18nc(\"@item:inlistbox\", \"All Supported Types ({0})\", \" \".join(all_types))) filters.append(catalog.i18nc(\"@item:inlistbox\", \"All Files (*)\")) #",
"super().__init__(parent) self.addRoleName(self.NameRole, \"name\") self.addRoleName(self.IsReadOnlyRole, \"is_read_only\") self.addRoleName(self.QualityGroupRole, \"quality_group\") self.addRoleName(self.QualityChangesGroupRole, \"quality_changes_group\") from cura.CuraApplication import CuraApplication",
"in quality_group_dict.items() if quality_group.is_available) if not available_quality_types and not quality_changes_group_dict: # Nothing to",
"+= quality_changes_item_list self.setItems(item_list) # TODO: Duplicated code here from InstanceContainersModel. Refactor and remove",
"when listing writers. # # \\param io_type \\type{str} name of the needed IO",
"filters for a file # dialog. @pyqtSlot(str, result = \"QVariantList\") def getFileNameFilters(self, io_type):",
"in quality_group_dict.values(): if not quality_group.is_available: continue item = {\"name\": quality_group.name, \"is_read_only\": True, \"quality_group\":",
"active_plugin_ids = pr.getActivePlugins() result = [] for plugin_id in active_plugin_ids: meta_data = pr.getMetaData(plugin_id)",
"profile reader or writer plugins # \\return List of tuples of (plugin_id, meta_data).",
"by names and append to the item list quality_changes_item_list = sorted(quality_changes_item_list, key =",
"and remove this later. # ## Gets a list of the possible file",
"self._quality_manager.getQualityChangesGroups(global_stack) available_quality_types = set(quality_type for quality_type, quality_group in quality_group_dict.items() if quality_group.is_available) if not",
"\")\") all_types.append(\"*.{0}\".format(io_plugin[\"extension\"])) if \"_reader\" in io_type: # if we're listing readers, add the",
"available_quality_types and not quality_changes_group_dict: # Nothing to show self.setItems([]) return item_list = []",
"+ \")\") all_types.append(\"*.{0}\".format(io_plugin[\"extension\"])) if \"_reader\" in io_type: # if we're listing readers, add",
"\"_reader\" in io_type: # if we're listing readers, add the option to show",
"Sort by quality names item_list = sorted(item_list, key = lambda x: x[\"name\"].upper()) #",
"= CuraApplication.getInstance().getMachineManager() self._extruder_manager = CuraApplication.getInstance().getExtruderManager() self._quality_manager = CuraApplication.getInstance().getQualityManager() self._machine_manager.globalContainerChanged.connect(self._update) self._quality_manager.qualitiesUpdated.connect(self._update) self._update() def _update(self):",
"self._container_registry = CuraApplication.getInstance().getContainerRegistry() self._machine_manager = CuraApplication.getInstance().getMachineManager() self._extruder_manager = CuraApplication.getInstance().getExtruderManager() self._quality_manager = CuraApplication.getInstance().getQualityManager() self._machine_manager.globalContainerChanged.connect(self._update)",
"\"quality_group\": quality_group, \"quality_changes_group\": None} item_list.append(item) # Sort by quality names item_list = sorted(item_list,",
"quality_group, \"quality_changes_group\": quality_changes_group} quality_changes_item_list.append(item) # Sort quality_changes items by names and append to",
"the item list quality_changes_item_list = sorted(quality_changes_item_list, key = lambda x: x[\"name\"].upper()) item_list +=",
"def getFileNameFilters(self, io_type): from UM.i18n import i18nCatalog catalog = i18nCatalog(\"uranium\") #TODO: This function",
"files as the default option filters.insert(0, catalog.i18nc(\"@item:inlistbox\", \"All Supported Types ({0})\", \" \".join(all_types)))",
"list of profile reader or writer plugins # \\return List of tuples of",
"or writer plugins # \\return List of tuples of (plugin_id, meta_data). def _getIOPlugins(self,",
"Types\" and \"All Files\" are added when listing # readers, but not when",
"3 QualityChangesGroupRole = Qt.UserRole + 4 def __init__(self, parent = None): super().__init__(parent) self.addRoleName(self.NameRole,",
"read or write. The convenience meta-filters # \"All Supported Types\" and \"All Files\"",
"i18nCatalog catalog = i18nCatalog(\"uranium\") #TODO: This function should be in UM.Resources! filters =",
"None} item_list.append(item) # Sort by quality names item_list = sorted(item_list, key = lambda",
"CuraApplication.getInstance().getExtruderManager() self._quality_manager = CuraApplication.getInstance().getQualityManager() self._machine_manager.globalContainerChanged.connect(self._update) self._quality_manager.qualitiesUpdated.connect(self._update) self._update() def _update(self): Logger.log(\"d\", \"Updating {model_class_name}.\".format(model_class_name =",
"be in UM.Resources! filters = [] all_types = [] for plugin_id, meta_data in",
"plugin_id, meta_data in self._getIOPlugins(io_type): for io_plugin in meta_data[io_type]: filters.append(io_plugin[\"description\"] + \" (*.\" +",
"item_list.append(item) # Sort by quality names item_list = sorted(item_list, key = lambda x:",
"self.addRoleName(self.QualityChangesGroupRole, \"quality_changes_group\") from cura.CuraApplication import CuraApplication self._container_registry = CuraApplication.getInstance().getContainerRegistry() self._machine_manager = CuraApplication.getInstance().getMachineManager() self._extruder_manager",
"to show all supported files as the default option filters.insert(0, catalog.i18nc(\"@item:inlistbox\", \"All Supported",
"CuraApplication self._container_registry = CuraApplication.getInstance().getContainerRegistry() self._machine_manager = CuraApplication.getInstance().getMachineManager() self._extruder_manager = CuraApplication.getInstance().getExtruderManager() self._quality_manager = CuraApplication.getInstance().getQualityManager()",
"self.addRoleName(self.QualityGroupRole, \"quality_group\") self.addRoleName(self.QualityChangesGroupRole, \"quality_changes_group\") from cura.CuraApplication import CuraApplication self._container_registry = CuraApplication.getInstance().getContainerRegistry() self._machine_manager =",
"lambda x: x[\"name\"].upper()) # Create quality_changes group items quality_changes_item_list = [] for quality_changes_group",
"not when listing writers. # # \\param io_type \\type{str} name of the needed",
"# Create quality group items for quality_group in quality_group_dict.values(): if not quality_group.is_available: continue",
"option filters.insert(0, catalog.i18nc(\"@item:inlistbox\", \"All Supported Types ({0})\", \" \".join(all_types))) filters.append(catalog.i18nc(\"@item:inlistbox\", \"All Files (*)\"))",
"quality_group.is_available) if not available_quality_types and not quality_changes_group_dict: # Nothing to show self.setItems([]) return",
"import ListModel from UM.Logger import Logger # # This the QML model for",
"quality_group.is_available: continue item = {\"name\": quality_group.name, \"is_read_only\": True, \"quality_group\": quality_group, \"quality_changes_group\": None} item_list.append(item)",
"# Cura is released under the terms of the LGPLv3 or higher. from",
"filters ## Gets a list of profile reader or writer plugins # \\return",
"\"is_read_only\": True, \"quality_group\": quality_group, \"quality_changes_group\": None} item_list.append(item) # Sort by quality names item_list",
"added when listing # readers, but not when listing writers. # # \\param",
"= CuraApplication.getInstance().getContainerRegistry() self._machine_manager = CuraApplication.getInstance().getMachineManager() self._extruder_manager = CuraApplication.getInstance().getExtruderManager() self._quality_manager = CuraApplication.getInstance().getQualityManager() self._machine_manager.globalContainerChanged.connect(self._update) self._quality_manager.qualitiesUpdated.connect(self._update)",
"self._machine_manager.activeMachine if not global_stack: self.setItems([]) return quality_group_dict = self._quality_manager.getQualityGroups(global_stack) quality_changes_group_dict = self._quality_manager.getQualityChangesGroups(global_stack) available_quality_types",
"# Nothing to show self.setItems([]) return item_list = [] # Create quality group",
"PluginRegistry.getInstance() active_plugin_ids = pr.getActivePlugins() result = [] for plugin_id in active_plugin_ids: meta_data =",
"the LGPLv3 or higher. from PyQt5.QtCore import Qt, pyqtSlot from UM.Qt.ListModel import ListModel",
"CuraApplication.getInstance().getMachineManager() self._extruder_manager = CuraApplication.getInstance().getExtruderManager() self._quality_manager = CuraApplication.getInstance().getQualityManager() self._machine_manager.globalContainerChanged.connect(self._update) self._quality_manager.qualitiesUpdated.connect(self._update) self._update() def _update(self): Logger.log(\"d\",",
"result = \"QVariantList\") def getFileNameFilters(self, io_type): from UM.i18n import i18nCatalog catalog = i18nCatalog(\"uranium\")",
"from cura.CuraApplication import CuraApplication self._container_registry = CuraApplication.getInstance().getContainerRegistry() self._machine_manager = CuraApplication.getInstance().getMachineManager() self._extruder_manager = CuraApplication.getInstance().getExtruderManager()",
"Qt.UserRole + 4 def __init__(self, parent = None): super().__init__(parent) self.addRoleName(self.NameRole, \"name\") self.addRoleName(self.IsReadOnlyRole, \"is_read_only\")",
"= [] for plugin_id in active_plugin_ids: meta_data = pr.getMetaData(plugin_id) if io_type in meta_data:",
"This function should be in UM.Resources! filters = [] all_types = [] for",
"meta_data = pr.getMetaData(plugin_id) if io_type in meta_data: result.append( (plugin_id, meta_data) ) return result",
"quality_changes items by names and append to the item list quality_changes_item_list = sorted(quality_changes_item_list,",
"IsReadOnlyRole = Qt.UserRole + 2 QualityGroupRole = Qt.UserRole + 3 QualityChangesGroupRole = Qt.UserRole",
"item list quality_changes_item_list = sorted(quality_changes_item_list, key = lambda x: x[\"name\"].upper()) item_list += quality_changes_item_list",
"io_plugin in meta_data[io_type]: filters.append(io_plugin[\"description\"] + \" (*.\" + io_plugin[\"extension\"] + \")\") all_types.append(\"*.{0}\".format(io_plugin[\"extension\"])) if",
"the default option filters.insert(0, catalog.i18nc(\"@item:inlistbox\", \"All Supported Types ({0})\", \" \".join(all_types))) filters.append(catalog.i18nc(\"@item:inlistbox\", \"All",
"should be in UM.Resources! filters = [] all_types = [] for plugin_id, meta_data",
"if we're listing readers, add the option to show all supported files as",
"quality_group_dict[quality_changes_group.quality_type] item = {\"name\": quality_changes_group.name, \"is_read_only\": False, \"quality_group\": quality_group, \"quality_changes_group\": quality_changes_group} quality_changes_item_list.append(item) #",
"writers. # # \\param io_type \\type{str} name of the needed IO type #",
"of strings indicating file name filters for a file # dialog. @pyqtSlot(str, result",
"= sorted(item_list, key = lambda x: x[\"name\"].upper()) # Create quality_changes group items quality_changes_item_list",
"def __init__(self, parent = None): super().__init__(parent) self.addRoleName(self.NameRole, \"name\") self.addRoleName(self.IsReadOnlyRole, \"is_read_only\") self.addRoleName(self.QualityGroupRole, \"quality_group\") self.addRoleName(self.QualityChangesGroupRole,",
"quality group items for quality_group in quality_group_dict.values(): if not quality_group.is_available: continue item =",
"io_type): from UM.PluginRegistry import PluginRegistry pr = PluginRegistry.getInstance() active_plugin_ids = pr.getActivePlugins() result =",
"[] for plugin_id in active_plugin_ids: meta_data = pr.getMetaData(plugin_id) if io_type in meta_data: result.append(",
"def _getIOPlugins(self, io_type): from UM.PluginRegistry import PluginRegistry pr = PluginRegistry.getInstance() active_plugin_ids = pr.getActivePlugins()",
"= [] # Create quality group items for quality_group in quality_group_dict.values(): if not",
"plugins # \\return List of tuples of (plugin_id, meta_data). def _getIOPlugins(self, io_type): from",
"we're listing readers, add the option to show all supported files as the",
"if not global_stack: self.setItems([]) return quality_group_dict = self._quality_manager.getQualityGroups(global_stack) quality_changes_group_dict = self._quality_manager.getQualityChangesGroups(global_stack) available_quality_types =",
"quality_changes_item_list = sorted(quality_changes_item_list, key = lambda x: x[\"name\"].upper()) item_list += quality_changes_item_list self.setItems(item_list) #",
"meta_data in self._getIOPlugins(io_type): for io_plugin in meta_data[io_type]: filters.append(io_plugin[\"description\"] + \" (*.\" + io_plugin[\"extension\"]",
"A list of strings indicating file name filters for a file # dialog.",
"Gets a list of profile reader or writer plugins # \\return List of",
"show all supported files as the default option filters.insert(0, catalog.i18nc(\"@item:inlistbox\", \"All Supported Types",
"@pyqtSlot(str, result = \"QVariantList\") def getFileNameFilters(self, io_type): from UM.i18n import i18nCatalog catalog =",
"have # registered they can read or write. The convenience meta-filters # \"All",
"not global_stack: self.setItems([]) return quality_group_dict = self._quality_manager.getQualityGroups(global_stack) quality_changes_group_dict = self._quality_manager.getQualityChangesGroups(global_stack) available_quality_types = set(quality_type",
"ListModel from UM.Logger import Logger # # This the QML model for the",
"key = lambda x: x[\"name\"].upper()) item_list += quality_changes_item_list self.setItems(item_list) # TODO: Duplicated code",
"4 def __init__(self, parent = None): super().__init__(parent) self.addRoleName(self.NameRole, \"name\") self.addRoleName(self.IsReadOnlyRole, \"is_read_only\") self.addRoleName(self.QualityGroupRole, \"quality_group\")",
"self._quality_manager = CuraApplication.getInstance().getQualityManager() self._machine_manager.globalContainerChanged.connect(self._update) self._quality_manager.qualitiesUpdated.connect(self._update) self._update() def _update(self): Logger.log(\"d\", \"Updating {model_class_name}.\".format(model_class_name = self.__class__.__name__))",
"None): super().__init__(parent) self.addRoleName(self.NameRole, \"name\") self.addRoleName(self.IsReadOnlyRole, \"is_read_only\") self.addRoleName(self.QualityGroupRole, \"quality_group\") self.addRoleName(self.QualityChangesGroupRole, \"quality_changes_group\") from cura.CuraApplication import",
"the QML model for the quality management page. # class QualityManagementModel(ListModel): NameRole =",
"io_type: # if we're listing readers, add the option to show all supported",
"and append to the item list quality_changes_item_list = sorted(quality_changes_item_list, key = lambda x:",
"allow arbitrary files, if the user so prefers. return filters ## Gets a",
"needed IO type # \\return A list of strings indicating file name filters",
"= lambda x: x[\"name\"].upper()) item_list += quality_changes_item_list self.setItems(item_list) # TODO: Duplicated code here",
"self.__class__.__name__)) global_stack = self._machine_manager.activeMachine if not global_stack: self.setItems([]) return quality_group_dict = self._quality_manager.getQualityGroups(global_stack) quality_changes_group_dict",
"\" \".join(all_types))) filters.append(catalog.i18nc(\"@item:inlistbox\", \"All Files (*)\")) # Also allow arbitrary files, if the",
"= {\"name\": quality_group.name, \"is_read_only\": True, \"quality_group\": quality_group, \"quality_changes_group\": None} item_list.append(item) # Sort by",
"self._quality_manager.getQualityGroups(global_stack) quality_changes_group_dict = self._quality_manager.getQualityChangesGroups(global_stack) available_quality_types = set(quality_type for quality_type, quality_group in quality_group_dict.items() if",
"for quality_group in quality_group_dict.values(): if not quality_group.is_available: continue item = {\"name\": quality_group.name, \"is_read_only\":",
"available_quality_types: continue quality_group = quality_group_dict[quality_changes_group.quality_type] item = {\"name\": quality_changes_group.name, \"is_read_only\": False, \"quality_group\": quality_group,",
"filters = [] all_types = [] for plugin_id, meta_data in self._getIOPlugins(io_type): for io_plugin",
"# registered they can read or write. The convenience meta-filters # \"All Supported",
"return item_list = [] # Create quality group items for quality_group in quality_group_dict.values():",
"to show self.setItems([]) return item_list = [] # Create quality group items for",
"available_quality_types = set(quality_type for quality_type, quality_group in quality_group_dict.items() if quality_group.is_available) if not available_quality_types",
"default option filters.insert(0, catalog.i18nc(\"@item:inlistbox\", \"All Supported Types ({0})\", \" \".join(all_types))) filters.append(catalog.i18nc(\"@item:inlistbox\", \"All Files",
"\"is_read_only\": False, \"quality_group\": quality_group, \"quality_changes_group\": quality_changes_group} quality_changes_item_list.append(item) # Sort quality_changes items by names",
"\\return A list of strings indicating file name filters for a file #",
"Qt.UserRole + 1 IsReadOnlyRole = Qt.UserRole + 2 QualityGroupRole = Qt.UserRole + 3",
"the quality management page. # class QualityManagementModel(ListModel): NameRole = Qt.UserRole + 1 IsReadOnlyRole",
"+ \" (*.\" + io_plugin[\"extension\"] + \")\") all_types.append(\"*.{0}\".format(io_plugin[\"extension\"])) if \"_reader\" in io_type: #",
"{model_class_name}.\".format(model_class_name = self.__class__.__name__)) global_stack = self._machine_manager.activeMachine if not global_stack: self.setItems([]) return quality_group_dict =",
"item = {\"name\": quality_changes_group.name, \"is_read_only\": False, \"quality_group\": quality_group, \"quality_changes_group\": quality_changes_group} quality_changes_item_list.append(item) # Sort",
"= None): super().__init__(parent) self.addRoleName(self.NameRole, \"name\") self.addRoleName(self.IsReadOnlyRole, \"is_read_only\") self.addRoleName(self.QualityGroupRole, \"quality_group\") self.addRoleName(self.QualityChangesGroupRole, \"quality_changes_group\") from cura.CuraApplication",
"self.addRoleName(self.NameRole, \"name\") self.addRoleName(self.IsReadOnlyRole, \"is_read_only\") self.addRoleName(self.QualityGroupRole, \"quality_group\") self.addRoleName(self.QualityChangesGroupRole, \"quality_changes_group\") from cura.CuraApplication import CuraApplication self._container_registry",
"Sort quality_changes items by names and append to the item list quality_changes_item_list =",
"quality_changes_group in quality_changes_group_dict.values(): if quality_changes_group.quality_type not in available_quality_types: continue quality_group = quality_group_dict[quality_changes_group.quality_type] item",
"file filters that the plugins have # registered they can read or write.",
"(*.\" + io_plugin[\"extension\"] + \")\") all_types.append(\"*.{0}\".format(io_plugin[\"extension\"])) if \"_reader\" in io_type: # if we're",
"PyQt5.QtCore import Qt, pyqtSlot from UM.Qt.ListModel import ListModel from UM.Logger import Logger #",
"# if we're listing readers, add the option to show all supported files",
"not in available_quality_types: continue quality_group = quality_group_dict[quality_changes_group.quality_type] item = {\"name\": quality_changes_group.name, \"is_read_only\": False,",
"plugins have # registered they can read or write. The convenience meta-filters #",
"quality_changes_group_dict: # Nothing to show self.setItems([]) return item_list = [] # Create quality",
"InstanceContainersModel. Refactor and remove this later. # ## Gets a list of the",
"tuples of (plugin_id, meta_data). def _getIOPlugins(self, io_type): from UM.PluginRegistry import PluginRegistry pr =",
"quality_group in quality_group_dict.values(): if not quality_group.is_available: continue item = {\"name\": quality_group.name, \"is_read_only\": True,",
"sorted(item_list, key = lambda x: x[\"name\"].upper()) # Create quality_changes group items quality_changes_item_list =",
"continue item = {\"name\": quality_group.name, \"is_read_only\": True, \"quality_group\": quality_group, \"quality_changes_group\": None} item_list.append(item) #",
"filters.append(catalog.i18nc(\"@item:inlistbox\", \"All Files (*)\")) # Also allow arbitrary files, if the user so",
"Copyright (c) 2018 <NAME>. # Cura is released under the terms of the",
"x[\"name\"].upper()) item_list += quality_changes_item_list self.setItems(item_list) # TODO: Duplicated code here from InstanceContainersModel. Refactor",
"Files (*)\")) # Also allow arbitrary files, if the user so prefers. return",
"self.setItems([]) return item_list = [] # Create quality group items for quality_group in",
"strings indicating file name filters for a file # dialog. @pyqtSlot(str, result =",
"list of strings indicating file name filters for a file # dialog. @pyqtSlot(str,",
"quality names item_list = sorted(item_list, key = lambda x: x[\"name\"].upper()) # Create quality_changes",
"registered they can read or write. The convenience meta-filters # \"All Supported Types\"",
"\"quality_group\") self.addRoleName(self.QualityChangesGroupRole, \"quality_changes_group\") from cura.CuraApplication import CuraApplication self._container_registry = CuraApplication.getInstance().getContainerRegistry() self._machine_manager = CuraApplication.getInstance().getMachineManager()",
"io_type \\type{str} name of the needed IO type # \\return A list of",
"supported files as the default option filters.insert(0, catalog.i18nc(\"@item:inlistbox\", \"All Supported Types ({0})\", \"",
"as the default option filters.insert(0, catalog.i18nc(\"@item:inlistbox\", \"All Supported Types ({0})\", \" \".join(all_types))) filters.append(catalog.i18nc(\"@item:inlistbox\",",
"group items quality_changes_item_list = [] for quality_changes_group in quality_changes_group_dict.values(): if quality_changes_group.quality_type not in",
"PluginRegistry pr = PluginRegistry.getInstance() active_plugin_ids = pr.getActivePlugins() result = [] for plugin_id in",
"the plugins have # registered they can read or write. The convenience meta-filters",
"\"quality_changes_group\": quality_changes_group} quality_changes_item_list.append(item) # Sort quality_changes items by names and append to the",
"from PyQt5.QtCore import Qt, pyqtSlot from UM.Qt.ListModel import ListModel from UM.Logger import Logger",
"\" (*.\" + io_plugin[\"extension\"] + \")\") all_types.append(\"*.{0}\".format(io_plugin[\"extension\"])) if \"_reader\" in io_type: # if",
"import PluginRegistry pr = PluginRegistry.getInstance() active_plugin_ids = pr.getActivePlugins() result = [] for plugin_id",
"global_stack: self.setItems([]) return quality_group_dict = self._quality_manager.getQualityGroups(global_stack) quality_changes_group_dict = self._quality_manager.getQualityChangesGroups(global_stack) available_quality_types = set(quality_type for",
"= \"QVariantList\") def getFileNameFilters(self, io_type): from UM.i18n import i18nCatalog catalog = i18nCatalog(\"uranium\") #TODO:",
"quality_changes_item_list.append(item) # Sort quality_changes items by names and append to the item list",
"is released under the terms of the LGPLv3 or higher. from PyQt5.QtCore import",
"set(quality_type for quality_type, quality_group in quality_group_dict.items() if quality_group.is_available) if not available_quality_types and not",
"quality_group_dict.values(): if not quality_group.is_available: continue item = {\"name\": quality_group.name, \"is_read_only\": True, \"quality_group\": quality_group,",
"UM.Logger import Logger # # This the QML model for the quality management",
"names and append to the item list quality_changes_item_list = sorted(quality_changes_item_list, key = lambda",
"for a file # dialog. @pyqtSlot(str, result = \"QVariantList\") def getFileNameFilters(self, io_type): from",
"the option to show all supported files as the default option filters.insert(0, catalog.i18nc(\"@item:inlistbox\",",
"quality_group = quality_group_dict[quality_changes_group.quality_type] item = {\"name\": quality_changes_group.name, \"is_read_only\": False, \"quality_group\": quality_group, \"quality_changes_group\": quality_changes_group}",
"if the user so prefers. return filters ## Gets a list of profile",
"_update(self): Logger.log(\"d\", \"Updating {model_class_name}.\".format(model_class_name = self.__class__.__name__)) global_stack = self._machine_manager.activeMachine if not global_stack: self.setItems([])",
"for plugin_id, meta_data in self._getIOPlugins(io_type): for io_plugin in meta_data[io_type]: filters.append(io_plugin[\"description\"] + \" (*.\"",
"return filters ## Gets a list of profile reader or writer plugins #",
"page. # class QualityManagementModel(ListModel): NameRole = Qt.UserRole + 1 IsReadOnlyRole = Qt.UserRole +",
"NameRole = Qt.UserRole + 1 IsReadOnlyRole = Qt.UserRole + 2 QualityGroupRole = Qt.UserRole",
"import Qt, pyqtSlot from UM.Qt.ListModel import ListModel from UM.Logger import Logger # #",
"False, \"quality_group\": quality_group, \"quality_changes_group\": quality_changes_group} quality_changes_item_list.append(item) # Sort quality_changes items by names and",
"= self.__class__.__name__)) global_stack = self._machine_manager.activeMachine if not global_stack: self.setItems([]) return quality_group_dict = self._quality_manager.getQualityGroups(global_stack)",
"\"QVariantList\") def getFileNameFilters(self, io_type): from UM.i18n import i18nCatalog catalog = i18nCatalog(\"uranium\") #TODO: This",
"QualityChangesGroupRole = Qt.UserRole + 4 def __init__(self, parent = None): super().__init__(parent) self.addRoleName(self.NameRole, \"name\")",
"can read or write. The convenience meta-filters # \"All Supported Types\" and \"All",
"files, if the user so prefers. return filters ## Gets a list of",
"management page. # class QualityManagementModel(ListModel): NameRole = Qt.UserRole + 1 IsReadOnlyRole = Qt.UserRole",
"if quality_group.is_available) if not available_quality_types and not quality_changes_group_dict: # Nothing to show self.setItems([])",
"listing # readers, but not when listing writers. # # \\param io_type \\type{str}",
"quality_changes_group} quality_changes_item_list.append(item) # Sort quality_changes items by names and append to the item",
"= set(quality_type for quality_type, quality_group in quality_group_dict.items() if quality_group.is_available) if not available_quality_types and",
"[] all_types = [] for plugin_id, meta_data in self._getIOPlugins(io_type): for io_plugin in meta_data[io_type]:",
"io_plugin[\"extension\"] + \")\") all_types.append(\"*.{0}\".format(io_plugin[\"extension\"])) if \"_reader\" in io_type: # if we're listing readers,",
"#TODO: This function should be in UM.Resources! filters = [] all_types = []",
"= CuraApplication.getInstance().getExtruderManager() self._quality_manager = CuraApplication.getInstance().getQualityManager() self._machine_manager.globalContainerChanged.connect(self._update) self._quality_manager.qualitiesUpdated.connect(self._update) self._update() def _update(self): Logger.log(\"d\", \"Updating {model_class_name}.\".format(model_class_name",
"# Also allow arbitrary files, if the user so prefers. return filters ##",
"UM.Qt.ListModel import ListModel from UM.Logger import Logger # # This the QML model",
"+ 1 IsReadOnlyRole = Qt.UserRole + 2 QualityGroupRole = Qt.UserRole + 3 QualityChangesGroupRole",
"for quality_changes_group in quality_changes_group_dict.values(): if quality_changes_group.quality_type not in available_quality_types: continue quality_group = quality_group_dict[quality_changes_group.quality_type]",
"a list of the possible file filters that the plugins have # registered",
"# readers, but not when listing writers. # # \\param io_type \\type{str} name",
"append to the item list quality_changes_item_list = sorted(quality_changes_item_list, key = lambda x: x[\"name\"].upper())",
"__init__(self, parent = None): super().__init__(parent) self.addRoleName(self.NameRole, \"name\") self.addRoleName(self.IsReadOnlyRole, \"is_read_only\") self.addRoleName(self.QualityGroupRole, \"quality_group\") self.addRoleName(self.QualityChangesGroupRole, \"quality_changes_group\")",
"and \"All Files\" are added when listing # readers, but not when listing",
"\"quality_changes_group\": None} item_list.append(item) # Sort by quality names item_list = sorted(item_list, key =",
"user so prefers. return filters ## Gets a list of profile reader or",
"# \\return A list of strings indicating file name filters for a file",
"so prefers. return filters ## Gets a list of profile reader or writer",
"self.setItems([]) return quality_group_dict = self._quality_manager.getQualityGroups(global_stack) quality_changes_group_dict = self._quality_manager.getQualityChangesGroups(global_stack) available_quality_types = set(quality_type for quality_type,",
"\\return List of tuples of (plugin_id, meta_data). def _getIOPlugins(self, io_type): from UM.PluginRegistry import",
"Also allow arbitrary files, if the user so prefers. return filters ## Gets",
"LGPLv3 or higher. from PyQt5.QtCore import Qt, pyqtSlot from UM.Qt.ListModel import ListModel from"
] |
[
"from backward feature selection from: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_selection/rfe.py Given an external estimator that assigns weights",
"False, False], dtype=bool) >>> selector.ranking_ array([1, 1, 1, 1, 1, 6, 4, 3,",
"shape [n_samples, n_features] The input samples. Returns ------- y : array of shape",
"import BaseEstimator from sklearn.base import MetaEstimatorMixin from sklearn.base import clone from sklearn.base import",
"import clone from sklearn.base import is_classifier from sklearn.cross_validation import _check_cv as check_cv from",
"y = make_friedman1(n_samples=50, n_features=10, random_state=0) >>> estimator = SVR(kernel=\"linear\") >>> selector = RFE(estimator,",
"forward feature selection (FFS) is to select features by recursively considering larger and",
"\" \"parameter is no longer necessary because the value \" \"is set via",
"\"feature_importances_\" ' 'attributes') # Get ranks if coefs.ndim > 1: ranks = np.argsort(safe_sqr(coefs).sum(axis=0))[::-1]",
"Given an external estimator that assigns weights to features (e.g., the coefficients of",
"np.zeros(n_features, dtype=np.bool) support_[0] = True ranking_ = np.zeros(n_features, dtype=np.int) ranking_[0] = 1 if",
"number of selected features. support_ : array of shape [n_features] The mask of",
": array of shape [n_samples] The target values. \"\"\" return self.estimator_.score(self.transform(X), y) def",
"The training input samples. y : array-like, shape = [n_samples] The target values.",
"5 right informative features in the Friedman #1 dataset. >>> from sklearn.datasets import",
"if self.estimator_params is not None: warnings.warn(\"The parameter 'estimator_params' is deprecated as \" \"of",
"greater than or equal to 1, then `step` corresponds to the (integer) number",
"int(max(1, self.step * n_features)) else: step = int(self.step) if step <= 0: raise",
"y) >>> selector.support_ # doctest: +NORMALIZE_WHITESPACE array([ True, True, True, True, True, False,",
"each one of them. Then, features whose absolute weights are the smallest are",
"int or float, optional (default=1) If greater than or equal to 1, then",
"if self.estimator_params: estimator.set_params(**self.estimator_params) if self.verbose > 0: print(\"Fitting estimator with %d features.\" %",
"set_params method instead. verbose : int, default=0 Controls verbosity of output. Attributes ----------",
": int The number of selected features. support_ : array of shape [n_features]",
"and will be removed in 0.18. The \" \"parameter is no longer necessary",
"from sklearn.base import clone from sklearn.base import is_classifier from sklearn.cross_validation import _check_cv as",
"weights are the smallest are pruned from the current set features. That procedure",
"<rfe>`. Parameters ---------- estimator : object A supervised learning estimator with a `fit`",
"and then return the score of the underlying estimator. Parameters ---------- X :",
"def _fit(self, X, y, step_score=None): #X, y = check_X_y(X, y, \"csc\") # Initialization",
"to select features by recursively considering larger and larger sets of features. First,",
"of a linear model), the goal of forward feature selection (FFS) is to",
"X : array of shape [n_samples, n_features] The input samples. Returns ------- y",
"MetaEstimatorMixin, SelectorMixin): \"\"\"Feature ranking with forward feature selection. Modification from backward feature selection",
"shape [n_features] The mask of selected features. ranking_ : array of shape [n_features]",
"import _safe_split, _score from sklearn.metrics.scorer import check_scoring from sklearn.feature_selection.base import SelectorMixin class FFS(BaseEstimator,",
"method instead. verbose : int, default=0 Controls verbosity of output. Attributes ---------- n_features_",
"the selected features and then return the score of the underlying estimator. Parameters",
"return self.support_ @if_delegate_has_method(delegate='estimator') def decision_function(self, X): return self.estimator_.decision_function(self.transform(X)) @if_delegate_has_method(delegate='estimator') def predict_proba(self, X): return",
"'\"coef_\" or \"feature_importances_\" ' 'attributes') # Get ranks if coefs.ndim > 1: ranks",
"y : array of shape [n_samples] The predicted target values. \"\"\" return self.estimator_.predict(self.transform(X))",
"while np.sum(support_) < n_features_to_select: # Remaining features features = np.arange(n_features)[support_] # Rank the",
"array-like, shape = [n_samples] The target values. \"\"\" return self._fit(X, y) def _fit(self,",
"that updates a `coef_` attribute that holds the fitted parameters. Important features must",
"The target values. \"\"\" return self.estimator_.score(self.transform(X), y) def _get_support_mask(self): return self.support_ @if_delegate_has_method(delegate='estimator') def",
"of the features are selected. step : int or float, optional (default=1) If",
"' 'attributes') # Get ranks if coefs.ndim > 1: ranks = np.argsort(safe_sqr(coefs).sum(axis=0))[::-1] else:",
"predict using the underlying estimator. Parameters ---------- X : array of shape [n_samples,",
"5]) References ---------- .. [1] <NAME>., <NAME>., <NAME>., & <NAME>., \"Gene selection for",
"support_.sum() self.support_ = support_ self.ranking_ = ranking_ return self @if_delegate_has_method(delegate='estimator') def predict(self, X):",
"n_features_to_select self.step = step self.estimator_params = estimator_params self.verbose = verbose @property def _estimator_type(self):",
"with %d features.\" % np.sum(support_)) estimator.fit(X[:, features], y) # Get coefs if hasattr(estimator,",
"to the ranking position of the i-th feature. Selected (i.e., estimated best) features",
"self.estimator_params = estimator_params self.verbose = verbose @property def _estimator_type(self): return self.estimator._estimator_type def fit(self,",
"X : {array-like, sparse matrix}, shape = [n_samples, n_features] The training input samples.",
"np.arange(n_features)[support_] self.estimator_ = clone(self.estimator) if self.estimator_params: self.estimator_.set_params(**self.estimator_params) self.estimator_.fit(X[:, features], y) # Compute step",
"if self.estimator_params: self.estimator_.set_params(**self.estimator_params) self.estimator_.fit(X[:, features], y) # Compute step score when only n_features_to_select",
"reduced dataset. Examples -------- The following example shows how to retrieve the 5",
"sklearn.base import is_classifier from sklearn.cross_validation import _check_cv as check_cv from sklearn.cross_validation import _safe_split,",
"the value \" \"is set via the estimator initialisation or \" \"set_params method.\",",
"# because 'estimator' must use features # that have not been eliminated yet",
"set features. That procedure is recursively repeated on the pruned set until the",
"or set_params method instead. verbose : int, default=0 Controls verbosity of output. Attributes",
"= self.n_features_to_select if 0.0 < self.step < 1.0: step = int(max(1, self.step *",
"by recursively considering larger and larger sets of features. First, the estimator is",
"values in the `coef_` array. For instance, this is the case for most",
"BaseEstimator from sklearn.base import MetaEstimatorMixin from sklearn.base import clone from sklearn.base import is_classifier",
"self.ranking_ = ranking_ return self @if_delegate_has_method(delegate='estimator') def predict(self, X): \"\"\"Reduce X to the",
"larger sets of features. First, the estimator is trained on the initial set",
"def fit(self, X, y): \"\"\"Fit the RFE model and then the underlying estimator",
"+NORMALIZE_WHITESPACE array([ True, True, True, True, True, False, False, False, False, False], dtype=bool)",
"\"\"\"Feature ranking with forward feature selection. Modification from backward feature selection from: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_selection/rfe.py",
"[n_samples, n_features] The input samples. y : array of shape [n_samples] The target",
"estimator initialisation or set_params method instead. verbose : int, default=0 Controls verbosity of",
"_get_support_mask(self): return self.support_ @if_delegate_has_method(delegate='estimator') def decision_function(self, X): return self.estimator_.decision_function(self.transform(X)) @if_delegate_has_method(delegate='estimator') def predict_proba(self, X):",
"clone(self.estimator) if self.estimator_params: estimator.set_params(**self.estimator_params) if self.verbose > 0: print(\"Fitting estimator with %d features.\"",
"assigned rank 1. estimator_ : object The external estimator fit on the reduced",
"True ranking_ = np.zeros(n_features, dtype=np.int) ranking_[0] = 1 if step_score: self.scores_ = []",
"= ranking_ return self @if_delegate_has_method(delegate='estimator') def predict(self, X): \"\"\"Reduce X to the selected",
"np.arange(n_features)[support_] # Rank the remaining features estimator = clone(self.estimator) if self.estimator_params: estimator.set_params(**self.estimator_params) if",
"estimator_params=None, verbose=0): self.estimator = estimator self.n_features_to_select = n_features_to_select self.step = step self.estimator_params =",
"int The number of selected features. support_ : array of shape [n_features] The",
"rank 1. estimator_ : object The external estimator fit on the reduced dataset.",
"# Eliminate the worse features threshold = min(step, n_features_to_select - np.sum(support_)) # Compute",
"sklearn.base import BaseEstimator from sklearn.base import MetaEstimatorMixin from sklearn.base import clone from sklearn.base",
"int or None (default=None) The number of features to select. If `None`, half",
"If greater than or equal to 1, then `step` corresponds to the (integer)",
"self.scores_.append(step_score(estimator, features)) support_[features[ranks][:threshold]] = True ranking_[np.logical_not(support_)] += 1 # Set final attributes features",
"to remove at each iteration. If within (0.0, 1.0), then `step` corresponds to",
"considering larger and larger sets of features. First, the estimator is trained on",
"are assigned to each one of them. Then, features whose absolute weights are",
"iteration. estimator_params : dict Parameters for the external estimator. This attribute is deprecated",
"Parameters ---------- estimator : object A supervised learning estimator with a `fit` method",
"[n_samples] The predicted target values. \"\"\" return self.estimator_.predict(self.transform(X)) @if_delegate_has_method(delegate='estimator') def score(self, X, y):",
"parameters. Important features must correspond to high absolute values in the `coef_` array.",
"features)) support_[features[ranks][:threshold]] = True ranking_[np.logical_not(support_)] += 1 # Set final attributes features =",
"self.verbose > 0: print(\"Fitting estimator with %d features.\" % np.sum(support_)) estimator.fit(X[:, features], y)",
"`fit` method that updates a `coef_` attribute that holds the fitted parameters. Important",
"(e.g., the coefficients of a linear model), the goal of forward feature selection",
"< n_features_to_select: # Remaining features features = np.arange(n_features)[support_] # Rank the remaining features",
"score of the underlying estimator. Parameters ---------- X : array of shape [n_samples,",
"desired number of features to select is eventually reached. Read more in the",
"[1] <NAME>., <NAME>., <NAME>., & <NAME>., \"Gene selection for cancer classification using support",
"that have not been eliminated yet if step_score: self.scores_.append(step_score(estimator, features)) support_[features[ranks][:threshold]] = True",
"remove at each iteration. If within (0.0, 1.0), then `step` corresponds to the",
"within (0.0, 1.0), then `step` corresponds to the percentage (rounded down) of features",
"of selected features. support_ : array of shape [n_features] The mask of selected",
"selector.ranking_ array([1, 1, 1, 1, 1, 6, 4, 3, 2, 5]) References ----------",
"The input samples. y : array of shape [n_samples] The target values. \"\"\"",
"selected features. support_ : array of shape [n_features] The mask of selected features.",
"coefs = estimator.feature_importances_ else: raise RuntimeError('The classifier does not expose ' '\"coef_\" or",
"1, then `step` corresponds to the (integer) number of features to remove at",
"# Compute step score when only n_features_to_select features left if step_score: self.scores_.append(step_score(self.estimator_, features))",
"of the underlying estimator. Parameters ---------- X : array of shape [n_samples, n_features]",
"= estimator_params self.verbose = verbose @property def _estimator_type(self): return self.estimator._estimator_type def fit(self, X,",
"reached. Read more in the :ref:`User Guide <rfe>`. Parameters ---------- estimator : object",
"is_classifier from sklearn.cross_validation import _check_cv as check_cv from sklearn.cross_validation import _safe_split, _score from",
"shape [n_features] The feature ranking, such that ``ranking_[i]`` corresponds to the ranking position",
"shape [n_samples] The target values. \"\"\" return self.estimator_.score(self.transform(X), y) def _get_support_mask(self): return self.support_",
"method.\", DeprecationWarning) support_ = np.zeros(n_features, dtype=np.bool) support_[0] = True ranking_ = np.zeros(n_features, dtype=np.int)",
"i-th feature. Selected (i.e., estimated best) features are assigned rank 1. estimator_ :",
"or None (default=None) The number of features to select. If `None`, half of",
"is not None: warnings.warn(\"The parameter 'estimator_params' is deprecated as \" \"of version 0.16",
"to select is eventually reached. Read more in the :ref:`User Guide <rfe>`. Parameters",
"= SVR(kernel=\"linear\") >>> selector = RFE(estimator, 5, step=1) >>> selector = selector.fit(X, y)",
": object A supervised learning estimator with a `fit` method that updates a",
"sparse matrix}, shape = [n_samples, n_features] The training input samples. y : array-like,",
"of shape [n_samples] The target values. \"\"\" return self.estimator_.score(self.transform(X), y) def _get_support_mask(self): return",
"None (default=None) The number of features to select. If `None`, half of the",
"The predicted target values. \"\"\" return self.estimator_.predict(self.transform(X)) @if_delegate_has_method(delegate='estimator') def score(self, X, y): \"\"\"Reduce",
"Rank the remaining features estimator = clone(self.estimator) if self.estimator_params: estimator.set_params(**self.estimator_params) if self.verbose >",
"' '\"coef_\" or \"feature_importances_\" ' 'attributes') # Get ranks if coefs.ndim > 1:",
"3, 2, 5]) References ---------- .. [1] <NAME>., <NAME>., <NAME>., & <NAME>., \"Gene",
"training input samples. y : array-like, shape = [n_samples] The target values. \"\"\"",
"array([ True, True, True, True, True, False, False, False, False, False], dtype=bool) >>>",
"First, the estimator is trained on the initial set of features and weights",
"and weights are assigned to each one of them. Then, features whose absolute",
"support_ = np.zeros(n_features, dtype=np.bool) support_[0] = True ranking_ = np.zeros(n_features, dtype=np.int) ranking_[0] =",
"the previous selection iteration # because 'estimator' must use features # that have",
": array of shape [n_features] The feature ranking, such that ``ranking_[i]`` corresponds to",
"import if_delegate_has_method from sklearn.base import BaseEstimator from sklearn.base import MetaEstimatorMixin from sklearn.base import",
"Returns ------- y : array of shape [n_samples] The predicted target values. \"\"\"",
"the features are selected. step : int or float, optional (default=1) If greater",
"y, \"csc\") # Initialization n_features = X.shape[1] if self.n_features_to_select is None: n_features_to_select =",
"external estimator that assigns weights to features (e.g., the coefficients of a linear",
"the pruned set until the desired number of features to select is eventually",
"selection (FFS) is to select features by recursively considering larger and larger sets",
"(default=1) If greater than or equal to 1, then `step` corresponds to the",
">>> selector = RFE(estimator, 5, step=1) >>> selector = selector.fit(X, y) >>> selector.support_",
"ranks = np.ravel(ranks) # Eliminate the worse features threshold = min(step, n_features_to_select -",
"high absolute values in the `coef_` array. For instance, this is the case",
"self.n_features_to_select = n_features_to_select self.step = step self.estimator_params = estimator_params self.verbose = verbose @property",
"Compute step score when only n_features_to_select features left if step_score: self.scores_.append(step_score(self.estimator_, features)) self.n_features_",
"holds the fitted parameters. Important features must correspond to high absolute values in",
"self.estimator_.fit(X[:, features], y) # Compute step score when only n_features_to_select features left if",
"matrix ranks = np.ravel(ranks) # Eliminate the worse features threshold = min(step, n_features_to_select",
"case for most supervised learning algorithms such as Support Vector Classifiers and Generalized",
"self.estimator_.set_params(**self.estimator_params) self.estimator_.fit(X[:, features], y) # Compute step score when only n_features_to_select features left",
"be removed in 0.18. The \" \"parameter is no longer necessary because the",
"Remaining features features = np.arange(n_features)[support_] # Rank the remaining features estimator = clone(self.estimator)",
"doctest: +NORMALIZE_WHITESPACE array([ True, True, True, True, True, False, False, False, False, False],",
"return self._fit(X, y) def _fit(self, X, y, step_score=None): #X, y = check_X_y(X, y,",
"such that ``ranking_[i]`` corresponds to the ranking position of the i-th feature. Selected",
"that ``ranking_[i]`` corresponds to the ranking position of the i-th feature. Selected (i.e.,",
"pruned from the current set features. That procedure is recursively repeated on the",
"default=0 Controls verbosity of output. Attributes ---------- n_features_ : int The number of",
"ranking_ = np.zeros(n_features, dtype=np.int) ranking_[0] = 1 if step_score: self.scores_ = [] #",
"np.sum(support_)) # Compute step score on the previous selection iteration # because 'estimator'",
">>> from sklearn.feature_selection import RFE >>> from sklearn.svm import SVR >>> X, y",
"n_features)) else: step = int(self.step) if step <= 0: raise ValueError(\"Step must be",
"equal to 1, then `step` corresponds to the (integer) number of features to",
"@property def _estimator_type(self): return self.estimator._estimator_type def fit(self, X, y): \"\"\"Fit the RFE model",
"selector.support_ # doctest: +NORMALIZE_WHITESPACE array([ True, True, True, True, True, False, False, False,",
"the `coef_` array. For instance, this is the case for most supervised learning",
"---------- .. [1] <NAME>., <NAME>., <NAME>., & <NAME>., \"Gene selection for cancer classification",
"0: raise ValueError(\"Step must be >0\") if self.estimator_params is not None: warnings.warn(\"The parameter",
"= X.shape[1] if self.n_features_to_select is None: n_features_to_select = n_features // 2 else: n_features_to_select",
"will be removed in 0.18. The \" \"parameter is no longer necessary because",
"from sklearn.datasets import make_friedman1 >>> from sklearn.feature_selection import RFE >>> from sklearn.svm import",
">>> selector.support_ # doctest: +NORMALIZE_WHITESPACE array([ True, True, True, True, True, False, False,",
"does not expose ' '\"coef_\" or \"feature_importances_\" ' 'attributes') # Get ranks if",
"_score from sklearn.metrics.scorer import check_scoring from sklearn.feature_selection.base import SelectorMixin class FFS(BaseEstimator, MetaEstimatorMixin, SelectorMixin):",
"Models from the `svm` and `linear_model` modules. n_features_to_select : int or None (default=None)",
"input samples. Returns ------- y : array of shape [n_samples] The predicted target",
"= [] # Elimination while np.sum(support_) < n_features_to_select: # Remaining features features =",
".. [1] <NAME>., <NAME>., <NAME>., & <NAME>., \"Gene selection for cancer classification using",
"or float, optional (default=1) If greater than or equal to 1, then `step`",
"or equal to 1, then `step` corresponds to the (integer) number of features",
"hasattr(estimator, 'feature_importances_'): coefs = estimator.feature_importances_ else: raise RuntimeError('The classifier does not expose '",
"`coef_` attribute that holds the fitted parameters. Important features must correspond to high",
"as \" \"of version 0.16 and will be removed in 0.18. The \"",
"the :ref:`User Guide <rfe>`. Parameters ---------- estimator : object A supervised learning estimator",
"self.estimator_.decision_function(self.transform(X)) @if_delegate_has_method(delegate='estimator') def predict_proba(self, X): return self.estimator_.predict_proba(self.transform(X)) @if_delegate_has_method(delegate='estimator') def predict_log_proba(self, X): return self.estimator_.predict_log_proba(self.transform(X))",
"algorithms such as Support Vector Classifiers and Generalized Linear Models from the `svm`",
"of version 0.16 and will be removed in 0.18. Use estimator initialisation or",
"<NAME>., & <NAME>., \"Gene selection for cancer classification using support vector machines\", Mach.",
"---------- estimator : object A supervised learning estimator with a `fit` method that",
"procedure is recursively repeated on the pruned set until the desired number of",
"object The external estimator fit on the reduced dataset. Examples -------- The following",
"dataset. Examples -------- The following example shows how to retrieve the 5 right",
":ref:`User Guide <rfe>`. Parameters ---------- estimator : object A supervised learning estimator with",
": {array-like, sparse matrix}, shape = [n_samples, n_features] The training input samples. y",
"import warnings import numpy as np from sklearn.utils import check_X_y, safe_sqr from sklearn.utils.metaestimators",
"self.scores_ = [] # Elimination while np.sum(support_) < n_features_to_select: # Remaining features features",
"Initialization n_features = X.shape[1] if self.n_features_to_select is None: n_features_to_select = n_features // 2",
"= estimator.feature_importances_ else: raise RuntimeError('The classifier does not expose ' '\"coef_\" or \"feature_importances_\"",
"Use estimator initialisation or set_params method instead. verbose : int, default=0 Controls verbosity",
": array of shape [n_samples] The predicted target values. \"\"\" return self.estimator_.predict(self.transform(X)) @if_delegate_has_method(delegate='estimator')",
"the current set features. That procedure is recursively repeated on the pruned set",
"<NAME>., <NAME>., & <NAME>., \"Gene selection for cancer classification using support vector machines\",",
"iteration. If within (0.0, 1.0), then `step` corresponds to the percentage (rounded down)",
"#X, y = check_X_y(X, y, \"csc\") # Initialization n_features = X.shape[1] if self.n_features_to_select",
"modules. n_features_to_select : int or None (default=None) The number of features to select.",
"Parameters ---------- X : array of shape [n_samples, n_features] The input samples. Returns",
"output. Attributes ---------- n_features_ : int The number of selected features. support_ :",
"% np.sum(support_)) estimator.fit(X[:, features], y) # Get coefs if hasattr(estimator, 'coef_'): coefs =",
"# Compute step score on the previous selection iteration # because 'estimator' must",
"np.argsort(safe_sqr(coefs))[::-1] # for sparse case ranks is matrix ranks = np.ravel(ranks) # Eliminate",
"features left if step_score: self.scores_.append(step_score(self.estimator_, features)) self.n_features_ = support_.sum() self.support_ = support_ self.ranking_",
"\"\"\" return self.estimator_.score(self.transform(X), y) def _get_support_mask(self): return self.support_ @if_delegate_has_method(delegate='estimator') def decision_function(self, X): return",
"= int(self.step) if step <= 0: raise ValueError(\"Step must be >0\") if self.estimator_params",
"self.step = step self.estimator_params = estimator_params self.verbose = verbose @property def _estimator_type(self): return",
"predict(self, X): \"\"\"Reduce X to the selected features and then predict using the",
"in the :ref:`User Guide <rfe>`. Parameters ---------- estimator : object A supervised learning",
"min(step, n_features_to_select - np.sum(support_)) # Compute step score on the previous selection iteration",
"backward feature selection from: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_selection/rfe.py Given an external estimator that assigns weights to",
"5, step=1) >>> selector = selector.fit(X, y) >>> selector.support_ # doctest: +NORMALIZE_WHITESPACE array([",
"estimator on the selected features. Parameters ---------- X : {array-like, sparse matrix}, shape",
"\"\"\" def __init__(self, estimator, n_features_to_select=None, step=1, estimator_params=None, verbose=0): self.estimator = estimator self.n_features_to_select =",
"to the percentage (rounded down) of features to remove at each iteration. estimator_params",
"set until the desired number of features to select is eventually reached. Read",
"shape = [n_samples, n_features] The training input samples. y : array-like, shape =",
"Then, features whose absolute weights are the smallest are pruned from the current",
"The following example shows how to retrieve the 5 right informative features in",
"self.scores_.append(step_score(self.estimator_, features)) self.n_features_ = support_.sum() self.support_ = support_ self.ranking_ = ranking_ return self",
"is the case for most supervised learning algorithms such as Support Vector Classifiers",
"eventually reached. Read more in the :ref:`User Guide <rfe>`. Parameters ---------- estimator :",
"from sklearn.utils.metaestimators import if_delegate_has_method from sklearn.base import BaseEstimator from sklearn.base import MetaEstimatorMixin from",
"to the (integer) number of features to remove at each iteration. If within",
"on the selected features. Parameters ---------- X : {array-like, sparse matrix}, shape =",
"final attributes features = np.arange(n_features)[support_] self.estimator_ = clone(self.estimator) if self.estimator_params: self.estimator_.set_params(**self.estimator_params) self.estimator_.fit(X[:, features],",
"True, True, True, True, False, False, False, False, False], dtype=bool) >>> selector.ranking_ array([1,",
"Parameters ---------- X : array of shape [n_samples, n_features] The input samples. y",
"as Support Vector Classifiers and Generalized Linear Models from the `svm` and `linear_model`",
"ranking with forward feature selection. Modification from backward feature selection from: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_selection/rfe.py Given",
"as of version 0.16 and will be removed in 0.18. Use estimator initialisation",
"y : array-like, shape = [n_samples] The target values. \"\"\" return self._fit(X, y)",
"must use features # that have not been eliminated yet if step_score: self.scores_.append(step_score(estimator,",
"= clone(self.estimator) if self.estimator_params: self.estimator_.set_params(**self.estimator_params) self.estimator_.fit(X[:, features], y) # Compute step score when",
"support_[0] = True ranking_ = np.zeros(n_features, dtype=np.int) ranking_[0] = 1 if step_score: self.scores_",
"how to retrieve the 5 right informative features in the Friedman #1 dataset.",
"the 5 right informative features in the Friedman #1 dataset. >>> from sklearn.datasets",
"been eliminated yet if step_score: self.scores_.append(step_score(estimator, features)) support_[features[ranks][:threshold]] = True ranking_[np.logical_not(support_)] += 1",
"correspond to high absolute values in the `coef_` array. For instance, this is",
"set via the estimator initialisation or \" \"set_params method.\", DeprecationWarning) support_ = np.zeros(n_features,",
"then the underlying estimator on the selected features. Parameters ---------- X : {array-like,",
"X, y): \"\"\"Reduce X to the selected features and then return the score",
"not been eliminated yet if step_score: self.scores_.append(step_score(estimator, features)) support_[features[ranks][:threshold]] = True ranking_[np.logical_not(support_)] +=",
"in 0.18. Use estimator initialisation or set_params method instead. verbose : int, default=0",
"instead. verbose : int, default=0 Controls verbosity of output. Attributes ---------- n_features_ :",
"<NAME>., \"Gene selection for cancer classification using support vector machines\", Mach. Learn., 46(1-3),",
"most supervised learning algorithms such as Support Vector Classifiers and Generalized Linear Models",
"sklearn.metrics.scorer import check_scoring from sklearn.feature_selection.base import SelectorMixin class FFS(BaseEstimator, MetaEstimatorMixin, SelectorMixin): \"\"\"Feature ranking",
"np.sum(support_) < n_features_to_select: # Remaining features features = np.arange(n_features)[support_] # Rank the remaining",
"set of features and weights are assigned to each one of them. Then,",
"= True ranking_ = np.zeros(n_features, dtype=np.int) ranking_[0] = 1 if step_score: self.scores_ =",
"corresponds to the percentage (rounded down) of features to remove at each iteration.",
"feature. Selected (i.e., estimated best) features are assigned rank 1. estimator_ : object",
"whose absolute weights are the smallest are pruned from the current set features.",
"then return the score of the underlying estimator. Parameters ---------- X : array",
"if step_score: self.scores_.append(step_score(self.estimator_, features)) self.n_features_ = support_.sum() self.support_ = support_ self.ranking_ = ranking_",
"y) # Get coefs if hasattr(estimator, 'coef_'): coefs = estimator.coef_ elif hasattr(estimator, 'feature_importances_'):",
"y): \"\"\"Reduce X to the selected features and then return the score of",
"of the i-th feature. Selected (i.e., estimated best) features are assigned rank 1.",
"and then the underlying estimator on the selected features. Parameters ---------- X :",
"= True ranking_[np.logical_not(support_)] += 1 # Set final attributes features = np.arange(n_features)[support_] self.estimator_",
"are pruned from the current set features. That procedure is recursively repeated on",
"# Set final attributes features = np.arange(n_features)[support_] self.estimator_ = clone(self.estimator) if self.estimator_params: self.estimator_.set_params(**self.estimator_params)",
"X to the selected features and then return the score of the underlying",
"fit(self, X, y): \"\"\"Fit the RFE model and then the underlying estimator on",
": object The external estimator fit on the reduced dataset. Examples -------- The",
"_fit(self, X, y, step_score=None): #X, y = check_X_y(X, y, \"csc\") # Initialization n_features",
": array of shape [n_samples, n_features] The input samples. Returns ------- y :",
"X, y, step_score=None): #X, y = check_X_y(X, y, \"csc\") # Initialization n_features =",
"the goal of forward feature selection (FFS) is to select features by recursively",
"= check_X_y(X, y, \"csc\") # Initialization n_features = X.shape[1] if self.n_features_to_select is None:",
"remove at each iteration. estimator_params : dict Parameters for the external estimator. This",
"from sklearn.base import is_classifier from sklearn.cross_validation import _check_cv as check_cv from sklearn.cross_validation import",
"The external estimator fit on the reduced dataset. Examples -------- The following example",
"\"Gene selection for cancer classification using support vector machines\", Mach. Learn., 46(1-3), 389--422,",
"underlying estimator. Parameters ---------- X : array of shape [n_samples, n_features] The input",
"selection for cancer classification using support vector machines\", Mach. Learn., 46(1-3), 389--422, 2002.",
"percentage (rounded down) of features to remove at each iteration. estimator_params : dict",
"the smallest are pruned from the current set features. That procedure is recursively",
"in the `coef_` array. For instance, this is the case for most supervised",
"True, False, False, False, False, False], dtype=bool) >>> selector.ranking_ array([1, 1, 1, 1,",
"absolute values in the `coef_` array. For instance, this is the case for",
"Attributes ---------- n_features_ : int The number of selected features. support_ : array",
"`step` corresponds to the percentage (rounded down) of features to remove at each",
"step=1, estimator_params=None, verbose=0): self.estimator = estimator self.n_features_to_select = n_features_to_select self.step = step self.estimator_params",
"features estimator = clone(self.estimator) if self.estimator_params: estimator.set_params(**self.estimator_params) if self.verbose > 0: print(\"Fitting estimator",
"for most supervised learning algorithms such as Support Vector Classifiers and Generalized Linear",
"0.16 and will be removed in 0.18. Use estimator initialisation or set_params method",
"attributes features = np.arange(n_features)[support_] self.estimator_ = clone(self.estimator) if self.estimator_params: self.estimator_.set_params(**self.estimator_params) self.estimator_.fit(X[:, features], y)",
"of features to remove at each iteration. If within (0.0, 1.0), then `step`",
"None: warnings.warn(\"The parameter 'estimator_params' is deprecated as \" \"of version 0.16 and will",
"[n_samples] The target values. \"\"\" return self._fit(X, y) def _fit(self, X, y, step_score=None):",
"target values. \"\"\" return self.estimator_.predict(self.transform(X)) @if_delegate_has_method(delegate='estimator') def score(self, X, y): \"\"\"Reduce X to",
"verbose=0): self.estimator = estimator self.n_features_to_select = n_features_to_select self.step = step self.estimator_params = estimator_params",
"self.estimator._estimator_type def fit(self, X, y): \"\"\"Fit the RFE model and then the underlying",
"the estimator is trained on the initial set of features and weights are",
"# doctest: +NORMALIZE_WHITESPACE array([ True, True, True, True, True, False, False, False, False,",
"'coef_'): coefs = estimator.coef_ elif hasattr(estimator, 'feature_importances_'): coefs = estimator.feature_importances_ else: raise RuntimeError('The",
"<NAME>., <NAME>., <NAME>., & <NAME>., \"Gene selection for cancer classification using support vector",
"coefficients of a linear model), the goal of forward feature selection (FFS) is",
"selection from: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_selection/rfe.py Given an external estimator that assigns weights to features (e.g.,",
"self.n_features_to_select is None: n_features_to_select = n_features // 2 else: n_features_to_select = self.n_features_to_select if",
"iteration # because 'estimator' must use features # that have not been eliminated",
"input samples. y : array of shape [n_samples] The target values. \"\"\" return",
"True, True, False, False, False, False, False], dtype=bool) >>> selector.ranking_ array([1, 1, 1,",
"= np.zeros(n_features, dtype=np.int) ranking_[0] = 1 if step_score: self.scores_ = [] # Elimination",
"> 0: print(\"Fitting estimator with %d features.\" % np.sum(support_)) estimator.fit(X[:, features], y) #",
"or \"feature_importances_\" ' 'attributes') # Get ranks if coefs.ndim > 1: ranks =",
"Selection import warnings import numpy as np from sklearn.utils import check_X_y, safe_sqr from",
"them. Then, features whose absolute weights are the smallest are pruned from the",
"6, 4, 3, 2, 5]) References ---------- .. [1] <NAME>., <NAME>., <NAME>., &",
"have not been eliminated yet if step_score: self.scores_.append(step_score(estimator, features)) support_[features[ranks][:threshold]] = True ranking_[np.logical_not(support_)]",
"estimator. Parameters ---------- X : array of shape [n_samples, n_features] The input samples.",
"more in the :ref:`User Guide <rfe>`. Parameters ---------- estimator : object A supervised",
"n_features_to_select: # Remaining features features = np.arange(n_features)[support_] # Rank the remaining features estimator",
"This attribute is deprecated as of version 0.16 and will be removed in",
"previous selection iteration # because 'estimator' must use features # that have not",
"samples. y : array of shape [n_samples] The target values. \"\"\" return self.estimator_.score(self.transform(X),",
"the `svm` and `linear_model` modules. n_features_to_select : int or None (default=None) The number",
"is eventually reached. Read more in the :ref:`User Guide <rfe>`. Parameters ---------- estimator",
"def _get_support_mask(self): return self.support_ @if_delegate_has_method(delegate='estimator') def decision_function(self, X): return self.estimator_.decision_function(self.transform(X)) @if_delegate_has_method(delegate='estimator') def predict_proba(self,",
"---------- X : {array-like, sparse matrix}, shape = [n_samples, n_features] The training input",
"`svm` and `linear_model` modules. n_features_to_select : int or None (default=None) The number of",
"< self.step < 1.0: step = int(max(1, self.step * n_features)) else: step =",
"(FFS) is to select features by recursively considering larger and larger sets of",
"Friedman #1 dataset. >>> from sklearn.datasets import make_friedman1 >>> from sklearn.feature_selection import RFE",
"1 # Set final attributes features = np.arange(n_features)[support_] self.estimator_ = clone(self.estimator) if self.estimator_params:",
"References ---------- .. [1] <NAME>., <NAME>., <NAME>., & <NAME>., \"Gene selection for cancer",
"warnings import numpy as np from sklearn.utils import check_X_y, safe_sqr from sklearn.utils.metaestimators import",
"= clone(self.estimator) if self.estimator_params: estimator.set_params(**self.estimator_params) if self.verbose > 0: print(\"Fitting estimator with %d",
"ranks = np.argsort(safe_sqr(coefs).sum(axis=0))[::-1] else: ranks = np.argsort(safe_sqr(coefs))[::-1] # for sparse case ranks is",
"step score on the previous selection iteration # because 'estimator' must use features",
"left if step_score: self.scores_.append(step_score(self.estimator_, features)) self.n_features_ = support_.sum() self.support_ = support_ self.ranking_ =",
"features. First, the estimator is trained on the initial set of features and",
"Mach. Learn., 46(1-3), 389--422, 2002. \"\"\" def __init__(self, estimator, n_features_to_select=None, step=1, estimator_params=None, verbose=0):",
"'estimator' must use features # that have not been eliminated yet if step_score:",
"* n_features)) else: step = int(self.step) if step <= 0: raise ValueError(\"Step must",
"warnings.warn(\"The parameter 'estimator_params' is deprecated as \" \"of version 0.16 and will be",
"mask of selected features. ranking_ : array of shape [n_features] The feature ranking,",
"Generalized Linear Models from the `svm` and `linear_model` modules. n_features_to_select : int or",
"import MetaEstimatorMixin from sklearn.base import clone from sklearn.base import is_classifier from sklearn.cross_validation import",
"weights to features (e.g., the coefficients of a linear model), the goal of",
"is trained on the initial set of features and weights are assigned to",
"def predict(self, X): \"\"\"Reduce X to the selected features and then predict using",
"0.18. The \" \"parameter is no longer necessary because the value \" \"is",
"informative features in the Friedman #1 dataset. >>> from sklearn.datasets import make_friedman1 >>>",
"estimator initialisation or \" \"set_params method.\", DeprecationWarning) support_ = np.zeros(n_features, dtype=np.bool) support_[0] =",
"feature selection. Modification from backward feature selection from: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_selection/rfe.py Given an external estimator",
"features are selected. step : int or float, optional (default=1) If greater than",
"Read more in the :ref:`User Guide <rfe>`. Parameters ---------- estimator : object A",
"check_cv from sklearn.cross_validation import _safe_split, _score from sklearn.metrics.scorer import check_scoring from sklearn.feature_selection.base import",
"estimated best) features are assigned rank 1. estimator_ : object The external estimator",
"import check_X_y, safe_sqr from sklearn.utils.metaestimators import if_delegate_has_method from sklearn.base import BaseEstimator from sklearn.base",
"down) of features to remove at each iteration. estimator_params : dict Parameters for",
"self.step * n_features)) else: step = int(self.step) if step <= 0: raise ValueError(\"Step",
"[n_samples, n_features] The input samples. Returns ------- y : array of shape [n_samples]",
"import RFE >>> from sklearn.svm import SVR >>> X, y = make_friedman1(n_samples=50, n_features=10,",
"np from sklearn.utils import check_X_y, safe_sqr from sklearn.utils.metaestimators import if_delegate_has_method from sklearn.base import",
"recursively repeated on the pruned set until the desired number of features to",
"[n_features] The feature ranking, such that ``ranking_[i]`` corresponds to the ranking position of",
"self.n_features_ = support_.sum() self.support_ = support_ self.ranking_ = ranking_ return self @if_delegate_has_method(delegate='estimator') def",
"'attributes') # Get ranks if coefs.ndim > 1: ranks = np.argsort(safe_sqr(coefs).sum(axis=0))[::-1] else: ranks",
"value \" \"is set via the estimator initialisation or \" \"set_params method.\", DeprecationWarning)",
"(default=None) The number of features to select. If `None`, half of the features",
"dtype=np.int) ranking_[0] = 1 if step_score: self.scores_ = [] # Elimination while np.sum(support_)",
"SVR >>> X, y = make_friedman1(n_samples=50, n_features=10, random_state=0) >>> estimator = SVR(kernel=\"linear\") >>>",
"to features (e.g., the coefficients of a linear model), the goal of forward",
"estimator that assigns weights to features (e.g., the coefficients of a linear model),",
"X, y = make_friedman1(n_samples=50, n_features=10, random_state=0) >>> estimator = SVR(kernel=\"linear\") >>> selector =",
"features and then predict using the underlying estimator. Parameters ---------- X : array",
"step <= 0: raise ValueError(\"Step must be >0\") if self.estimator_params is not None:",
"on the pruned set until the desired number of features to select is",
"with a `fit` method that updates a `coef_` attribute that holds the fitted",
"ranking, such that ``ranking_[i]`` corresponds to the ranking position of the i-th feature.",
"return self.estimator_.predict(self.transform(X)) @if_delegate_has_method(delegate='estimator') def score(self, X, y): \"\"\"Reduce X to the selected features",
"ranking_[0] = 1 if step_score: self.scores_ = [] # Elimination while np.sum(support_) <",
"else: ranks = np.argsort(safe_sqr(coefs))[::-1] # for sparse case ranks is matrix ranks =",
"forward feature selection. Modification from backward feature selection from: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_selection/rfe.py Given an external",
"`None`, half of the features are selected. step : int or float, optional",
"absolute weights are the smallest are pruned from the current set features. That",
"in the Friedman #1 dataset. >>> from sklearn.datasets import make_friedman1 >>> from sklearn.feature_selection",
"at each iteration. If within (0.0, 1.0), then `step` corresponds to the percentage",
"for cancer classification using support vector machines\", Mach. Learn., 46(1-3), 389--422, 2002. \"\"\"",
"are assigned rank 1. estimator_ : object The external estimator fit on the",
"RFE(estimator, 5, step=1) >>> selector = selector.fit(X, y) >>> selector.support_ # doctest: +NORMALIZE_WHITESPACE",
"shape [n_samples, n_features] The input samples. y : array of shape [n_samples] The",
"n_features_to_select features left if step_score: self.scores_.append(step_score(self.estimator_, features)) self.n_features_ = support_.sum() self.support_ = support_",
"sklearn.utils.metaestimators import if_delegate_has_method from sklearn.base import BaseEstimator from sklearn.base import MetaEstimatorMixin from sklearn.base",
"If within (0.0, 1.0), then `step` corresponds to the percentage (rounded down) of",
"That procedure is recursively repeated on the pruned set until the desired number",
"that holds the fitted parameters. Important features must correspond to high absolute values",
"the external estimator. This attribute is deprecated as of version 0.16 and will",
"is to select features by recursively considering larger and larger sets of features.",
"external estimator. This attribute is deprecated as of version 0.16 and will be",
"n_features_ : int The number of selected features. support_ : array of shape",
"Examples -------- The following example shows how to retrieve the 5 right informative",
"[n_samples, n_features] The training input samples. y : array-like, shape = [n_samples] The",
"the score of the underlying estimator. Parameters ---------- X : array of shape",
"import check_scoring from sklearn.feature_selection.base import SelectorMixin class FFS(BaseEstimator, MetaEstimatorMixin, SelectorMixin): \"\"\"Feature ranking with",
"not None: warnings.warn(\"The parameter 'estimator_params' is deprecated as \" \"of version 0.16 and",
"\"\"\" return self._fit(X, y) def _fit(self, X, y, step_score=None): #X, y = check_X_y(X,",
"initialisation or set_params method instead. verbose : int, default=0 Controls verbosity of output.",
"The number of selected features. support_ : array of shape [n_features] The mask",
"check_X_y, safe_sqr from sklearn.utils.metaestimators import if_delegate_has_method from sklearn.base import BaseEstimator from sklearn.base import",
"be >0\") if self.estimator_params is not None: warnings.warn(\"The parameter 'estimator_params' is deprecated as",
"SelectorMixin class FFS(BaseEstimator, MetaEstimatorMixin, SelectorMixin): \"\"\"Feature ranking with forward feature selection. Modification from",
"the estimator initialisation or \" \"set_params method.\", DeprecationWarning) support_ = np.zeros(n_features, dtype=np.bool) support_[0]",
"because 'estimator' must use features # that have not been eliminated yet if",
"= RFE(estimator, 5, step=1) >>> selector = selector.fit(X, y) >>> selector.support_ # doctest:",
"when only n_features_to_select features left if step_score: self.scores_.append(step_score(self.estimator_, features)) self.n_features_ = support_.sum() self.support_",
"the remaining features estimator = clone(self.estimator) if self.estimator_params: estimator.set_params(**self.estimator_params) if self.verbose > 0:",
"The number of features to select. If `None`, half of the features are",
"1, 1, 1, 6, 4, 3, 2, 5]) References ---------- .. [1] <NAME>.,",
"`step` corresponds to the (integer) number of features to remove at each iteration.",
"= support_.sum() self.support_ = support_ self.ranking_ = ranking_ return self @if_delegate_has_method(delegate='estimator') def predict(self,",
"n_features_to_select : int or None (default=None) The number of features to select. If",
"``ranking_[i]`` corresponds to the ranking position of the i-th feature. Selected (i.e., estimated",
"#1 dataset. >>> from sklearn.datasets import make_friedman1 >>> from sklearn.feature_selection import RFE >>>",
"model and then the underlying estimator on the selected features. Parameters ---------- X",
"and `linear_model` modules. n_features_to_select : int or None (default=None) The number of features",
"array of shape [n_samples] The target values. \"\"\" return self.estimator_.score(self.transform(X), y) def _get_support_mask(self):",
"the RFE model and then the underlying estimator on the selected features. Parameters",
"the i-th feature. Selected (i.e., estimated best) features are assigned rank 1. estimator_",
"for the external estimator. This attribute is deprecated as of version 0.16 and",
"to the selected features and then predict using the underlying estimator. Parameters ----------",
"sklearn.utils import check_X_y, safe_sqr from sklearn.utils.metaestimators import if_delegate_has_method from sklearn.base import BaseEstimator from",
"selection iteration # because 'estimator' must use features # that have not been",
"MetaEstimatorMixin from sklearn.base import clone from sklearn.base import is_classifier from sklearn.cross_validation import _check_cv",
"import SelectorMixin class FFS(BaseEstimator, MetaEstimatorMixin, SelectorMixin): \"\"\"Feature ranking with forward feature selection. Modification",
">>> estimator = SVR(kernel=\"linear\") >>> selector = RFE(estimator, 5, step=1) >>> selector =",
"a linear model), the goal of forward feature selection (FFS) is to select",
"of selected features. ranking_ : array of shape [n_features] The feature ranking, such",
"False, False, False, False], dtype=bool) >>> selector.ranking_ array([1, 1, 1, 1, 1, 6,",
"assigns weights to features (e.g., the coefficients of a linear model), the goal",
"ranking_ : array of shape [n_features] The feature ranking, such that ``ranking_[i]`` corresponds",
"step_score: self.scores_ = [] # Elimination while np.sum(support_) < n_features_to_select: # Remaining features",
"underlying estimator on the selected features. Parameters ---------- X : {array-like, sparse matrix},",
"estimator.fit(X[:, features], y) # Get coefs if hasattr(estimator, 'coef_'): coefs = estimator.coef_ elif",
"X to the selected features and then predict using the underlying estimator. Parameters",
"corresponds to the ranking position of the i-th feature. Selected (i.e., estimated best)",
"repeated on the pruned set until the desired number of features to select",
"@if_delegate_has_method(delegate='estimator') def score(self, X, y): \"\"\"Reduce X to the selected features and then",
"n_features=10, random_state=0) >>> estimator = SVR(kernel=\"linear\") >>> selector = RFE(estimator, 5, step=1) >>>",
"n_features_to_select - np.sum(support_)) # Compute step score on the previous selection iteration #",
"predicted target values. \"\"\" return self.estimator_.predict(self.transform(X)) @if_delegate_has_method(delegate='estimator') def score(self, X, y): \"\"\"Reduce X",
"version 0.16 and will be removed in 0.18. Use estimator initialisation or set_params",
"from sklearn.feature_selection import RFE >>> from sklearn.svm import SVR >>> X, y =",
"longer necessary because the value \" \"is set via the estimator initialisation or",
"of shape [n_features] The mask of selected features. ranking_ : array of shape",
"the selected features and then predict using the underlying estimator. Parameters ---------- X",
"each iteration. estimator_params : dict Parameters for the external estimator. This attribute is",
"The mask of selected features. ranking_ : array of shape [n_features] The feature",
"import numpy as np from sklearn.utils import check_X_y, safe_sqr from sklearn.utils.metaestimators import if_delegate_has_method",
"from the current set features. That procedure is recursively repeated on the pruned",
"array of shape [n_features] The feature ranking, such that ``ranking_[i]`` corresponds to the",
"to high absolute values in the `coef_` array. For instance, this is the",
"features to remove at each iteration. If within (0.0, 1.0), then `step` corresponds",
"def _estimator_type(self): return self.estimator._estimator_type def fit(self, X, y): \"\"\"Fit the RFE model and",
"n_features_to_select=None, step=1, estimator_params=None, verbose=0): self.estimator = estimator self.n_features_to_select = n_features_to_select self.step = step",
"estimator.coef_ elif hasattr(estimator, 'feature_importances_'): coefs = estimator.feature_importances_ else: raise RuntimeError('The classifier does not",
"self @if_delegate_has_method(delegate='estimator') def predict(self, X): \"\"\"Reduce X to the selected features and then",
">>> from sklearn.svm import SVR >>> X, y = make_friedman1(n_samples=50, n_features=10, random_state=0) >>>",
"1, 1, 6, 4, 3, 2, 5]) References ---------- .. [1] <NAME>., <NAME>.,",
"y): \"\"\"Fit the RFE model and then the underlying estimator on the selected",
"will be removed in 0.18. Use estimator initialisation or set_params method instead. verbose",
"of output. Attributes ---------- n_features_ : int The number of selected features. support_",
": array-like, shape = [n_samples] The target values. \"\"\" return self._fit(X, y) def",
"RuntimeError('The classifier does not expose ' '\"coef_\" or \"feature_importances_\" ' 'attributes') # Get",
"number of features to select is eventually reached. Read more in the :ref:`User",
"# Remaining features features = np.arange(n_features)[support_] # Rank the remaining features estimator =",
"self.estimator_.predict(self.transform(X)) @if_delegate_has_method(delegate='estimator') def score(self, X, y): \"\"\"Reduce X to the selected features and",
"shows how to retrieve the 5 right informative features in the Friedman #1",
"updates a `coef_` attribute that holds the fitted parameters. Important features must correspond",
"not expose ' '\"coef_\" or \"feature_importances_\" ' 'attributes') # Get ranks if coefs.ndim",
"= support_ self.ranking_ = ranking_ return self @if_delegate_has_method(delegate='estimator') def predict(self, X): \"\"\"Reduce X",
"for sparse case ranks is matrix ranks = np.ravel(ranks) # Eliminate the worse",
"of forward feature selection (FFS) is to select features by recursively considering larger",
"eliminated yet if step_score: self.scores_.append(step_score(estimator, features)) support_[features[ranks][:threshold]] = True ranking_[np.logical_not(support_)] += 1 #",
"step_score: self.scores_.append(step_score(self.estimator_, features)) self.n_features_ = support_.sum() self.support_ = support_ self.ranking_ = ranking_ return",
"are the smallest are pruned from the current set features. That procedure is",
"SVR(kernel=\"linear\") >>> selector = RFE(estimator, 5, step=1) >>> selector = selector.fit(X, y) >>>",
"right informative features in the Friedman #1 dataset. >>> from sklearn.datasets import make_friedman1",
"// 2 else: n_features_to_select = self.n_features_to_select if 0.0 < self.step < 1.0: step",
"SelectorMixin): \"\"\"Feature ranking with forward feature selection. Modification from backward feature selection from:",
"of features to select. If `None`, half of the features are selected. step",
"n_features] The input samples. Returns ------- y : array of shape [n_samples] The",
"recursively considering larger and larger sets of features. First, the estimator is trained",
"_estimator_type(self): return self.estimator._estimator_type def fit(self, X, y): \"\"\"Fit the RFE model and then",
"numpy as np from sklearn.utils import check_X_y, safe_sqr from sklearn.utils.metaestimators import if_delegate_has_method from",
"features features = np.arange(n_features)[support_] # Rank the remaining features estimator = clone(self.estimator) if",
"learning estimator with a `fit` method that updates a `coef_` attribute that holds",
"dataset. >>> from sklearn.datasets import make_friedman1 >>> from sklearn.feature_selection import RFE >>> from",
"classification using support vector machines\", Mach. Learn., 46(1-3), 389--422, 2002. \"\"\" def __init__(self,",
"array([1, 1, 1, 1, 1, 6, 4, 3, 2, 5]) References ---------- ..",
"and will be removed in 0.18. Use estimator initialisation or set_params method instead.",
"\"csc\") # Initialization n_features = X.shape[1] if self.n_features_to_select is None: n_features_to_select = n_features",
"if hasattr(estimator, 'coef_'): coefs = estimator.coef_ elif hasattr(estimator, 'feature_importances_'): coefs = estimator.feature_importances_ else:",
"is recursively repeated on the pruned set until the desired number of features",
"\"parameter is no longer necessary because the value \" \"is set via the",
"then `step` corresponds to the percentage (rounded down) of features to remove at",
"features = np.arange(n_features)[support_] self.estimator_ = clone(self.estimator) if self.estimator_params: self.estimator_.set_params(**self.estimator_params) self.estimator_.fit(X[:, features], y) #",
"Parameters for the external estimator. This attribute is deprecated as of version 0.16",
"-------- The following example shows how to retrieve the 5 right informative features",
"features in the Friedman #1 dataset. >>> from sklearn.datasets import make_friedman1 >>> from",
"fit on the reduced dataset. Examples -------- The following example shows how to",
"y = check_X_y(X, y, \"csc\") # Initialization n_features = X.shape[1] if self.n_features_to_select is",
"estimator = SVR(kernel=\"linear\") >>> selector = RFE(estimator, 5, step=1) >>> selector = selector.fit(X,",
"self.support_ @if_delegate_has_method(delegate='estimator') def decision_function(self, X): return self.estimator_.decision_function(self.transform(X)) @if_delegate_has_method(delegate='estimator') def predict_proba(self, X): return self.estimator_.predict_proba(self.transform(X))",
"features must correspond to high absolute values in the `coef_` array. For instance,",
"is matrix ranks = np.ravel(ranks) # Eliminate the worse features threshold = min(step,",
"the coefficients of a linear model), the goal of forward feature selection (FFS)",
"attribute is deprecated as of version 0.16 and will be removed in 0.18.",
"return self @if_delegate_has_method(delegate='estimator') def predict(self, X): \"\"\"Reduce X to the selected features and",
"external estimator fit on the reduced dataset. Examples -------- The following example shows",
"= int(max(1, self.step * n_features)) else: step = int(self.step) if step <= 0:",
"select. If `None`, half of the features are selected. step : int or",
"Sequential Forward Selection import warnings import numpy as np from sklearn.utils import check_X_y,",
"estimator_ : object The external estimator fit on the reduced dataset. Examples --------",
"check_X_y(X, y, \"csc\") # Initialization n_features = X.shape[1] if self.n_features_to_select is None: n_features_to_select",
"linear model), the goal of forward feature selection (FFS) is to select features",
"\" \"is set via the estimator initialisation or \" \"set_params method.\", DeprecationWarning) support_",
"estimator = clone(self.estimator) if self.estimator_params: estimator.set_params(**self.estimator_params) if self.verbose > 0: print(\"Fitting estimator with",
"target values. \"\"\" return self._fit(X, y) def _fit(self, X, y, step_score=None): #X, y",
"selected. step : int or float, optional (default=1) If greater than or equal",
"sets of features. First, the estimator is trained on the initial set of",
"= n_features // 2 else: n_features_to_select = self.n_features_to_select if 0.0 < self.step <",
"\" \"set_params method.\", DeprecationWarning) support_ = np.zeros(n_features, dtype=np.bool) support_[0] = True ranking_ =",
"array. For instance, this is the case for most supervised learning algorithms such",
"from: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_selection/rfe.py Given an external estimator that assigns weights to features (e.g., the",
"True ranking_[np.logical_not(support_)] += 1 # Set final attributes features = np.arange(n_features)[support_] self.estimator_ =",
"[] # Elimination while np.sum(support_) < n_features_to_select: # Remaining features features = np.arange(n_features)[support_]",
"one of them. Then, features whose absolute weights are the smallest are pruned",
"389--422, 2002. \"\"\" def __init__(self, estimator, n_features_to_select=None, step=1, estimator_params=None, verbose=0): self.estimator = estimator",
"estimator self.n_features_to_select = n_features_to_select self.step = step self.estimator_params = estimator_params self.verbose = verbose",
"sklearn.svm import SVR >>> X, y = make_friedman1(n_samples=50, n_features=10, random_state=0) >>> estimator =",
"deprecated as \" \"of version 0.16 and will be removed in 0.18. The",
"yet if step_score: self.scores_.append(step_score(estimator, features)) support_[features[ranks][:threshold]] = True ranking_[np.logical_not(support_)] += 1 # Set",
"estimator_params : dict Parameters for the external estimator. This attribute is deprecated as",
"an external estimator that assigns weights to features (e.g., the coefficients of a",
"the ranking position of the i-th feature. Selected (i.e., estimated best) features are",
"Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples, n_features] The training",
"and larger sets of features. First, the estimator is trained on the initial",
"the fitted parameters. Important features must correspond to high absolute values in the",
"learning algorithms such as Support Vector Classifiers and Generalized Linear Models from the",
"parameter 'estimator_params' is deprecated as \" \"of version 0.16 and will be removed",
"features], y) # Compute step score when only n_features_to_select features left if step_score:",
"on the initial set of features and weights are assigned to each one",
"support_[features[ranks][:threshold]] = True ranking_[np.logical_not(support_)] += 1 # Set final attributes features = np.arange(n_features)[support_]",
"pruned set until the desired number of features to select is eventually reached.",
"import make_friedman1 >>> from sklearn.feature_selection import RFE >>> from sklearn.svm import SVR >>>",
"support_ self.ranking_ = ranking_ return self @if_delegate_has_method(delegate='estimator') def predict(self, X): \"\"\"Reduce X to",
"classifier does not expose ' '\"coef_\" or \"feature_importances_\" ' 'attributes') # Get ranks",
"1, 6, 4, 3, 2, 5]) References ---------- .. [1] <NAME>., <NAME>., <NAME>.,",
"class FFS(BaseEstimator, MetaEstimatorMixin, SelectorMixin): \"\"\"Feature ranking with forward feature selection. Modification from backward",
"select is eventually reached. Read more in the :ref:`User Guide <rfe>`. Parameters ----------",
"fitted parameters. Important features must correspond to high absolute values in the `coef_`",
"the (integer) number of features to remove at each iteration. If within (0.0,",
"sklearn.datasets import make_friedman1 >>> from sklearn.feature_selection import RFE >>> from sklearn.svm import SVR",
"optional (default=1) If greater than or equal to 1, then `step` corresponds to",
"machines\", Mach. Learn., 46(1-3), 389--422, 2002. \"\"\" def __init__(self, estimator, n_features_to_select=None, step=1, estimator_params=None,",
"step : int or float, optional (default=1) If greater than or equal to",
"int(self.step) if step <= 0: raise ValueError(\"Step must be >0\") if self.estimator_params is",
"Get ranks if coefs.ndim > 1: ranks = np.argsort(safe_sqr(coefs).sum(axis=0))[::-1] else: ranks = np.argsort(safe_sqr(coefs))[::-1]",
"1.0), then `step` corresponds to the percentage (rounded down) of features to remove",
"raise ValueError(\"Step must be >0\") if self.estimator_params is not None: warnings.warn(\"The parameter 'estimator_params'",
"remaining features estimator = clone(self.estimator) if self.estimator_params: estimator.set_params(**self.estimator_params) if self.verbose > 0: print(\"Fitting",
"> 1: ranks = np.argsort(safe_sqr(coefs).sum(axis=0))[::-1] else: ranks = np.argsort(safe_sqr(coefs))[::-1] # for sparse case",
"feature ranking, such that ``ranking_[i]`` corresponds to the ranking position of the i-th",
"The input samples. Returns ------- y : array of shape [n_samples] The predicted",
"def score(self, X, y): \"\"\"Reduce X to the selected features and then return",
"to 1, then `step` corresponds to the (integer) number of features to remove",
"vector machines\", Mach. Learn., 46(1-3), 389--422, 2002. \"\"\" def __init__(self, estimator, n_features_to_select=None, step=1,",
"= [n_samples] The target values. \"\"\" return self._fit(X, y) def _fit(self, X, y,",
"is no longer necessary because the value \" \"is set via the estimator",
"corresponds to the (integer) number of features to remove at each iteration. If",
"False, False, False, False, False], dtype=bool) >>> selector.ranking_ array([1, 1, 1, 1, 1,",
"larger and larger sets of features. First, the estimator is trained on the",
"best) features are assigned rank 1. estimator_ : object The external estimator fit",
"as np from sklearn.utils import check_X_y, safe_sqr from sklearn.utils.metaestimators import if_delegate_has_method from sklearn.base",
"clone from sklearn.base import is_classifier from sklearn.cross_validation import _check_cv as check_cv from sklearn.cross_validation",
"features. That procedure is recursively repeated on the pruned set until the desired",
"no longer necessary because the value \" \"is set via the estimator initialisation",
"using the underlying estimator. Parameters ---------- X : array of shape [n_samples, n_features]",
"sparse case ranks is matrix ranks = np.ravel(ranks) # Eliminate the worse features",
"trained on the initial set of features and weights are assigned to each",
"is deprecated as of version 0.16 and will be removed in 0.18. Use",
"in 0.18. The \" \"parameter is no longer necessary because the value \"",
"instance, this is the case for most supervised learning algorithms such as Support",
"sklearn.base import MetaEstimatorMixin from sklearn.base import clone from sklearn.base import is_classifier from sklearn.cross_validation",
"if coefs.ndim > 1: ranks = np.argsort(safe_sqr(coefs).sum(axis=0))[::-1] else: ranks = np.argsort(safe_sqr(coefs))[::-1] # for",
"verbosity of output. Attributes ---------- n_features_ : int The number of selected features.",
"y) def _fit(self, X, y, step_score=None): #X, y = check_X_y(X, y, \"csc\") #",
"ValueError(\"Step must be >0\") if self.estimator_params is not None: warnings.warn(\"The parameter 'estimator_params' is",
"if step_score: self.scores_ = [] # Elimination while np.sum(support_) < n_features_to_select: # Remaining",
"estimator with %d features.\" % np.sum(support_)) estimator.fit(X[:, features], y) # Get coefs if",
"---------- X : array of shape [n_samples, n_features] The input samples. Returns -------",
"4, 3, 2, 5]) References ---------- .. [1] <NAME>., <NAME>., <NAME>., & <NAME>.,",
"- np.sum(support_)) # Compute step score on the previous selection iteration # because",
"\"is set via the estimator initialisation or \" \"set_params method.\", DeprecationWarning) support_ =",
"selection. Modification from backward feature selection from: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_selection/rfe.py Given an external estimator that",
"of features to select is eventually reached. Read more in the :ref:`User Guide",
"DeprecationWarning) support_ = np.zeros(n_features, dtype=np.bool) support_[0] = True ranking_ = np.zeros(n_features, dtype=np.int) ranking_[0]",
"ranks is matrix ranks = np.ravel(ranks) # Eliminate the worse features threshold =",
"sklearn.feature_selection.base import SelectorMixin class FFS(BaseEstimator, MetaEstimatorMixin, SelectorMixin): \"\"\"Feature ranking with forward feature selection.",
"to each one of them. Then, features whose absolute weights are the smallest",
"then `step` corresponds to the (integer) number of features to remove at each",
"input samples. y : array-like, shape = [n_samples] The target values. \"\"\" return",
"self.n_features_to_select if 0.0 < self.step < 1.0: step = int(max(1, self.step * n_features))",
"must correspond to high absolute values in the `coef_` array. For instance, this",
"= min(step, n_features_to_select - np.sum(support_)) # Compute step score on the previous selection",
"[n_features] The mask of selected features. ranking_ : array of shape [n_features] The",
"np.ravel(ranks) # Eliminate the worse features threshold = min(step, n_features_to_select - np.sum(support_)) #",
"smallest are pruned from the current set features. That procedure is recursively repeated",
"Selected (i.e., estimated best) features are assigned rank 1. estimator_ : object The",
"features are assigned rank 1. estimator_ : object The external estimator fit on",
"46(1-3), 389--422, 2002. \"\"\" def __init__(self, estimator, n_features_to_select=None, step=1, estimator_params=None, verbose=0): self.estimator =",
"estimator.set_params(**self.estimator_params) if self.verbose > 0: print(\"Fitting estimator with %d features.\" % np.sum(support_)) estimator.fit(X[:,",
"else: step = int(self.step) if step <= 0: raise ValueError(\"Step must be >0\")",
"this is the case for most supervised learning algorithms such as Support Vector",
"coefs.ndim > 1: ranks = np.argsort(safe_sqr(coefs).sum(axis=0))[::-1] else: ranks = np.argsort(safe_sqr(coefs))[::-1] # for sparse",
"from sklearn.utils import check_X_y, safe_sqr from sklearn.utils.metaestimators import if_delegate_has_method from sklearn.base import BaseEstimator",
"selected features. ranking_ : array of shape [n_features] The feature ranking, such that",
"_safe_split, _score from sklearn.metrics.scorer import check_scoring from sklearn.feature_selection.base import SelectorMixin class FFS(BaseEstimator, MetaEstimatorMixin,",
"deprecated as of version 0.16 and will be removed in 0.18. Use estimator",
"The \" \"parameter is no longer necessary because the value \" \"is set",
"then predict using the underlying estimator. Parameters ---------- X : array of shape",
"of shape [n_samples] The predicted target values. \"\"\" return self.estimator_.predict(self.transform(X)) @if_delegate_has_method(delegate='estimator') def score(self,",
"a `coef_` attribute that holds the fitted parameters. Important features must correspond to",
"# for sparse case ranks is matrix ranks = np.ravel(ranks) # Eliminate the",
"features.\" % np.sum(support_)) estimator.fit(X[:, features], y) # Get coefs if hasattr(estimator, 'coef_'): coefs",
"such as Support Vector Classifiers and Generalized Linear Models from the `svm` and",
"following example shows how to retrieve the 5 right informative features in the",
"The feature ranking, such that ``ranking_[i]`` corresponds to the ranking position of the",
"selector.fit(X, y) >>> selector.support_ # doctest: +NORMALIZE_WHITESPACE array([ True, True, True, True, True,",
"print(\"Fitting estimator with %d features.\" % np.sum(support_)) estimator.fit(X[:, features], y) # Get coefs",
"is None: n_features_to_select = n_features // 2 else: n_features_to_select = self.n_features_to_select if 0.0",
"\"\"\"Reduce X to the selected features and then return the score of the",
"array of shape [n_samples, n_features] The input samples. Returns ------- y : array",
": dict Parameters for the external estimator. This attribute is deprecated as of",
"float, optional (default=1) If greater than or equal to 1, then `step` corresponds",
"feature selection from: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_selection/rfe.py Given an external estimator that assigns weights to features",
"RFE >>> from sklearn.svm import SVR >>> X, y = make_friedman1(n_samples=50, n_features=10, random_state=0)",
"0.18. Use estimator initialisation or set_params method instead. verbose : int, default=0 Controls",
"or \" \"set_params method.\", DeprecationWarning) support_ = np.zeros(n_features, dtype=np.bool) support_[0] = True ranking_",
"attribute that holds the fitted parameters. Important features must correspond to high absolute",
"y) # Compute step score when only n_features_to_select features left if step_score: self.scores_.append(step_score(self.estimator_,",
"= selector.fit(X, y) >>> selector.support_ # doctest: +NORMALIZE_WHITESPACE array([ True, True, True, True,",
"if 0.0 < self.step < 1.0: step = int(max(1, self.step * n_features)) else:",
"coefs = estimator.coef_ elif hasattr(estimator, 'feature_importances_'): coefs = estimator.feature_importances_ else: raise RuntimeError('The classifier",
"False, False, False], dtype=bool) >>> selector.ranking_ array([1, 1, 1, 1, 1, 6, 4,",
"because the value \" \"is set via the estimator initialisation or \" \"set_params",
"_check_cv as check_cv from sklearn.cross_validation import _safe_split, _score from sklearn.metrics.scorer import check_scoring from",
"and then predict using the underlying estimator. Parameters ---------- X : array of",
"Controls verbosity of output. Attributes ---------- n_features_ : int The number of selected",
"verbose : int, default=0 Controls verbosity of output. Attributes ---------- n_features_ : int",
"dtype=bool) >>> selector.ranking_ array([1, 1, 1, 1, 1, 6, 4, 3, 2, 5])",
"values. \"\"\" return self.estimator_.score(self.transform(X), y) def _get_support_mask(self): return self.support_ @if_delegate_has_method(delegate='estimator') def decision_function(self, X):",
"current set features. That procedure is recursively repeated on the pruned set until",
"to select. If `None`, half of the features are selected. step : int",
"of shape [n_samples, n_features] The input samples. y : array of shape [n_samples]",
"---------- X : array of shape [n_samples, n_features] The input samples. y :",
"step score when only n_features_to_select features left if step_score: self.scores_.append(step_score(self.estimator_, features)) self.n_features_ =",
"estimator fit on the reduced dataset. Examples -------- The following example shows how",
"are selected. step : int or float, optional (default=1) If greater than or",
"y : array of shape [n_samples] The target values. \"\"\" return self.estimator_.score(self.transform(X), y)",
"sklearn.cross_validation import _check_cv as check_cv from sklearn.cross_validation import _safe_split, _score from sklearn.metrics.scorer import",
"selected features and then return the score of the underlying estimator. Parameters ----------",
"step=1) >>> selector = selector.fit(X, y) >>> selector.support_ # doctest: +NORMALIZE_WHITESPACE array([ True,",
"from sklearn.base import BaseEstimator from sklearn.base import MetaEstimatorMixin from sklearn.base import clone from",
"from sklearn.cross_validation import _safe_split, _score from sklearn.metrics.scorer import check_scoring from sklearn.feature_selection.base import SelectorMixin",
"features threshold = min(step, n_features_to_select - np.sum(support_)) # Compute step score on the",
": array of shape [n_features] The mask of selected features. ranking_ : array",
">>> selector.ranking_ array([1, 1, 1, 1, 1, 6, 4, 3, 2, 5]) References",
"return the score of the underlying estimator. Parameters ---------- X : array of",
"# Initialization n_features = X.shape[1] if self.n_features_to_select is None: n_features_to_select = n_features //",
"step self.estimator_params = estimator_params self.verbose = verbose @property def _estimator_type(self): return self.estimator._estimator_type def",
"as check_cv from sklearn.cross_validation import _safe_split, _score from sklearn.metrics.scorer import check_scoring from sklearn.feature_selection.base",
"True, True, True, True, True, False, False, False, False, False], dtype=bool) >>> selector.ranking_",
"FFS(BaseEstimator, MetaEstimatorMixin, SelectorMixin): \"\"\"Feature ranking with forward feature selection. Modification from backward feature",
"\"\"\"Fit the RFE model and then the underlying estimator on the selected features.",
"import SVR >>> X, y = make_friedman1(n_samples=50, n_features=10, random_state=0) >>> estimator = SVR(kernel=\"linear\")",
"n_features_to_select = n_features // 2 else: n_features_to_select = self.n_features_to_select if 0.0 < self.step",
"features and weights are assigned to each one of them. Then, features whose",
"estimator. This attribute is deprecated as of version 0.16 and will be removed",
"`coef_` array. For instance, this is the case for most supervised learning algorithms",
"that assigns weights to features (e.g., the coefficients of a linear model), the",
"2002. \"\"\" def __init__(self, estimator, n_features_to_select=None, step=1, estimator_params=None, verbose=0): self.estimator = estimator self.n_features_to_select",
"def __init__(self, estimator, n_features_to_select=None, step=1, estimator_params=None, verbose=0): self.estimator = estimator self.n_features_to_select = n_features_to_select",
"self.verbose = verbose @property def _estimator_type(self): return self.estimator._estimator_type def fit(self, X, y): \"\"\"Fit",
"The target values. \"\"\" return self._fit(X, y) def _fit(self, X, y, step_score=None): #X,",
"= estimator.coef_ elif hasattr(estimator, 'feature_importances_'): coefs = estimator.feature_importances_ else: raise RuntimeError('The classifier does",
"\"set_params method.\", DeprecationWarning) support_ = np.zeros(n_features, dtype=np.bool) support_[0] = True ranking_ = np.zeros(n_features,",
"score on the previous selection iteration # because 'estimator' must use features #",
"Set final attributes features = np.arange(n_features)[support_] self.estimator_ = clone(self.estimator) if self.estimator_params: self.estimator_.set_params(**self.estimator_params) self.estimator_.fit(X[:,",
"if step_score: self.scores_.append(step_score(estimator, features)) support_[features[ranks][:threshold]] = True ranking_[np.logical_not(support_)] += 1 # Set final",
"supervised learning estimator with a `fit` method that updates a `coef_` attribute that",
"(i.e., estimated best) features are assigned rank 1. estimator_ : object The external",
"features by recursively considering larger and larger sets of features. First, the estimator",
"Important features must correspond to high absolute values in the `coef_` array. For",
"the selected features. Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples,",
"select features by recursively considering larger and larger sets of features. First, the",
"initialisation or \" \"set_params method.\", DeprecationWarning) support_ = np.zeros(n_features, dtype=np.bool) support_[0] = True",
"\"\"\"Reduce X to the selected features and then predict using the underlying estimator.",
"https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_selection/rfe.py Given an external estimator that assigns weights to features (e.g., the coefficients",
"For instance, this is the case for most supervised learning algorithms such as",
"= np.argsort(safe_sqr(coefs))[::-1] # for sparse case ranks is matrix ranks = np.ravel(ranks) #",
"the underlying estimator. Parameters ---------- X : array of shape [n_samples, n_features] The",
"1: ranks = np.argsort(safe_sqr(coefs).sum(axis=0))[::-1] else: ranks = np.argsort(safe_sqr(coefs))[::-1] # for sparse case ranks",
"the Friedman #1 dataset. >>> from sklearn.datasets import make_friedman1 >>> from sklearn.feature_selection import",
"make_friedman1(n_samples=50, n_features=10, random_state=0) >>> estimator = SVR(kernel=\"linear\") >>> selector = RFE(estimator, 5, step=1)",
"coefs if hasattr(estimator, 'coef_'): coefs = estimator.coef_ elif hasattr(estimator, 'feature_importances_'): coefs = estimator.feature_importances_",
"retrieve the 5 right informative features in the Friedman #1 dataset. >>> from",
"\" \"of version 0.16 and will be removed in 0.18. The \" \"parameter",
"and Generalized Linear Models from the `svm` and `linear_model` modules. n_features_to_select : int",
">>> selector = selector.fit(X, y) >>> selector.support_ # doctest: +NORMALIZE_WHITESPACE array([ True, True,",
": int or None (default=None) The number of features to select. If `None`,",
"raise RuntimeError('The classifier does not expose ' '\"coef_\" or \"feature_importances_\" ' 'attributes') #",
"features. support_ : array of shape [n_features] The mask of selected features. ranking_",
"Guide <rfe>`. Parameters ---------- estimator : object A supervised learning estimator with a",
"2, 5]) References ---------- .. [1] <NAME>., <NAME>., <NAME>., & <NAME>., \"Gene selection",
"random_state=0) >>> estimator = SVR(kernel=\"linear\") >>> selector = RFE(estimator, 5, step=1) >>> selector",
"False], dtype=bool) >>> selector.ranking_ array([1, 1, 1, 1, 1, 6, 4, 3, 2,",
"self.estimator_params: estimator.set_params(**self.estimator_params) if self.verbose > 0: print(\"Fitting estimator with %d features.\" % np.sum(support_))",
"make_friedman1 >>> from sklearn.feature_selection import RFE >>> from sklearn.svm import SVR >>> X,",
"'estimator_params' is deprecated as \" \"of version 0.16 and will be removed in",
"# Sequential Forward Selection import warnings import numpy as np from sklearn.utils import",
"sklearn.base import clone from sklearn.base import is_classifier from sklearn.cross_validation import _check_cv as check_cv",
"features (e.g., the coefficients of a linear model), the goal of forward feature",
"method that updates a `coef_` attribute that holds the fitted parameters. Important features",
"= step self.estimator_params = estimator_params self.verbose = verbose @property def _estimator_type(self): return self.estimator._estimator_type",
"array of shape [n_samples] The predicted target values. \"\"\" return self.estimator_.predict(self.transform(X)) @if_delegate_has_method(delegate='estimator') def",
"2 else: n_features_to_select = self.n_features_to_select if 0.0 < self.step < 1.0: step =",
"else: n_features_to_select = self.n_features_to_select if 0.0 < self.step < 1.0: step = int(max(1,",
"of shape [n_samples, n_features] The input samples. Returns ------- y : array of",
"object A supervised learning estimator with a `fit` method that updates a `coef_`",
"position of the i-th feature. Selected (i.e., estimated best) features are assigned rank",
"via the estimator initialisation or \" \"set_params method.\", DeprecationWarning) support_ = np.zeros(n_features, dtype=np.bool)",
"step = int(self.step) if step <= 0: raise ValueError(\"Step must be >0\") if",
"self.estimator_params is not None: warnings.warn(\"The parameter 'estimator_params' is deprecated as \" \"of version",
"sklearn.feature_selection import RFE >>> from sklearn.svm import SVR >>> X, y = make_friedman1(n_samples=50,",
"\"of version 0.16 and will be removed in 0.18. The \" \"parameter is",
"Vector Classifiers and Generalized Linear Models from the `svm` and `linear_model` modules. n_features_to_select",
"= np.argsort(safe_sqr(coefs).sum(axis=0))[::-1] else: ranks = np.argsort(safe_sqr(coefs))[::-1] # for sparse case ranks is matrix",
"0: print(\"Fitting estimator with %d features.\" % np.sum(support_)) estimator.fit(X[:, features], y) # Get",
"of features to remove at each iteration. estimator_params : dict Parameters for the",
"initial set of features and weights are assigned to each one of them.",
"on the reduced dataset. Examples -------- The following example shows how to retrieve",
"0.0 < self.step < 1.0: step = int(max(1, self.step * n_features)) else: step",
"only n_features_to_select features left if step_score: self.scores_.append(step_score(self.estimator_, features)) self.n_features_ = support_.sum() self.support_ =",
"goal of forward feature selection (FFS) is to select features by recursively considering",
"step_score: self.scores_.append(step_score(estimator, features)) support_[features[ranks][:threshold]] = True ranking_[np.logical_not(support_)] += 1 # Set final attributes",
"self.estimator = estimator self.n_features_to_select = n_features_to_select self.step = step self.estimator_params = estimator_params self.verbose",
"features to select is eventually reached. Read more in the :ref:`User Guide <rfe>`.",
"Compute step score on the previous selection iteration # because 'estimator' must use",
"return self.estimator_.decision_function(self.transform(X)) @if_delegate_has_method(delegate='estimator') def predict_proba(self, X): return self.estimator_.predict_proba(self.transform(X)) @if_delegate_has_method(delegate='estimator') def predict_log_proba(self, X): return",
"clone(self.estimator) if self.estimator_params: self.estimator_.set_params(**self.estimator_params) self.estimator_.fit(X[:, features], y) # Compute step score when only",
"must be >0\") if self.estimator_params is not None: warnings.warn(\"The parameter 'estimator_params' is deprecated",
"selector = selector.fit(X, y) >>> selector.support_ # doctest: +NORMALIZE_WHITESPACE array([ True, True, True,",
"X): \"\"\"Reduce X to the selected features and then predict using the underlying",
"of them. Then, features whose absolute weights are the smallest are pruned from",
"= verbose @property def _estimator_type(self): return self.estimator._estimator_type def fit(self, X, y): \"\"\"Fit the",
"samples. Returns ------- y : array of shape [n_samples] The predicted target values.",
"& <NAME>., \"Gene selection for cancer classification using support vector machines\", Mach. Learn.,",
"elif hasattr(estimator, 'feature_importances_'): coefs = estimator.feature_importances_ else: raise RuntimeError('The classifier does not expose",
"features. Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples, n_features] The",
"X.shape[1] if self.n_features_to_select is None: n_features_to_select = n_features // 2 else: n_features_to_select =",
"n_features_to_select = self.n_features_to_select if 0.0 < self.step < 1.0: step = int(max(1, self.step",
"# Get coefs if hasattr(estimator, 'coef_'): coefs = estimator.coef_ elif hasattr(estimator, 'feature_importances_'): coefs",
"else: raise RuntimeError('The classifier does not expose ' '\"coef_\" or \"feature_importances_\" ' 'attributes')",
"features. ranking_ : array of shape [n_features] The feature ranking, such that ``ranking_[i]``",
"= np.ravel(ranks) # Eliminate the worse features threshold = min(step, n_features_to_select - np.sum(support_))",
"= make_friedman1(n_samples=50, n_features=10, random_state=0) >>> estimator = SVR(kernel=\"linear\") >>> selector = RFE(estimator, 5,",
"X): return self.estimator_.decision_function(self.transform(X)) @if_delegate_has_method(delegate='estimator') def predict_proba(self, X): return self.estimator_.predict_proba(self.transform(X)) @if_delegate_has_method(delegate='estimator') def predict_log_proba(self, X):",
"from sklearn.cross_validation import _check_cv as check_cv from sklearn.cross_validation import _safe_split, _score from sklearn.metrics.scorer",
"on the previous selection iteration # because 'estimator' must use features # that",
": int or float, optional (default=1) If greater than or equal to 1,",
"selected features and then predict using the underlying estimator. Parameters ---------- X :",
"removed in 0.18. Use estimator initialisation or set_params method instead. verbose : int,",
"int, default=0 Controls verbosity of output. Attributes ---------- n_features_ : int The number",
"if_delegate_has_method from sklearn.base import BaseEstimator from sklearn.base import MetaEstimatorMixin from sklearn.base import clone",
"estimator_params self.verbose = verbose @property def _estimator_type(self): return self.estimator._estimator_type def fit(self, X, y):",
"check_scoring from sklearn.feature_selection.base import SelectorMixin class FFS(BaseEstimator, MetaEstimatorMixin, SelectorMixin): \"\"\"Feature ranking with forward",
"the percentage (rounded down) of features to remove at each iteration. estimator_params :",
"features whose absolute weights are the smallest are pruned from the current set",
"from sklearn.base import MetaEstimatorMixin from sklearn.base import clone from sklearn.base import is_classifier from",
"np.sum(support_)) estimator.fit(X[:, features], y) # Get coefs if hasattr(estimator, 'coef_'): coefs = estimator.coef_",
"values. \"\"\" return self.estimator_.predict(self.transform(X)) @if_delegate_has_method(delegate='estimator') def score(self, X, y): \"\"\"Reduce X to the",
"shape = [n_samples] The target values. \"\"\" return self._fit(X, y) def _fit(self, X,",
"number of features to remove at each iteration. If within (0.0, 1.0), then",
"until the desired number of features to select is eventually reached. Read more",
"of shape [n_features] The feature ranking, such that ``ranking_[i]`` corresponds to the ranking",
"removed in 0.18. The \" \"parameter is no longer necessary because the value",
"Get coefs if hasattr(estimator, 'coef_'): coefs = estimator.coef_ elif hasattr(estimator, 'feature_importances_'): coefs =",
"matrix}, shape = [n_samples, n_features] The training input samples. y : array-like, shape",
"Modification from backward feature selection from: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_selection/rfe.py Given an external estimator that assigns",
"from sklearn.metrics.scorer import check_scoring from sklearn.feature_selection.base import SelectorMixin class FFS(BaseEstimator, MetaEstimatorMixin, SelectorMixin): \"\"\"Feature",
"case ranks is matrix ranks = np.ravel(ranks) # Eliminate the worse features threshold",
"half of the features are selected. step : int or float, optional (default=1)",
"= np.arange(n_features)[support_] # Rank the remaining features estimator = clone(self.estimator) if self.estimator_params: estimator.set_params(**self.estimator_params)",
"`linear_model` modules. n_features_to_select : int or None (default=None) The number of features to",
"estimator : object A supervised learning estimator with a `fit` method that updates",
"+= 1 # Set final attributes features = np.arange(n_features)[support_] self.estimator_ = clone(self.estimator) if",
"features)) self.n_features_ = support_.sum() self.support_ = support_ self.ranking_ = ranking_ return self @if_delegate_has_method(delegate='estimator')",
"ranking position of the i-th feature. Selected (i.e., estimated best) features are assigned",
">>> X, y = make_friedman1(n_samples=50, n_features=10, random_state=0) >>> estimator = SVR(kernel=\"linear\") >>> selector",
">>> from sklearn.datasets import make_friedman1 >>> from sklearn.feature_selection import RFE >>> from sklearn.svm",
"n_features] The training input samples. y : array-like, shape = [n_samples] The target",
"@if_delegate_has_method(delegate='estimator') def decision_function(self, X): return self.estimator_.decision_function(self.transform(X)) @if_delegate_has_method(delegate='estimator') def predict_proba(self, X): return self.estimator_.predict_proba(self.transform(X)) @if_delegate_has_method(delegate='estimator')",
"assigned to each one of them. Then, features whose absolute weights are the",
"use features # that have not been eliminated yet if step_score: self.scores_.append(step_score(estimator, features))",
"estimator with a `fit` method that updates a `coef_` attribute that holds the",
"self.estimator_ = clone(self.estimator) if self.estimator_params: self.estimator_.set_params(**self.estimator_params) self.estimator_.fit(X[:, features], y) # Compute step score",
"model), the goal of forward feature selection (FFS) is to select features by",
"1 if step_score: self.scores_ = [] # Elimination while np.sum(support_) < n_features_to_select: #",
"worse features threshold = min(step, n_features_to_select - np.sum(support_)) # Compute step score on",
"return self.estimator_.score(self.transform(X), y) def _get_support_mask(self): return self.support_ @if_delegate_has_method(delegate='estimator') def decision_function(self, X): return self.estimator_.decision_function(self.transform(X))",
"ranks = np.argsort(safe_sqr(coefs))[::-1] # for sparse case ranks is matrix ranks = np.ravel(ranks)",
"def decision_function(self, X): return self.estimator_.decision_function(self.transform(X)) @if_delegate_has_method(delegate='estimator') def predict_proba(self, X): return self.estimator_.predict_proba(self.transform(X)) @if_delegate_has_method(delegate='estimator') def",
"Support Vector Classifiers and Generalized Linear Models from the `svm` and `linear_model` modules.",
"array of shape [n_samples, n_features] The input samples. y : array of shape",
"target values. \"\"\" return self.estimator_.score(self.transform(X), y) def _get_support_mask(self): return self.support_ @if_delegate_has_method(delegate='estimator') def decision_function(self,",
"of features and weights are assigned to each one of them. Then, features",
"A supervised learning estimator with a `fit` method that updates a `coef_` attribute",
"self._fit(X, y) def _fit(self, X, y, step_score=None): #X, y = check_X_y(X, y, \"csc\")",
"(rounded down) of features to remove at each iteration. estimator_params : dict Parameters",
"None: n_features_to_select = n_features // 2 else: n_features_to_select = self.n_features_to_select if 0.0 <",
"Forward Selection import warnings import numpy as np from sklearn.utils import check_X_y, safe_sqr",
"if step <= 0: raise ValueError(\"Step must be >0\") if self.estimator_params is not",
"X, y): \"\"\"Fit the RFE model and then the underlying estimator on the",
"ranks if coefs.ndim > 1: ranks = np.argsort(safe_sqr(coefs).sum(axis=0))[::-1] else: ranks = np.argsort(safe_sqr(coefs))[::-1] #",
"verbose @property def _estimator_type(self): return self.estimator._estimator_type def fit(self, X, y): \"\"\"Fit the RFE",
"%d features.\" % np.sum(support_)) estimator.fit(X[:, features], y) # Get coefs if hasattr(estimator, 'coef_'):",
"if self.n_features_to_select is None: n_features_to_select = n_features // 2 else: n_features_to_select = self.n_features_to_select",
"support_ : array of shape [n_features] The mask of selected features. ranking_ :",
"cancer classification using support vector machines\", Mach. Learn., 46(1-3), 389--422, 2002. \"\"\" def",
"__init__(self, estimator, n_features_to_select=None, step=1, estimator_params=None, verbose=0): self.estimator = estimator self.n_features_to_select = n_features_to_select self.step",
"than or equal to 1, then `step` corresponds to the (integer) number of",
"to the selected features and then return the score of the underlying estimator.",
"import is_classifier from sklearn.cross_validation import _check_cv as check_cv from sklearn.cross_validation import _safe_split, _score",
"import _check_cv as check_cv from sklearn.cross_validation import _safe_split, _score from sklearn.metrics.scorer import check_scoring",
"the underlying estimator on the selected features. Parameters ---------- X : {array-like, sparse",
"the worse features threshold = min(step, n_features_to_select - np.sum(support_)) # Compute step score",
"from sklearn.svm import SVR >>> X, y = make_friedman1(n_samples=50, n_features=10, random_state=0) >>> estimator",
"{array-like, sparse matrix}, shape = [n_samples, n_features] The training input samples. y :",
"X : array of shape [n_samples, n_features] The input samples. y : array",
"If `None`, half of the features are selected. step : int or float,",
"= np.zeros(n_features, dtype=np.bool) support_[0] = True ranking_ = np.zeros(n_features, dtype=np.int) ranking_[0] = 1",
"<= 0: raise ValueError(\"Step must be >0\") if self.estimator_params is not None: warnings.warn(\"The",
"self.support_ = support_ self.ranking_ = ranking_ return self @if_delegate_has_method(delegate='estimator') def predict(self, X): \"\"\"Reduce",
"selector = RFE(estimator, 5, step=1) >>> selector = selector.fit(X, y) >>> selector.support_ #",
"= estimator self.n_features_to_select = n_features_to_select self.step = step self.estimator_params = estimator_params self.verbose =",
"values. \"\"\" return self._fit(X, y) def _fit(self, X, y, step_score=None): #X, y =",
"each iteration. If within (0.0, 1.0), then `step` corresponds to the percentage (rounded",
"features to remove at each iteration. estimator_params : dict Parameters for the external",
"n_features // 2 else: n_features_to_select = self.n_features_to_select if 0.0 < self.step < 1.0:",
"threshold = min(step, n_features_to_select - np.sum(support_)) # Compute step score on the previous",
"if self.verbose > 0: print(\"Fitting estimator with %d features.\" % np.sum(support_)) estimator.fit(X[:, features],",
"supervised learning algorithms such as Support Vector Classifiers and Generalized Linear Models from",
"n_features] The input samples. y : array of shape [n_samples] The target values.",
"features to select. If `None`, half of the features are selected. step :",
"selected features. Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples, n_features]",
"1, 1, 1, 1, 6, 4, 3, 2, 5]) References ---------- .. [1]",
"necessary because the value \" \"is set via the estimator initialisation or \"",
"self.step < 1.0: step = int(max(1, self.step * n_features)) else: step = int(self.step)",
"---------- n_features_ : int The number of selected features. support_ : array of",
"Classifiers and Generalized Linear Models from the `svm` and `linear_model` modules. n_features_to_select :",
"True, True, True, False, False, False, False, False], dtype=bool) >>> selector.ranking_ array([1, 1,",
"to remove at each iteration. estimator_params : dict Parameters for the external estimator.",
"a `fit` method that updates a `coef_` attribute that holds the fitted parameters.",
"the reduced dataset. Examples -------- The following example shows how to retrieve the",
"score when only n_features_to_select features left if step_score: self.scores_.append(step_score(self.estimator_, features)) self.n_features_ = support_.sum()",
"estimator, n_features_to_select=None, step=1, estimator_params=None, verbose=0): self.estimator = estimator self.n_features_to_select = n_features_to_select self.step =",
"np.zeros(n_features, dtype=np.int) ranking_[0] = 1 if step_score: self.scores_ = [] # Elimination while",
"\"\"\" return self.estimator_.predict(self.transform(X)) @if_delegate_has_method(delegate='estimator') def score(self, X, y): \"\"\"Reduce X to the selected",
"features # that have not been eliminated yet if step_score: self.scores_.append(step_score(estimator, features)) support_[features[ranks][:threshold]]",
"0.16 and will be removed in 0.18. The \" \"parameter is no longer",
"------- y : array of shape [n_samples] The predicted target values. \"\"\" return",
"= n_features_to_select self.step = step self.estimator_params = estimator_params self.verbose = verbose @property def",
"< 1.0: step = int(max(1, self.step * n_features)) else: step = int(self.step) if",
"n_features = X.shape[1] if self.n_features_to_select is None: n_features_to_select = n_features // 2 else:",
"(integer) number of features to remove at each iteration. If within (0.0, 1.0),",
"= [n_samples, n_features] The training input samples. y : array-like, shape = [n_samples]",
"expose ' '\"coef_\" or \"feature_importances_\" ' 'attributes') # Get ranks if coefs.ndim >",
"dtype=np.bool) support_[0] = True ranking_ = np.zeros(n_features, dtype=np.int) ranking_[0] = 1 if step_score:",
"features], y) # Get coefs if hasattr(estimator, 'coef_'): coefs = estimator.coef_ elif hasattr(estimator,",
"with forward feature selection. Modification from backward feature selection from: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_selection/rfe.py Given an",
"estimator is trained on the initial set of features and weights are assigned",
"feature selection (FFS) is to select features by recursively considering larger and larger",
"the desired number of features to select is eventually reached. Read more in",
"score(self, X, y): \"\"\"Reduce X to the selected features and then return the",
"# Rank the remaining features estimator = clone(self.estimator) if self.estimator_params: estimator.set_params(**self.estimator_params) if self.verbose",
"example shows how to retrieve the 5 right informative features in the Friedman",
": array of shape [n_samples, n_features] The input samples. y : array of",
"support vector machines\", Mach. Learn., 46(1-3), 389--422, 2002. \"\"\" def __init__(self, estimator, n_features_to_select=None,",
"at each iteration. estimator_params : dict Parameters for the external estimator. This attribute",
"from sklearn.feature_selection.base import SelectorMixin class FFS(BaseEstimator, MetaEstimatorMixin, SelectorMixin): \"\"\"Feature ranking with forward feature",
"be removed in 0.18. Use estimator initialisation or set_params method instead. verbose :",
"number of features to select. If `None`, half of the features are selected.",
"array of shape [n_features] The mask of selected features. ranking_ : array of",
"y, step_score=None): #X, y = check_X_y(X, y, \"csc\") # Initialization n_features = X.shape[1]",
"(0.0, 1.0), then `step` corresponds to the percentage (rounded down) of features to",
"y) def _get_support_mask(self): return self.support_ @if_delegate_has_method(delegate='estimator') def decision_function(self, X): return self.estimator_.decision_function(self.transform(X)) @if_delegate_has_method(delegate='estimator') def",
"samples. y : array-like, shape = [n_samples] The target values. \"\"\" return self._fit(X,",
"features = np.arange(n_features)[support_] # Rank the remaining features estimator = clone(self.estimator) if self.estimator_params:",
"return self.estimator._estimator_type def fit(self, X, y): \"\"\"Fit the RFE model and then the",
"np.argsort(safe_sqr(coefs).sum(axis=0))[::-1] else: ranks = np.argsort(safe_sqr(coefs))[::-1] # for sparse case ranks is matrix ranks",
"Elimination while np.sum(support_) < n_features_to_select: # Remaining features features = np.arange(n_features)[support_] # Rank",
"estimator.feature_importances_ else: raise RuntimeError('The classifier does not expose ' '\"coef_\" or \"feature_importances_\" '",
"[n_samples] The target values. \"\"\" return self.estimator_.score(self.transform(X), y) def _get_support_mask(self): return self.support_ @if_delegate_has_method(delegate='estimator')",
"Linear Models from the `svm` and `linear_model` modules. n_features_to_select : int or None",
"is deprecated as \" \"of version 0.16 and will be removed in 0.18.",
"sklearn.cross_validation import _safe_split, _score from sklearn.metrics.scorer import check_scoring from sklearn.feature_selection.base import SelectorMixin class",
"# Get ranks if coefs.ndim > 1: ranks = np.argsort(safe_sqr(coefs).sum(axis=0))[::-1] else: ranks =",
"# Elimination while np.sum(support_) < n_features_to_select: # Remaining features features = np.arange(n_features)[support_] #",
"features and then return the score of the underlying estimator. Parameters ---------- X",
"ranking_[np.logical_not(support_)] += 1 # Set final attributes features = np.arange(n_features)[support_] self.estimator_ = clone(self.estimator)",
"to retrieve the 5 right informative features in the Friedman #1 dataset. >>>",
"dict Parameters for the external estimator. This attribute is deprecated as of version",
"version 0.16 and will be removed in 0.18. The \" \"parameter is no",
"# that have not been eliminated yet if step_score: self.scores_.append(step_score(estimator, features)) support_[features[ranks][:threshold]] =",
">0\") if self.estimator_params is not None: warnings.warn(\"The parameter 'estimator_params' is deprecated as \"",
"<gh_stars>1-10 # Sequential Forward Selection import warnings import numpy as np from sklearn.utils",
": int, default=0 Controls verbosity of output. Attributes ---------- n_features_ : int The",
"1.0: step = int(max(1, self.step * n_features)) else: step = int(self.step) if step",
"= 1 if step_score: self.scores_ = [] # Elimination while np.sum(support_) < n_features_to_select:",
"Eliminate the worse features threshold = min(step, n_features_to_select - np.sum(support_)) # Compute step",
"safe_sqr from sklearn.utils.metaestimators import if_delegate_has_method from sklearn.base import BaseEstimator from sklearn.base import MetaEstimatorMixin",
"1. estimator_ : object The external estimator fit on the reduced dataset. Examples",
"@if_delegate_has_method(delegate='estimator') def predict(self, X): \"\"\"Reduce X to the selected features and then predict",
"Learn., 46(1-3), 389--422, 2002. \"\"\" def __init__(self, estimator, n_features_to_select=None, step=1, estimator_params=None, verbose=0): self.estimator",
"from the `svm` and `linear_model` modules. n_features_to_select : int or None (default=None) The",
"hasattr(estimator, 'coef_'): coefs = estimator.coef_ elif hasattr(estimator, 'feature_importances_'): coefs = estimator.feature_importances_ else: raise",
"self.estimator_params: self.estimator_.set_params(**self.estimator_params) self.estimator_.fit(X[:, features], y) # Compute step score when only n_features_to_select features",
"= np.arange(n_features)[support_] self.estimator_ = clone(self.estimator) if self.estimator_params: self.estimator_.set_params(**self.estimator_params) self.estimator_.fit(X[:, features], y) # Compute",
"the case for most supervised learning algorithms such as Support Vector Classifiers and",
"self.estimator_.score(self.transform(X), y) def _get_support_mask(self): return self.support_ @if_delegate_has_method(delegate='estimator') def decision_function(self, X): return self.estimator_.decision_function(self.transform(X)) @if_delegate_has_method(delegate='estimator')",
"step_score=None): #X, y = check_X_y(X, y, \"csc\") # Initialization n_features = X.shape[1] if",
"the initial set of features and weights are assigned to each one of",
"decision_function(self, X): return self.estimator_.decision_function(self.transform(X)) @if_delegate_has_method(delegate='estimator') def predict_proba(self, X): return self.estimator_.predict_proba(self.transform(X)) @if_delegate_has_method(delegate='estimator') def predict_log_proba(self,",
"weights are assigned to each one of them. Then, features whose absolute weights",
"of features. First, the estimator is trained on the initial set of features",
"shape [n_samples] The predicted target values. \"\"\" return self.estimator_.predict(self.transform(X)) @if_delegate_has_method(delegate='estimator') def score(self, X,",
"step = int(max(1, self.step * n_features)) else: step = int(self.step) if step <=",
"'feature_importances_'): coefs = estimator.feature_importances_ else: raise RuntimeError('The classifier does not expose ' '\"coef_\"",
"using support vector machines\", Mach. Learn., 46(1-3), 389--422, 2002. \"\"\" def __init__(self, estimator,",
"ranking_ return self @if_delegate_has_method(delegate='estimator') def predict(self, X): \"\"\"Reduce X to the selected features",
"RFE model and then the underlying estimator on the selected features. Parameters ----------"
] |
[
"# fp = tempfile.TemporaryFile() # bh = list(map(lambda v: v.encode(\"utf-8\"), regular_entry_base_meta_columns)) no_t =",
"ts: datetime.strftime(ts, \"%Y\"), \"last_edit_ts\": lambda ts: datetime.strftime(ts, \"%Y\"), \"template\": lambda template: template.title, \"actors\":",
"resolve_values(aspect, value): a_name = aspect.get(NAME) a_type = aspect[TYPE] if a_type in TERMINAL_ASPECT_TYPES: return",
"\":\" transformer = { \"uuid\": lambda uuid: str(uuid), \"creation_ts\": lambda ts: datetime.strftime(ts, \"%Y\"),",
"fp.read() for aspect in template.aspects: res = resolve_values(aspect, entry.values[aspect.name]) return csv_text def resolve_values(aspect,",
"a_name = aspect.get(NAME) a_type = aspect[TYPE] if a_type in TERMINAL_ASPECT_TYPES: return {a_name: value[VALUE]}",
"lambda template: template.title, \"actors\": lambda actors: cell_separated( list(map(lambda entry_role: entry_role.csv_format(inner_value_sep), actors)) ), }",
"# bh = list(map(lambda v: v.encode(\"utf-8\"), regular_entry_base_meta_columns)) no_t = open(\"t.csv\", \"w\") writer =",
"import DictWriter from datetime import datetime from typing import List from app.models.orm import",
"entry_role.csv_format(inner_value_sep), entry.actors, ) ) ) ) for col in regular_entry_base_meta_columns: # if col",
"\"license\", \"image\", \"attached_files\", \"actors\", ] straight_grab = [ \"uuid\", \"creation_ts\", \"domain\", \"template_version\", \"type\",",
"# fp.seek(0) # csv_text = fp.read() for aspect in template.aspects: res = resolve_values(aspect,",
"uuid: str(uuid), \"creation_ts\": lambda ts: datetime.strftime(ts, \"%Y\"), \"last_edit_ts\": lambda ts: datetime.strftime(ts, \"%Y\"), \"template\":",
"inner_value_sep = \":\" transformer = { \"uuid\": lambda uuid: str(uuid), \"creation_ts\": lambda ts:",
"cell_separated( list(map(lambda entry_role: entry_role.csv_format(inner_value_sep), actors)) ), } def cell_separated(values: List[str]): return list_item_sep.join(values) def",
"method... # fp.seek(0) # csv_text = fp.read() for aspect in template.aspects: res =",
"def cell_separated(values: List[str]): return list_item_sep.join(values) def transform_to_csv(entry: Entry, template: Entry): res = {}",
"= { \"uuid\": lambda uuid: str(uuid), \"creation_ts\": lambda ts: datetime.strftime(ts, \"%Y\"), \"last_edit_ts\": lambda",
"lambda actors: cell_separated( list(map(lambda entry_role: entry_role.csv_format(inner_value_sep), actors)) ), } def cell_separated(values: List[str]): return",
"writer.writeheader() writer.writerow(res) no_t.close() csv_text = open(\"t.csv\").read() # temp file method... # fp.seek(0) #",
"= fp.read() for aspect in template.aspects: res = resolve_values(aspect, entry.values[aspect.name]) return csv_text def",
"template.title, \"actors\": lambda actors: cell_separated( list(map(lambda entry_role: entry_role.csv_format(inner_value_sep), actors)) ), } def cell_separated(values:",
"val: val = \"\" if col in transformer: val = transformer[col](val) res[col] =",
"\"type\", \"last_edit_ts\", \"version\", \"title\", \"status\", \"description\", \"language\", \"privacy\", \"license\", \"image\", \"template_version\", ] list_item_sep",
"return list_item_sep.join(values) def transform_to_csv(entry: Entry, template: Entry): res = {} print( cell_separated( list(",
"= open(\"t.csv\").read() # temp file method... # fp.seek(0) # csv_text = fp.read() for",
"import List from app.models.orm import Entry from app.util.consts import TYPE, NAME, TERMINAL_ASPECT_TYPES, VALUE",
"temp file method. doesnt work atm # fp = tempfile.TemporaryFile() # bh =",
"fp.seek(0) # csv_text = fp.read() for aspect in template.aspects: res = resolve_values(aspect, entry.values[aspect.name])",
"Entry): res = {} print( cell_separated( list( map( lambda entry_role: entry_role.csv_format(inner_value_sep), entry.actors, )",
"] list_item_sep = \"|\" inner_value_sep = \":\" transformer = { \"uuid\": lambda uuid:",
"template: template.title, \"actors\": lambda actors: cell_separated( list(map(lambda entry_role: entry_role.csv_format(inner_value_sep), actors)) ), } def",
"\"description\", \"language\", \"privacy\", \"license\", \"image\", \"template_version\", ] list_item_sep = \"|\" inner_value_sep = \":\"",
"\"template\": lambda template: template.title, \"actors\": lambda actors: cell_separated( list(map(lambda entry_role: entry_role.csv_format(inner_value_sep), actors)) ),",
"\"actors\", ] straight_grab = [ \"uuid\", \"creation_ts\", \"domain\", \"template_version\", \"type\", \"last_edit_ts\", \"version\", \"title\",",
"val # temp file method. doesnt work atm # fp = tempfile.TemporaryFile() #",
"\"template\", \"template_version\", \"type\", \"last_edit_ts\", \"version\", \"title\", \"status\", \"description\", \"language\", \"privacy\", \"license\", \"image\", \"attached_files\",",
"print( cell_separated( list( map( lambda entry_role: entry_role.csv_format(inner_value_sep), entry.actors, ) ) ) ) for",
"\"last_edit_ts\", \"version\", \"title\", \"status\", \"description\", \"language\", \"privacy\", \"license\", \"image\", \"template_version\", ] list_item_sep =",
"), } def cell_separated(values: List[str]): return list_item_sep.join(values) def transform_to_csv(entry: Entry, template: Entry): res",
"Entry, template: Entry): res = {} print( cell_separated( list( map( lambda entry_role: entry_role.csv_format(inner_value_sep),",
"= \"\" if col in transformer: val = transformer[col](val) res[col] = val #",
"{ \"uuid\": lambda uuid: str(uuid), \"creation_ts\": lambda ts: datetime.strftime(ts, \"%Y\"), \"last_edit_ts\": lambda ts:",
"\"uuid\": lambda uuid: str(uuid), \"creation_ts\": lambda ts: datetime.strftime(ts, \"%Y\"), \"last_edit_ts\": lambda ts: datetime.strftime(ts,",
"csv import DictWriter from datetime import datetime from typing import List from app.models.orm",
"datetime from typing import List from app.models.orm import Entry from app.util.consts import TYPE,",
"entry_role: entry_role.csv_format(inner_value_sep), entry.actors, ) ) ) ) for col in regular_entry_base_meta_columns: # if",
"regular_entry_base_meta_columns = [ \"uuid\", \"creation_ts\", \"domain\", \"template\", \"template_version\", \"type\", \"last_edit_ts\", \"version\", \"title\", \"status\",",
"\"license\", \"image\", \"template_version\", ] list_item_sep = \"|\" inner_value_sep = \":\" transformer = {",
"DictWriter(no_t, regular_entry_base_meta_columns) # print(bh) # print(writer.fieldnames) writer.writeheader() writer.writerow(res) no_t.close() csv_text = open(\"t.csv\").read() #",
"\"creation_ts\", \"domain\", \"template\", \"template_version\", \"type\", \"last_edit_ts\", \"version\", \"title\", \"status\", \"description\", \"language\", \"privacy\", \"license\",",
"# if col in straight_grab: val = getattr(entry, col) if not val: val",
"regular_entry_base_meta_columns)) no_t = open(\"t.csv\", \"w\") writer = DictWriter(no_t, regular_entry_base_meta_columns) # print(bh) # print(writer.fieldnames)",
"\"domain\", \"template_version\", \"type\", \"last_edit_ts\", \"version\", \"title\", \"status\", \"description\", \"language\", \"privacy\", \"license\", \"image\", \"template_version\",",
"\"privacy\", \"license\", \"image\", \"attached_files\", \"actors\", ] straight_grab = [ \"uuid\", \"creation_ts\", \"domain\", \"template_version\",",
"<gh_stars>0 from csv import DictWriter from datetime import datetime from typing import List",
"cell_separated( list( map( lambda entry_role: entry_role.csv_format(inner_value_sep), entry.actors, ) ) ) ) for col",
"\"uuid\", \"creation_ts\", \"domain\", \"template_version\", \"type\", \"last_edit_ts\", \"version\", \"title\", \"status\", \"description\", \"language\", \"privacy\", \"license\",",
"no_t.close() csv_text = open(\"t.csv\").read() # temp file method... # fp.seek(0) # csv_text =",
"datetime import datetime from typing import List from app.models.orm import Entry from app.util.consts",
"\"uuid\", \"creation_ts\", \"domain\", \"template\", \"template_version\", \"type\", \"last_edit_ts\", \"version\", \"title\", \"status\", \"description\", \"language\", \"privacy\",",
"entry.actors, ) ) ) ) for col in regular_entry_base_meta_columns: # if col in",
"if col in transformer: val = transformer[col](val) res[col] = val # temp file",
"list(map(lambda v: v.encode(\"utf-8\"), regular_entry_base_meta_columns)) no_t = open(\"t.csv\", \"w\") writer = DictWriter(no_t, regular_entry_base_meta_columns) #",
"\"title\", \"status\", \"description\", \"language\", \"privacy\", \"license\", \"image\", \"template_version\", ] list_item_sep = \"|\" inner_value_sep",
"for col in regular_entry_base_meta_columns: # if col in straight_grab: val = getattr(entry, col)",
"resolve_values(aspect, entry.values[aspect.name]) return csv_text def resolve_values(aspect, value): a_name = aspect.get(NAME) a_type = aspect[TYPE]",
"transform_to_csv(entry: Entry, template: Entry): res = {} print( cell_separated( list( map( lambda entry_role:",
"# temp file method... # fp.seek(0) # csv_text = fp.read() for aspect in",
"writer = DictWriter(no_t, regular_entry_base_meta_columns) # print(bh) # print(writer.fieldnames) writer.writeheader() writer.writerow(res) no_t.close() csv_text =",
"= transformer[col](val) res[col] = val # temp file method. doesnt work atm #",
"entry.values[aspect.name]) return csv_text def resolve_values(aspect, value): a_name = aspect.get(NAME) a_type = aspect[TYPE] if",
"col in regular_entry_base_meta_columns: # if col in straight_grab: val = getattr(entry, col) if",
"val = transformer[col](val) res[col] = val # temp file method. doesnt work atm",
"aspect in template.aspects: res = resolve_values(aspect, entry.values[aspect.name]) return csv_text def resolve_values(aspect, value): a_name",
"\"creation_ts\", \"domain\", \"template_version\", \"type\", \"last_edit_ts\", \"version\", \"title\", \"status\", \"description\", \"language\", \"privacy\", \"license\", \"image\",",
"import datetime from typing import List from app.models.orm import Entry from app.util.consts import",
"transformer: val = transformer[col](val) res[col] = val # temp file method. doesnt work",
"v: v.encode(\"utf-8\"), regular_entry_base_meta_columns)) no_t = open(\"t.csv\", \"w\") writer = DictWriter(no_t, regular_entry_base_meta_columns) # print(bh)",
"in template.aspects: res = resolve_values(aspect, entry.values[aspect.name]) return csv_text def resolve_values(aspect, value): a_name =",
"regular_entry_base_meta_columns: # if col in straight_grab: val = getattr(entry, col) if not val:",
"atm # fp = tempfile.TemporaryFile() # bh = list(map(lambda v: v.encode(\"utf-8\"), regular_entry_base_meta_columns)) no_t",
"method. doesnt work atm # fp = tempfile.TemporaryFile() # bh = list(map(lambda v:",
"not val: val = \"\" if col in transformer: val = transformer[col](val) res[col]",
"\"actors\": lambda actors: cell_separated( list(map(lambda entry_role: entry_role.csv_format(inner_value_sep), actors)) ), } def cell_separated(values: List[str]):",
"writer.writerow(res) no_t.close() csv_text = open(\"t.csv\").read() # temp file method... # fp.seek(0) # csv_text",
"if not val: val = \"\" if col in transformer: val = transformer[col](val)",
"col in transformer: val = transformer[col](val) res[col] = val # temp file method.",
"app.util.consts import TYPE, NAME, TERMINAL_ASPECT_TYPES, VALUE regular_entry_base_meta_columns = [ \"uuid\", \"creation_ts\", \"domain\", \"template\",",
"\"|\" inner_value_sep = \":\" transformer = { \"uuid\": lambda uuid: str(uuid), \"creation_ts\": lambda",
") for col in regular_entry_base_meta_columns: # if col in straight_grab: val = getattr(entry,",
"transformer[col](val) res[col] = val # temp file method. doesnt work atm # fp",
"open(\"t.csv\", \"w\") writer = DictWriter(no_t, regular_entry_base_meta_columns) # print(bh) # print(writer.fieldnames) writer.writeheader() writer.writerow(res) no_t.close()",
"= tempfile.TemporaryFile() # bh = list(map(lambda v: v.encode(\"utf-8\"), regular_entry_base_meta_columns)) no_t = open(\"t.csv\", \"w\")",
"from csv import DictWriter from datetime import datetime from typing import List from",
"res = resolve_values(aspect, entry.values[aspect.name]) return csv_text def resolve_values(aspect, value): a_name = aspect.get(NAME) a_type",
"in straight_grab: val = getattr(entry, col) if not val: val = \"\" if",
"res[col] = val # temp file method. doesnt work atm # fp =",
"\"\" if col in transformer: val = transformer[col](val) res[col] = val # temp",
"\"title\", \"status\", \"description\", \"language\", \"privacy\", \"license\", \"image\", \"attached_files\", \"actors\", ] straight_grab = [",
"bh = list(map(lambda v: v.encode(\"utf-8\"), regular_entry_base_meta_columns)) no_t = open(\"t.csv\", \"w\") writer = DictWriter(no_t,",
"doesnt work atm # fp = tempfile.TemporaryFile() # bh = list(map(lambda v: v.encode(\"utf-8\"),",
"cell_separated(values: List[str]): return list_item_sep.join(values) def transform_to_csv(entry: Entry, template: Entry): res = {} print(",
"\"status\", \"description\", \"language\", \"privacy\", \"license\", \"image\", \"template_version\", ] list_item_sep = \"|\" inner_value_sep =",
"list_item_sep = \"|\" inner_value_sep = \":\" transformer = { \"uuid\": lambda uuid: str(uuid),",
"[ \"uuid\", \"creation_ts\", \"domain\", \"template\", \"template_version\", \"type\", \"last_edit_ts\", \"version\", \"title\", \"status\", \"description\", \"language\",",
"lambda ts: datetime.strftime(ts, \"%Y\"), \"last_edit_ts\": lambda ts: datetime.strftime(ts, \"%Y\"), \"template\": lambda template: template.title,",
"VALUE regular_entry_base_meta_columns = [ \"uuid\", \"creation_ts\", \"domain\", \"template\", \"template_version\", \"type\", \"last_edit_ts\", \"version\", \"title\",",
"entry_role.csv_format(inner_value_sep), actors)) ), } def cell_separated(values: List[str]): return list_item_sep.join(values) def transform_to_csv(entry: Entry, template:",
"\"attached_files\", \"actors\", ] straight_grab = [ \"uuid\", \"creation_ts\", \"domain\", \"template_version\", \"type\", \"last_edit_ts\", \"version\",",
"datetime.strftime(ts, \"%Y\"), \"template\": lambda template: template.title, \"actors\": lambda actors: cell_separated( list(map(lambda entry_role: entry_role.csv_format(inner_value_sep),",
"print(bh) # print(writer.fieldnames) writer.writeheader() writer.writerow(res) no_t.close() csv_text = open(\"t.csv\").read() # temp file method...",
"from typing import List from app.models.orm import Entry from app.util.consts import TYPE, NAME,",
"lambda uuid: str(uuid), \"creation_ts\": lambda ts: datetime.strftime(ts, \"%Y\"), \"last_edit_ts\": lambda ts: datetime.strftime(ts, \"%Y\"),",
"\"%Y\"), \"template\": lambda template: template.title, \"actors\": lambda actors: cell_separated( list(map(lambda entry_role: entry_role.csv_format(inner_value_sep), actors))",
"\"language\", \"privacy\", \"license\", \"image\", \"attached_files\", \"actors\", ] straight_grab = [ \"uuid\", \"creation_ts\", \"domain\",",
"file method... # fp.seek(0) # csv_text = fp.read() for aspect in template.aspects: res",
"# csv_text = fp.read() for aspect in template.aspects: res = resolve_values(aspect, entry.values[aspect.name]) return",
"no_t = open(\"t.csv\", \"w\") writer = DictWriter(no_t, regular_entry_base_meta_columns) # print(bh) # print(writer.fieldnames) writer.writeheader()",
"\"w\") writer = DictWriter(no_t, regular_entry_base_meta_columns) # print(bh) # print(writer.fieldnames) writer.writeheader() writer.writerow(res) no_t.close() csv_text",
"} def cell_separated(values: List[str]): return list_item_sep.join(values) def transform_to_csv(entry: Entry, template: Entry): res =",
"list(map(lambda entry_role: entry_role.csv_format(inner_value_sep), actors)) ), } def cell_separated(values: List[str]): return list_item_sep.join(values) def transform_to_csv(entry:",
"template.aspects: res = resolve_values(aspect, entry.values[aspect.name]) return csv_text def resolve_values(aspect, value): a_name = aspect.get(NAME)",
"lambda ts: datetime.strftime(ts, \"%Y\"), \"template\": lambda template: template.title, \"actors\": lambda actors: cell_separated( list(map(lambda",
"in regular_entry_base_meta_columns: # if col in straight_grab: val = getattr(entry, col) if not",
"\"image\", \"template_version\", ] list_item_sep = \"|\" inner_value_sep = \":\" transformer = { \"uuid\":",
"return csv_text def resolve_values(aspect, value): a_name = aspect.get(NAME) a_type = aspect[TYPE] if a_type",
"= [ \"uuid\", \"creation_ts\", \"domain\", \"template_version\", \"type\", \"last_edit_ts\", \"version\", \"title\", \"status\", \"description\", \"language\",",
"typing import List from app.models.orm import Entry from app.util.consts import TYPE, NAME, TERMINAL_ASPECT_TYPES,",
"v.encode(\"utf-8\"), regular_entry_base_meta_columns)) no_t = open(\"t.csv\", \"w\") writer = DictWriter(no_t, regular_entry_base_meta_columns) # print(bh) #",
"from app.util.consts import TYPE, NAME, TERMINAL_ASPECT_TYPES, VALUE regular_entry_base_meta_columns = [ \"uuid\", \"creation_ts\", \"domain\",",
"actors: cell_separated( list(map(lambda entry_role: entry_role.csv_format(inner_value_sep), actors)) ), } def cell_separated(values: List[str]): return list_item_sep.join(values)",
"val = \"\" if col in transformer: val = transformer[col](val) res[col] = val",
"= \":\" transformer = { \"uuid\": lambda uuid: str(uuid), \"creation_ts\": lambda ts: datetime.strftime(ts,",
"list( map( lambda entry_role: entry_role.csv_format(inner_value_sep), entry.actors, ) ) ) ) for col in",
"regular_entry_base_meta_columns) # print(bh) # print(writer.fieldnames) writer.writeheader() writer.writerow(res) no_t.close() csv_text = open(\"t.csv\").read() # temp",
"\"template_version\", \"type\", \"last_edit_ts\", \"version\", \"title\", \"status\", \"description\", \"language\", \"privacy\", \"license\", \"image\", \"attached_files\", \"actors\",",
"= resolve_values(aspect, entry.values[aspect.name]) return csv_text def resolve_values(aspect, value): a_name = aspect.get(NAME) a_type =",
"# print(writer.fieldnames) writer.writeheader() writer.writerow(res) no_t.close() csv_text = open(\"t.csv\").read() # temp file method... #",
"\"last_edit_ts\", \"version\", \"title\", \"status\", \"description\", \"language\", \"privacy\", \"license\", \"image\", \"attached_files\", \"actors\", ] straight_grab",
"DictWriter from datetime import datetime from typing import List from app.models.orm import Entry",
"List[str]): return list_item_sep.join(values) def transform_to_csv(entry: Entry, template: Entry): res = {} print( cell_separated(",
"= [ \"uuid\", \"creation_ts\", \"domain\", \"template\", \"template_version\", \"type\", \"last_edit_ts\", \"version\", \"title\", \"status\", \"description\",",
"\"language\", \"privacy\", \"license\", \"image\", \"template_version\", ] list_item_sep = \"|\" inner_value_sep = \":\" transformer",
"= \"|\" inner_value_sep = \":\" transformer = { \"uuid\": lambda uuid: str(uuid), \"creation_ts\":",
"print(writer.fieldnames) writer.writeheader() writer.writerow(res) no_t.close() csv_text = open(\"t.csv\").read() # temp file method... # fp.seek(0)",
"\"image\", \"attached_files\", \"actors\", ] straight_grab = [ \"uuid\", \"creation_ts\", \"domain\", \"template_version\", \"type\", \"last_edit_ts\",",
"\"template_version\", ] list_item_sep = \"|\" inner_value_sep = \":\" transformer = { \"uuid\": lambda",
"import TYPE, NAME, TERMINAL_ASPECT_TYPES, VALUE regular_entry_base_meta_columns = [ \"uuid\", \"creation_ts\", \"domain\", \"template\", \"template_version\",",
"transformer = { \"uuid\": lambda uuid: str(uuid), \"creation_ts\": lambda ts: datetime.strftime(ts, \"%Y\"), \"last_edit_ts\":",
"from datetime import datetime from typing import List from app.models.orm import Entry from",
"lambda entry_role: entry_role.csv_format(inner_value_sep), entry.actors, ) ) ) ) for col in regular_entry_base_meta_columns: #",
") ) for col in regular_entry_base_meta_columns: # if col in straight_grab: val =",
"getattr(entry, col) if not val: val = \"\" if col in transformer: val",
"for aspect in template.aspects: res = resolve_values(aspect, entry.values[aspect.name]) return csv_text def resolve_values(aspect, value):",
"def resolve_values(aspect, value): a_name = aspect.get(NAME) a_type = aspect[TYPE] if a_type in TERMINAL_ASPECT_TYPES:",
"str(uuid), \"creation_ts\": lambda ts: datetime.strftime(ts, \"%Y\"), \"last_edit_ts\": lambda ts: datetime.strftime(ts, \"%Y\"), \"template\": lambda",
"entry_role: entry_role.csv_format(inner_value_sep), actors)) ), } def cell_separated(values: List[str]): return list_item_sep.join(values) def transform_to_csv(entry: Entry,",
"\"privacy\", \"license\", \"image\", \"template_version\", ] list_item_sep = \"|\" inner_value_sep = \":\" transformer =",
"NAME, TERMINAL_ASPECT_TYPES, VALUE regular_entry_base_meta_columns = [ \"uuid\", \"creation_ts\", \"domain\", \"template\", \"template_version\", \"type\", \"last_edit_ts\",",
"\"description\", \"language\", \"privacy\", \"license\", \"image\", \"attached_files\", \"actors\", ] straight_grab = [ \"uuid\", \"creation_ts\",",
"{} print( cell_separated( list( map( lambda entry_role: entry_role.csv_format(inner_value_sep), entry.actors, ) ) ) )",
"\"status\", \"description\", \"language\", \"privacy\", \"license\", \"image\", \"attached_files\", \"actors\", ] straight_grab = [ \"uuid\",",
"TERMINAL_ASPECT_TYPES, VALUE regular_entry_base_meta_columns = [ \"uuid\", \"creation_ts\", \"domain\", \"template\", \"template_version\", \"type\", \"last_edit_ts\", \"version\",",
"temp file method... # fp.seek(0) # csv_text = fp.read() for aspect in template.aspects:",
"List from app.models.orm import Entry from app.util.consts import TYPE, NAME, TERMINAL_ASPECT_TYPES, VALUE regular_entry_base_meta_columns",
"col) if not val: val = \"\" if col in transformer: val =",
"in transformer: val = transformer[col](val) res[col] = val # temp file method. doesnt",
"fp = tempfile.TemporaryFile() # bh = list(map(lambda v: v.encode(\"utf-8\"), regular_entry_base_meta_columns)) no_t = open(\"t.csv\",",
"def transform_to_csv(entry: Entry, template: Entry): res = {} print( cell_separated( list( map( lambda",
"\"last_edit_ts\": lambda ts: datetime.strftime(ts, \"%Y\"), \"template\": lambda template: template.title, \"actors\": lambda actors: cell_separated(",
"res = {} print( cell_separated( list( map( lambda entry_role: entry_role.csv_format(inner_value_sep), entry.actors, ) )",
"file method. doesnt work atm # fp = tempfile.TemporaryFile() # bh = list(map(lambda",
"] straight_grab = [ \"uuid\", \"creation_ts\", \"domain\", \"template_version\", \"type\", \"last_edit_ts\", \"version\", \"title\", \"status\",",
"= getattr(entry, col) if not val: val = \"\" if col in transformer:",
"= DictWriter(no_t, regular_entry_base_meta_columns) # print(bh) # print(writer.fieldnames) writer.writeheader() writer.writerow(res) no_t.close() csv_text = open(\"t.csv\").read()",
"app.models.orm import Entry from app.util.consts import TYPE, NAME, TERMINAL_ASPECT_TYPES, VALUE regular_entry_base_meta_columns = [",
"open(\"t.csv\").read() # temp file method... # fp.seek(0) # csv_text = fp.read() for aspect",
"= open(\"t.csv\", \"w\") writer = DictWriter(no_t, regular_entry_base_meta_columns) # print(bh) # print(writer.fieldnames) writer.writeheader() writer.writerow(res)",
"# print(bh) # print(writer.fieldnames) writer.writeheader() writer.writerow(res) no_t.close() csv_text = open(\"t.csv\").read() # temp file",
"if col in straight_grab: val = getattr(entry, col) if not val: val =",
"import Entry from app.util.consts import TYPE, NAME, TERMINAL_ASPECT_TYPES, VALUE regular_entry_base_meta_columns = [ \"uuid\",",
"\"version\", \"title\", \"status\", \"description\", \"language\", \"privacy\", \"license\", \"image\", \"template_version\", ] list_item_sep = \"|\"",
"actors)) ), } def cell_separated(values: List[str]): return list_item_sep.join(values) def transform_to_csv(entry: Entry, template: Entry):",
"ts: datetime.strftime(ts, \"%Y\"), \"template\": lambda template: template.title, \"actors\": lambda actors: cell_separated( list(map(lambda entry_role:",
"\"type\", \"last_edit_ts\", \"version\", \"title\", \"status\", \"description\", \"language\", \"privacy\", \"license\", \"image\", \"attached_files\", \"actors\", ]",
"\"creation_ts\": lambda ts: datetime.strftime(ts, \"%Y\"), \"last_edit_ts\": lambda ts: datetime.strftime(ts, \"%Y\"), \"template\": lambda template:",
"\"%Y\"), \"last_edit_ts\": lambda ts: datetime.strftime(ts, \"%Y\"), \"template\": lambda template: template.title, \"actors\": lambda actors:",
"\"version\", \"title\", \"status\", \"description\", \"language\", \"privacy\", \"license\", \"image\", \"attached_files\", \"actors\", ] straight_grab =",
"straight_grab = [ \"uuid\", \"creation_ts\", \"domain\", \"template_version\", \"type\", \"last_edit_ts\", \"version\", \"title\", \"status\", \"description\",",
"template: Entry): res = {} print( cell_separated( list( map( lambda entry_role: entry_role.csv_format(inner_value_sep), entry.actors,",
"list_item_sep.join(values) def transform_to_csv(entry: Entry, template: Entry): res = {} print( cell_separated( list( map(",
"# temp file method. doesnt work atm # fp = tempfile.TemporaryFile() # bh",
"work atm # fp = tempfile.TemporaryFile() # bh = list(map(lambda v: v.encode(\"utf-8\"), regular_entry_base_meta_columns))",
") ) ) ) for col in regular_entry_base_meta_columns: # if col in straight_grab:",
") ) ) for col in regular_entry_base_meta_columns: # if col in straight_grab: val",
"straight_grab: val = getattr(entry, col) if not val: val = \"\" if col",
"tempfile.TemporaryFile() # bh = list(map(lambda v: v.encode(\"utf-8\"), regular_entry_base_meta_columns)) no_t = open(\"t.csv\", \"w\") writer",
"csv_text = open(\"t.csv\").read() # temp file method... # fp.seek(0) # csv_text = fp.read()",
"Entry from app.util.consts import TYPE, NAME, TERMINAL_ASPECT_TYPES, VALUE regular_entry_base_meta_columns = [ \"uuid\", \"creation_ts\",",
"TYPE, NAME, TERMINAL_ASPECT_TYPES, VALUE regular_entry_base_meta_columns = [ \"uuid\", \"creation_ts\", \"domain\", \"template\", \"template_version\", \"type\",",
"\"template_version\", \"type\", \"last_edit_ts\", \"version\", \"title\", \"status\", \"description\", \"language\", \"privacy\", \"license\", \"image\", \"template_version\", ]",
"map( lambda entry_role: entry_role.csv_format(inner_value_sep), entry.actors, ) ) ) ) for col in regular_entry_base_meta_columns:",
"csv_text def resolve_values(aspect, value): a_name = aspect.get(NAME) a_type = aspect[TYPE] if a_type in",
"\"domain\", \"template\", \"template_version\", \"type\", \"last_edit_ts\", \"version\", \"title\", \"status\", \"description\", \"language\", \"privacy\", \"license\", \"image\",",
"[ \"uuid\", \"creation_ts\", \"domain\", \"template_version\", \"type\", \"last_edit_ts\", \"version\", \"title\", \"status\", \"description\", \"language\", \"privacy\",",
"val = getattr(entry, col) if not val: val = \"\" if col in",
"col in straight_grab: val = getattr(entry, col) if not val: val = \"\"",
"datetime.strftime(ts, \"%Y\"), \"last_edit_ts\": lambda ts: datetime.strftime(ts, \"%Y\"), \"template\": lambda template: template.title, \"actors\": lambda",
"= val # temp file method. doesnt work atm # fp = tempfile.TemporaryFile()",
"csv_text = fp.read() for aspect in template.aspects: res = resolve_values(aspect, entry.values[aspect.name]) return csv_text",
"= list(map(lambda v: v.encode(\"utf-8\"), regular_entry_base_meta_columns)) no_t = open(\"t.csv\", \"w\") writer = DictWriter(no_t, regular_entry_base_meta_columns)",
"value): a_name = aspect.get(NAME) a_type = aspect[TYPE] if a_type in TERMINAL_ASPECT_TYPES: return {a_name:",
"from app.models.orm import Entry from app.util.consts import TYPE, NAME, TERMINAL_ASPECT_TYPES, VALUE regular_entry_base_meta_columns =",
"= {} print( cell_separated( list( map( lambda entry_role: entry_role.csv_format(inner_value_sep), entry.actors, ) ) )"
] |
[
"response = {'ok': True, 'message': 'no record found'} return jsonify(response), 200 else: return",
"True, 'message': 'User created successfully!', 'user': user}), 200 else: return jsonify({'ok': False, 'message':",
"user['email']}) if db_response.deleted_count == 1: response = {'ok': True, 'message': 'record deleted'} else:",
"a random string of fixed length \"\"\" letters = string.ascii_lowercase return ''.join(random.choice(letters) for",
"record found'} return jsonify(response), 200 else: return jsonify({'ok': False, 'message': 'Bad request parameters!'}),",
"jsonify from app import app, mongo import datetime import random import string @app.route('/users',",
"= <PASSWORD>() user['created_at'] = now user['updated_at'] = now mongo.db.users.insert_one(user) return jsonify({'ok': True, 'message':",
"def usersCreate(): user = request.get_json() if user.get('name', None) is not None and user.get('email',",
"= {'ok': True, 'message': 'record deleted'} else: response = {'ok': True, 'message': 'no",
"string @app.route('/users', methods=['GET']) def usersIndex(): data = list(mongo.db.users.find()) return jsonify({'result': data}), 200 @app.route('/users',",
"is not None: now = datetime.datetime.now() user['token'] = <PASSWORD>() user['created_at'] = now user['updated_at']",
"{'ok': True, 'message': 'no record found'} return jsonify(response), 200 else: return jsonify({'ok': False,",
"created successfully!', 'user': user}), 200 else: return jsonify({'ok': False, 'message': 'Bad request parameters!'}),",
"not None: now = datetime.datetime.now() user['token'] = <PASSWORD>() user['created_at'] = now user['updated_at'] =",
"db_response.deleted_count == 1: response = {'ok': True, 'message': 'record deleted'} else: response =",
"'message': 'Bad request parameters!'}), 400 @app.route('/users', methods=['DELETE']) def usersDelete(): user = request.get_json() if",
"1: response = {'ok': True, 'message': 'record deleted'} else: response = {'ok': True,",
"else: return jsonify({'ok': False, 'message': 'Bad request parameters!'}), 400 def randomString(stringLength=50): \"\"\"Generate a",
"@app.route('/users', methods=['GET']) def usersIndex(): data = list(mongo.db.users.find()) return jsonify({'result': data}), 200 @app.route('/users', methods=['POST'])",
"200 else: return jsonify({'ok': False, 'message': 'Bad request parameters!'}), 400 def randomString(stringLength=50): \"\"\"Generate",
"= now user['updated_at'] = now mongo.db.users.insert_one(user) return jsonify({'ok': True, 'message': 'User created successfully!',",
"from flask import request, jsonify from app import app, mongo import datetime import",
"request, jsonify from app import app, mongo import datetime import random import string",
"now user['updated_at'] = now mongo.db.users.insert_one(user) return jsonify({'ok': True, 'message': 'User created successfully!', 'user':",
"False, 'message': 'Bad request parameters!'}), 400 @app.route('/users', methods=['DELETE']) def usersDelete(): user = request.get_json()",
"user}), 200 else: return jsonify({'ok': False, 'message': 'Bad request parameters!'}), 400 @app.route('/users', methods=['DELETE'])",
"string of fixed length \"\"\" letters = string.ascii_lowercase return ''.join(random.choice(letters) for i in",
"'Bad request parameters!'}), 400 @app.route('/users', methods=['DELETE']) def usersDelete(): user = request.get_json() if user.get('email',",
"random string of fixed length \"\"\" letters = string.ascii_lowercase return ''.join(random.choice(letters) for i",
"app, mongo import datetime import random import string @app.route('/users', methods=['GET']) def usersIndex(): data",
"flask import request, jsonify from app import app, mongo import datetime import random",
"<PASSWORD>() user['created_at'] = now user['updated_at'] = now mongo.db.users.insert_one(user) return jsonify({'ok': True, 'message': 'User",
"not None: db_response = mongo.db.users.delete_one({'email': user['email']}) if db_response.deleted_count == 1: response = {'ok':",
"= {'ok': True, 'message': 'no record found'} return jsonify(response), 200 else: return jsonify({'ok':",
"import random import string @app.route('/users', methods=['GET']) def usersIndex(): data = list(mongo.db.users.find()) return jsonify({'result':",
"def usersDelete(): user = request.get_json() if user.get('email', None) is not None: db_response =",
"'user': user}), 200 else: return jsonify({'ok': False, 'message': 'Bad request parameters!'}), 400 @app.route('/users',",
"usersDelete(): user = request.get_json() if user.get('email', None) is not None: db_response = mongo.db.users.delete_one({'email':",
"None) is not None and user.get('email', None) is not None: now = datetime.datetime.now()",
"return jsonify({'ok': True, 'message': 'User created successfully!', 'user': user}), 200 else: return jsonify({'ok':",
"usersIndex(): data = list(mongo.db.users.find()) return jsonify({'result': data}), 200 @app.route('/users', methods=['POST']) def usersCreate(): user",
"jsonify({'ok': False, 'message': 'Bad request parameters!'}), 400 @app.route('/users', methods=['DELETE']) def usersDelete(): user =",
"response = {'ok': True, 'message': 'record deleted'} else: response = {'ok': True, 'message':",
"'message': 'record deleted'} else: response = {'ok': True, 'message': 'no record found'} return",
"\"\"\"Generate a random string of fixed length \"\"\" letters = string.ascii_lowercase return ''.join(random.choice(letters)",
"user['created_at'] = now user['updated_at'] = now mongo.db.users.insert_one(user) return jsonify({'ok': True, 'message': 'User created",
"400 @app.route('/users', methods=['DELETE']) def usersDelete(): user = request.get_json() if user.get('email', None) is not",
"jsonify({'ok': True, 'message': 'User created successfully!', 'user': user}), 200 else: return jsonify({'ok': False,",
"mongo.db.users.insert_one(user) return jsonify({'ok': True, 'message': 'User created successfully!', 'user': user}), 200 else: return",
"mongo import datetime import random import string @app.route('/users', methods=['GET']) def usersIndex(): data =",
"import datetime import random import string @app.route('/users', methods=['GET']) def usersIndex(): data = list(mongo.db.users.find())",
"import os from flask import request, jsonify from app import app, mongo import",
"request parameters!'}), 400 @app.route('/users', methods=['DELETE']) def usersDelete(): user = request.get_json() if user.get('email', None)",
"not None and user.get('email', None) is not None: now = datetime.datetime.now() user['token'] =",
"now mongo.db.users.insert_one(user) return jsonify({'ok': True, 'message': 'User created successfully!', 'user': user}), 200 else:",
"and user.get('email', None) is not None: now = datetime.datetime.now() user['token'] = <PASSWORD>() user['created_at']",
"None: now = datetime.datetime.now() user['token'] = <PASSWORD>() user['created_at'] = now user['updated_at'] = now",
"datetime.datetime.now() user['token'] = <PASSWORD>() user['created_at'] = now user['updated_at'] = now mongo.db.users.insert_one(user) return jsonify({'ok':",
"= request.get_json() if user.get('email', None) is not None: db_response = mongo.db.users.delete_one({'email': user['email']}) if",
"mongo.db.users.delete_one({'email': user['email']}) if db_response.deleted_count == 1: response = {'ok': True, 'message': 'record deleted'}",
"user = request.get_json() if user.get('name', None) is not None and user.get('email', None) is",
"user.get('name', None) is not None and user.get('email', None) is not None: now =",
"user['token'] = <PASSWORD>() user['created_at'] = now user['updated_at'] = now mongo.db.users.insert_one(user) return jsonify({'ok': True,",
"'message': 'no record found'} return jsonify(response), 200 else: return jsonify({'ok': False, 'message': 'Bad",
"'no record found'} return jsonify(response), 200 else: return jsonify({'ok': False, 'message': 'Bad request",
"request.get_json() if user.get('email', None) is not None: db_response = mongo.db.users.delete_one({'email': user['email']}) if db_response.deleted_count",
"'message': 'User created successfully!', 'user': user}), 200 else: return jsonify({'ok': False, 'message': 'Bad",
"def randomString(stringLength=50): \"\"\"Generate a random string of fixed length \"\"\" letters = string.ascii_lowercase",
"return jsonify({'ok': False, 'message': 'Bad request parameters!'}), 400 def randomString(stringLength=50): \"\"\"Generate a random",
"= list(mongo.db.users.find()) return jsonify({'result': data}), 200 @app.route('/users', methods=['POST']) def usersCreate(): user = request.get_json()",
"methods=['GET']) def usersIndex(): data = list(mongo.db.users.find()) return jsonify({'result': data}), 200 @app.route('/users', methods=['POST']) def",
"methods=['POST']) def usersCreate(): user = request.get_json() if user.get('name', None) is not None and",
"db_response = mongo.db.users.delete_one({'email': user['email']}) if db_response.deleted_count == 1: response = {'ok': True, 'message':",
"if db_response.deleted_count == 1: response = {'ok': True, 'message': 'record deleted'} else: response",
"of fixed length \"\"\" letters = string.ascii_lowercase return ''.join(random.choice(letters) for i in range(stringLength))",
"None and user.get('email', None) is not None: now = datetime.datetime.now() user['token'] = <PASSWORD>()",
"is not None: db_response = mongo.db.users.delete_one({'email': user['email']}) if db_response.deleted_count == 1: response =",
"successfully!', 'user': user}), 200 else: return jsonify({'ok': False, 'message': 'Bad request parameters!'}), 400",
"now = datetime.datetime.now() user['token'] = <PASSWORD>() user['created_at'] = now user['updated_at'] = now mongo.db.users.insert_one(user)",
"import app, mongo import datetime import random import string @app.route('/users', methods=['GET']) def usersIndex():",
"None) is not None: now = datetime.datetime.now() user['token'] = <PASSWORD>() user['created_at'] = now",
"jsonify({'result': data}), 200 @app.route('/users', methods=['POST']) def usersCreate(): user = request.get_json() if user.get('name', None)",
"else: response = {'ok': True, 'message': 'no record found'} return jsonify(response), 200 else:",
"'message': 'Bad request parameters!'}), 400 def randomString(stringLength=50): \"\"\"Generate a random string of fixed",
"list(mongo.db.users.find()) return jsonify({'result': data}), 200 @app.route('/users', methods=['POST']) def usersCreate(): user = request.get_json() if",
"data}), 200 @app.route('/users', methods=['POST']) def usersCreate(): user = request.get_json() if user.get('name', None) is",
"request.get_json() if user.get('name', None) is not None and user.get('email', None) is not None:",
"True, 'message': 'record deleted'} else: response = {'ok': True, 'message': 'no record found'}",
"deleted'} else: response = {'ok': True, 'message': 'no record found'} return jsonify(response), 200",
"True, 'message': 'no record found'} return jsonify(response), 200 else: return jsonify({'ok': False, 'message':",
"methods=['DELETE']) def usersDelete(): user = request.get_json() if user.get('email', None) is not None: db_response",
"= request.get_json() if user.get('name', None) is not None and user.get('email', None) is not",
"parameters!'}), 400 def randomString(stringLength=50): \"\"\"Generate a random string of fixed length \"\"\" letters",
"user.get('email', None) is not None: now = datetime.datetime.now() user['token'] = <PASSWORD>() user['created_at'] =",
"200 else: return jsonify({'ok': False, 'message': 'Bad request parameters!'}), 400 @app.route('/users', methods=['DELETE']) def",
"random import string @app.route('/users', methods=['GET']) def usersIndex(): data = list(mongo.db.users.find()) return jsonify({'result': data}),",
"400 def randomString(stringLength=50): \"\"\"Generate a random string of fixed length \"\"\" letters =",
"if user.get('email', None) is not None: db_response = mongo.db.users.delete_one({'email': user['email']}) if db_response.deleted_count ==",
"None) is not None: db_response = mongo.db.users.delete_one({'email': user['email']}) if db_response.deleted_count == 1: response",
"return jsonify({'ok': False, 'message': 'Bad request parameters!'}), 400 @app.route('/users', methods=['DELETE']) def usersDelete(): user",
"parameters!'}), 400 @app.route('/users', methods=['DELETE']) def usersDelete(): user = request.get_json() if user.get('email', None) is",
"found'} return jsonify(response), 200 else: return jsonify({'ok': False, 'message': 'Bad request parameters!'}), 400",
"'User created successfully!', 'user': user}), 200 else: return jsonify({'ok': False, 'message': 'Bad request",
"user['updated_at'] = now mongo.db.users.insert_one(user) return jsonify({'ok': True, 'message': 'User created successfully!', 'user': user}),",
"import request, jsonify from app import app, mongo import datetime import random import",
"jsonify(response), 200 else: return jsonify({'ok': False, 'message': 'Bad request parameters!'}), 400 def randomString(stringLength=50):",
"200 @app.route('/users', methods=['POST']) def usersCreate(): user = request.get_json() if user.get('name', None) is not",
"{'ok': True, 'message': 'record deleted'} else: response = {'ok': True, 'message': 'no record",
"datetime import random import string @app.route('/users', methods=['GET']) def usersIndex(): data = list(mongo.db.users.find()) return",
"user.get('email', None) is not None: db_response = mongo.db.users.delete_one({'email': user['email']}) if db_response.deleted_count == 1:",
"data = list(mongo.db.users.find()) return jsonify({'result': data}), 200 @app.route('/users', methods=['POST']) def usersCreate(): user =",
"= now mongo.db.users.insert_one(user) return jsonify({'ok': True, 'message': 'User created successfully!', 'user': user}), 200",
"== 1: response = {'ok': True, 'message': 'record deleted'} else: response = {'ok':",
"@app.route('/users', methods=['POST']) def usersCreate(): user = request.get_json() if user.get('name', None) is not None",
"return jsonify(response), 200 else: return jsonify({'ok': False, 'message': 'Bad request parameters!'}), 400 def",
"= datetime.datetime.now() user['token'] = <PASSWORD>() user['created_at'] = now user['updated_at'] = now mongo.db.users.insert_one(user) return",
"os from flask import request, jsonify from app import app, mongo import datetime",
"is not None and user.get('email', None) is not None: now = datetime.datetime.now() user['token']",
"else: return jsonify({'ok': False, 'message': 'Bad request parameters!'}), 400 @app.route('/users', methods=['DELETE']) def usersDelete():",
"import string @app.route('/users', methods=['GET']) def usersIndex(): data = list(mongo.db.users.find()) return jsonify({'result': data}), 200",
"@app.route('/users', methods=['DELETE']) def usersDelete(): user = request.get_json() if user.get('email', None) is not None:",
"'record deleted'} else: response = {'ok': True, 'message': 'no record found'} return jsonify(response),",
"def usersIndex(): data = list(mongo.db.users.find()) return jsonify({'result': data}), 200 @app.route('/users', methods=['POST']) def usersCreate():",
"request parameters!'}), 400 def randomString(stringLength=50): \"\"\"Generate a random string of fixed length \"\"\"",
"usersCreate(): user = request.get_json() if user.get('name', None) is not None and user.get('email', None)",
"from app import app, mongo import datetime import random import string @app.route('/users', methods=['GET'])",
"False, 'message': 'Bad request parameters!'}), 400 def randomString(stringLength=50): \"\"\"Generate a random string of",
"user = request.get_json() if user.get('email', None) is not None: db_response = mongo.db.users.delete_one({'email': user['email']})",
"randomString(stringLength=50): \"\"\"Generate a random string of fixed length \"\"\" letters = string.ascii_lowercase return",
"jsonify({'ok': False, 'message': 'Bad request parameters!'}), 400 def randomString(stringLength=50): \"\"\"Generate a random string",
"app import app, mongo import datetime import random import string @app.route('/users', methods=['GET']) def",
"return jsonify({'result': data}), 200 @app.route('/users', methods=['POST']) def usersCreate(): user = request.get_json() if user.get('name',",
"None: db_response = mongo.db.users.delete_one({'email': user['email']}) if db_response.deleted_count == 1: response = {'ok': True,",
"if user.get('name', None) is not None and user.get('email', None) is not None: now",
"'Bad request parameters!'}), 400 def randomString(stringLength=50): \"\"\"Generate a random string of fixed length",
"= mongo.db.users.delete_one({'email': user['email']}) if db_response.deleted_count == 1: response = {'ok': True, 'message': 'record",
"<filename>notification-api/modules/app/controllers/user.py import os from flask import request, jsonify from app import app, mongo"
] |
[
"if not conf.get(\"general\", \"import\") == \"\": conf3 = ExtendedConfigParser() conf3.read(conf.get(\"general\", \"import\")) conf.merge(conf3) conf.filename",
"in defaults # If new option found, warn and ignore it def warn_opt(section,",
"\"\": return None else: return tuple(datetime.datetime.strptime(e.strip(), \"%Y-%m-%d %H:%M:%S\") for e in ret.split(\",\")) def",
"return [] def get_value(self, group): if self.gdict.has_key(group): return self.gdict[group] else: return [] def",
"for option in conf.options(section): if not self.has_option(section, option): value = conf.get(section, option) self.set(section,",
"= conf.get(section, option) if not option in self.options(section): if warn: warn_opt(section, option, conf.filename)",
"self.get(section, name) if ret == \"\": return None else: return datetime.datetime.strptime(ret.strip(), \"%Y-%m-%d %H:%M:%S\")",
"\"import\")) conf.merge(conf3) conf.filename = fn return conf # common objects for logging def",
"group is None: raise ValueError(\"no group definition before value\") val = line self.gdict.setdefault(group,",
"str2dur(string): \"\"\" Note: \\d+s: \\d seconds \\d+m: \\d minutes \\d+h: \\d hours \\d+d:",
"\"\": pass else: self.open_def(fn) def open_def(self, fn): group = None with open(fn, 'r')",
"in conf.options(section): if not self.has_option(section, option): value = conf.get(section, option) self.set(section, option, value)",
"hours \\d+d: \\d days \\d+w: \\d * 7 days \"\"\" if \"s\" in",
"lv = logging.INFO): fn = conf.get(\"general\", \"info_log\") fmt = logging.Formatter( fmt = \"%(asctime)s",
"= ExtendedConfigParser() conf2.read(fn) conf.update(conf2, warn = True) if conf.has_section(\"general\"): if conf.has_option(\"general\", \"import\"): if",
"self.get(section, name) return tuple(e.strip() for e in ret.split(\",\") if not e.strip() == \"\")",
"self.sections(): self.add_section(section) if warn: warn_sec(section, conf.filename) for option in conf.options(section): value = conf.get(section,",
"getterm(self, section, name): ret = self.get(section, name) if ret == \"\": return None",
"line self.gdict.setdefault(group, []).append(val) self.rgdict.setdefault(val, []).append(group) def setdefault(self, group): self.default = group def groups(self):",
"description after # in a line will be recognized as comment line \"[GROUP_NAME]\"",
"return None else: return datetime.datetime.strptime(ret.strip(), \"%Y-%m-%d %H:%M:%S\") def getterm(self, section, name): ret =",
"it def warn_opt(section, option, fn): _logger.warning(\"\"\" Invalid option name {0} in section {1}",
"open_def(self, fn): group = None with open(fn, 'r') as f: for line in",
"# common objects for logging def set_common_logging(conf, logger = None, l_logger_name = [],",
"return None else: return [e.strip() for e in ret.split(\",\") if not e.strip() ==",
"values(self): return self.rgdict.keys() def ingroup(self, group, val): if self.rgdict(val): return val in self.rgdict[val]",
"\\d+w: \\d * 7 days \"\"\" if \"s\" in string: num = int(string.partition(\"s\")[0])",
"def get_group(self, val): if self.rgdict.has_key(val): return self.rgdict[val] else: return [] def get_value(self, group):",
"found\".format(fn)) else: self.filename = fn return super(ExtendedConfigParser, self).read(fn) def update(self, conf, warn =",
"conf, warn = False): # Update existing configurations in defaults # If new",
"conf = ExtendedConfigParser() conf.read(DEFAULT_CONFIG_NAME) if fn is not None: conf2 = ExtendedConfigParser() conf2.read(fn)",
"fn): group = None with open(fn, 'r') as f: for line in f:",
"conf.filename) for option in conf.options(section): value = conf.get(section, option) if not option in",
"ch.setLevel(lv) if logger is not None: logger.setLevel(lv) logger.addHandler(ch) for ln in l_logger_name: temp",
"GROUP_NAME line \"\"\" def __init__(self, fn, default_val = None): self.gdict = {} self.rgdict",
"group, l_val in self.gdict.iteritems(): for val in l_val: yield group, val def str2dur(string):",
"IOError(\"{0} not found\".format(fn)) else: self.filename = fn return super(ExtendedConfigParser, self).read(fn) def update(self, conf,",
"= conf.get(\"general\", \"info_log\") fmt = logging.Formatter( fmt = \"%(asctime)s %(levelname)s (%(processName)s) %(message)s\", datefmt",
"\"h\" in string: num = int(string.partition(\"h\")[0]) return datetime.timedelta(hours = num) elif \"d\" in",
"datetime.timedelta(minutes = num) elif \"h\" in string: num = int(string.partition(\"h\")[0]) return datetime.timedelta(hours =",
"\"\": continue elif line[0] == \"#\": continue elif line[0] == \"[\" and line[-1]",
"= None): conf = ExtendedConfigParser() conf.read(DEFAULT_CONFIG_NAME) if fn is not None: conf2 =",
"True) if conf.has_section(\"general\"): if conf.has_option(\"general\", \"import\"): if not conf.get(\"general\", \"import\") == \"\": conf3",
"section in conf.sections(): print \"[{0}]\".format(section) for option, value in conf.items(section): print \"{0} =",
"\"%Y-%m-%d %H:%M:%S\") def getterm(self, section, name): ret = self.get(section, name) if ret ==",
"group = None with open(fn, 'r') as f: for line in f: #",
"\"import\") == \"\": conf3 = ExtendedConfigParser() conf3.read(conf.get(\"general\", \"import\")) conf.merge(conf3) conf.filename = fn return",
"ValueError(\"no group definition before value\") val = line self.gdict.setdefault(group, []).append(val) self.rgdict.setdefault(val, []).append(group) def",
"\"]\": group = line[1:].strip(\"[]\") else: if group is None: raise ValueError(\"no group definition",
"warn_opt(section, option, conf.filename) self.set(section, option, value) return self def merge(self, conf): # Do",
"is not None: logger.setLevel(lv) logger.addHandler(ch) for ln in l_logger_name: temp = logging.getLogger(ln) temp.setLevel(lv)",
"None else: return tuple(datetime.datetime.strptime(e.strip(), \"%Y-%m-%d %H:%M:%S\") for e in ret.split(\",\")) def getdur(self, section,",
"in section {1} in {2}, ignored \"\"\".strip().format(option, section, fn)) def warn_sec(section, fn): _logger.warning(\"Invalid",
"name): ret = self.get(section, name) if ret == \"\": return None else: return",
"None or fn == \"\": pass else: self.open_def(fn) def open_def(self, fn): group =",
"not None: conf2 = ExtendedConfigParser() conf2.read(fn) conf.update(conf2, warn = True) if conf.has_section(\"general\"): if",
"section, fn)) def warn_sec(section, fn): _logger.warning(\"Invalid section name {0} in {1}\".format( section, fn))",
"\"w\" in string: num = int(string.partition(\"w\")[0]) return datetime.timedelta(days = num * 7) else:",
"self.filename = fn return super(ExtendedConfigParser, self).read(fn) def update(self, conf, warn = False): #",
"= None): if logger is not None: logger.removeHandler(ch) if l_logger_name is not None:",
"defaults for section in conf.sections(): if not section in self.sections(): self.add_section(section) for option",
"for e in ret.split(\",\") if not e.strip() == \"\") def getlist(self, section, name):",
"\\d+m: \\d minutes \\d+h: \\d hours \\d+d: \\d days \\d+w: \\d * 7",
"= logging.INFO): fn = conf.get(\"general\", \"info_log\") fmt = logging.Formatter( fmt = \"%(asctime)s %(levelname)s",
"conf # common objects for logging def set_common_logging(conf, logger = None, l_logger_name =",
"ret.split(\",\")) def getdur(self, section, name): ret = self.get(section, name) if ret == \"\":",
"for e in ret.split(\",\") if not e.strip() == \"\"] def getdt(self, section, name):",
"# If new option found, warn and ignore it def warn_opt(section, option, fn):",
"warn: warn_sec(section, conf.filename) for option in conf.options(section): value = conf.get(section, option) if not",
"self.has_option(section, option): value = conf.get(section, option) self.set(section, option, value) return self def gettuple(self,",
"\"\"\" Note: \\d+s: \\d seconds \\d+m: \\d minutes \\d+h: \\d hours \\d+d: \\d",
"__init__(self): #super(ExtendedConfigParser, self).__init__(self) ConfigParser.SafeConfigParser.__init__(self) self.filename = None # source filename def read(self, fn):",
"self.get(section, name) if ret == \"\": return None else: return tuple(datetime.datetime.strptime(e.strip(), \"%Y-%m-%d %H:%M:%S\")",
"Note: \\d+s: \\d seconds \\d+m: \\d minutes \\d+h: \\d hours \\d+d: \\d days",
"else: ch = logging.FileHandler(fn) ch.setFormatter(fmt) ch.setLevel(lv) if logger is not None: logger.setLevel(lv) logger.addHandler(ch)",
"else: self.open_def(fn) def open_def(self, fn): group = None with open(fn, 'r') as f:",
"if logger is not None: logger.removeHandler(ch) if l_logger_name is not None: for ln",
"[] def get_value(self, group): if self.gdict.has_key(group): return self.gdict[group] else: return [] def iter_def(self):",
"option, conf.filename) self.set(section, option, value) return self def merge(self, conf): # Do NOT",
"by external text Rules: description after # in a line will be recognized",
"return self.gdict[group] else: return [] def iter_def(self): for group, l_val in self.gdict.iteritems(): for",
"self.gdict.setdefault(group, []).append(val) self.rgdict.setdefault(val, []).append(group) def setdefault(self, group): self.default = group def groups(self): return",
"ValueError(\"Duration string invalid\") def open_config(fn = None): conf = ExtendedConfigParser() conf.read(DEFAULT_CONFIG_NAME) if fn",
"fn)) for section in conf.sections(): if not section in self.sections(): self.add_section(section) if warn:",
"not section in self.sections(): self.add_section(section) if warn: warn_sec(section, conf.filename) for option in conf.options(section):",
"string invalid\") def open_config(fn = None): conf = ExtendedConfigParser() conf.read(DEFAULT_CONFIG_NAME) if fn is",
"section in self.sections(): self.add_section(section) for option in conf.options(section): if not self.has_option(section, option): value",
"ingroup(self, group, val): if self.rgdict(val): return val in self.rgdict[val] else: return False def",
"print \"{0} = {1}\".format(option, value) if __name__ == \"__main__\": ## import old config,",
"is not None: conf2 = ExtendedConfigParser() conf2.read(fn) conf.update(conf2, warn = True) if conf.has_section(\"general\"):",
"fn is not None: conf2 = ExtendedConfigParser() conf2.read(fn) conf.update(conf2, warn = True) if",
"self.get(section, name) if ret == \"\": return None else: return [e.strip() for e",
"logging.StreamHandler() _ch.setLevel(logging.WARNING) _logger.setLevel(logging.WARNING) _logger.addHandler(_ch) class ExtendedConfigParser(ConfigParser.SafeConfigParser, object): def __init__(self): #super(ExtendedConfigParser, self).__init__(self) ConfigParser.SafeConfigParser.__init__(self) self.filename",
"is not None: logger.removeHandler(ch) if l_logger_name is not None: for ln in l_logger_name:",
"string: num = int(string.partition(\"w\")[0]) return datetime.timedelta(days = num * 7) else: raise ValueError(\"Duration",
"num = int(string.partition(\"h\")[0]) return datetime.timedelta(hours = num) elif \"d\" in string: num =",
"temp.setLevel(lv) temp.addHandler(ch) return ch def release_common_logging(ch, logger = None, l_logger_name = None): if",
"= num) elif \"d\" in string: num = int(string.partition(\"d\")[0]) return datetime.timedelta(days = num)",
"object): def __init__(self): #super(ExtendedConfigParser, self).__init__(self) ConfigParser.SafeConfigParser.__init__(self) self.filename = None # source filename def",
"self.set(section, option, value) return self def gettuple(self, section, name): ret = self.get(section, name)",
"os import datetime import logging import collections import ConfigParser DEFAULT_CONFIG_NAME = \"/\".join((os.path.dirname(__file__), \"config.conf.default\"))",
"will change group to set other lines add elements in the group set",
"#!/usr/bin/env python # coding: utf-8 import sys import os import datetime import logging",
"= None # source filename def read(self, fn): if not os.path.exists(fn): raise IOError(\"{0}",
"new default config, and output if len(sys.argv) < 2: sys.exit(\"usage : {0} config\".format(sys.argv[0]))",
"ret.split(\",\") if not e.strip() == \"\") def getlist(self, section, name): ret = self.get(section,",
"other lines add elements in the group set with GROUP_NAME line \"\"\" def",
"= None): self.gdict = {} self.rgdict = {} self.default = default_val if fn",
"%H:%M:%S\") #lv = logging.INFO if fn == \"\": ch = logging.StreamHandler() else: ch",
"option) self.set(section, option, value) return self def gettuple(self, section, name): ret = self.get(section,",
"int(string.partition(\"h\")[0]) return datetime.timedelta(hours = num) elif \"d\" in string: num = int(string.partition(\"d\")[0]) return",
"logging import collections import ConfigParser DEFAULT_CONFIG_NAME = \"/\".join((os.path.dirname(__file__), \"config.conf.default\")) LOGGER_NAME = __name__.rpartition(\".\")[-1] _logger",
"_logger.setLevel(logging.WARNING) _logger.addHandler(_ch) class ExtendedConfigParser(ConfigParser.SafeConfigParser, object): def __init__(self): #super(ExtendedConfigParser, self).__init__(self) ConfigParser.SafeConfigParser.__init__(self) self.filename = None",
"if group is None: raise ValueError(\"no group definition before value\") val = line",
"before value\") val = line self.gdict.setdefault(group, []).append(val) self.rgdict.setdefault(val, []).append(group) def setdefault(self, group): self.default",
"return None else: return str2dur(ret) class GroupDef(): \"\"\" Define grouping by external text",
"None: conf2 = ExtendedConfigParser() conf2.read(fn) conf.update(conf2, warn = True) if conf.has_section(\"general\"): if conf.has_option(\"general\",",
"fn = conf.get(\"general\", \"info_log\") fmt = logging.Formatter( fmt = \"%(asctime)s %(levelname)s (%(processName)s) %(message)s\",",
"with GROUP_NAME line \"\"\" def __init__(self, fn, default_val = None): self.gdict = {}",
"continue elif line[0] == \"[\" and line[-1] == \"]\": group = line[1:].strip(\"[]\") else:",
"in conf.sections(): if not section in self.sections(): self.add_section(section) if warn: warn_sec(section, conf.filename) for",
"val in self.rgdict[val] else: return False def get_group(self, val): if self.rgdict.has_key(val): return self.rgdict[val]",
"sys import os import datetime import logging import collections import ConfigParser DEFAULT_CONFIG_NAME =",
"int(string.partition(\"w\")[0]) return datetime.timedelta(days = num * 7) else: raise ValueError(\"Duration string invalid\") def",
"value) if __name__ == \"__main__\": ## import old config, merge it with new",
"filename def read(self, fn): if not os.path.exists(fn): raise IOError(\"{0} not found\".format(fn)) else: self.filename",
"return datetime.timedelta(hours = num) elif \"d\" in string: num = int(string.partition(\"d\")[0]) return datetime.timedelta(days",
"warn_sec(section, fn): _logger.warning(\"Invalid section name {0} in {1}\".format( section, fn)) for section in",
"e.strip() == \"\"] def getdt(self, section, name): ret = self.get(section, name) if ret",
"== \"\": ch = logging.StreamHandler() else: ch = logging.FileHandler(fn) ch.setFormatter(fmt) ch.setLevel(lv) if logger",
"logging.INFO): fn = conf.get(\"general\", \"info_log\") fmt = logging.Formatter( fmt = \"%(asctime)s %(levelname)s (%(processName)s)",
"value in conf.items(section): print \"{0} = {1}\".format(option, value) if __name__ == \"__main__\": ##",
"if not e.strip() == \"\"] def getdt(self, section, name): ret = self.get(section, name)",
"objects for logging def set_common_logging(conf, logger = None, l_logger_name = [], lv =",
"raise ValueError(\"Duration string invalid\") def open_config(fn = None): conf = ExtendedConfigParser() conf.read(DEFAULT_CONFIG_NAME) if",
"ln in l_logger_name: temp = logging.getLogger(ln) temp.setLevel(lv) temp.addHandler(ch) return ch def release_common_logging(ch, logger",
"ExtendedConfigParser() conf3.read(conf.get(\"general\", \"import\")) conf.merge(conf3) conf.filename = fn return conf # common objects for",
"< 2: sys.exit(\"usage : {0} config\".format(sys.argv[0])) #default_conf = DEFAULT_CONFIG_NAME conf = sys.argv[1] test_config(conf)",
"else: return [] def iter_def(self): for group, l_val in self.gdict.iteritems(): for val in",
"in {1}\".format( section, fn)) for section in conf.sections(): if not section in self.sections():",
"in string: num = int(string.partition(\"d\")[0]) return datetime.timedelta(days = num) elif \"w\" in string:",
"self.open_def(fn) def open_def(self, fn): group = None with open(fn, 'r') as f: for",
"e.strip() == \"\") def getlist(self, section, name): ret = self.get(section, name) if ret",
"ret == \"\": return None else: return datetime.datetime.strptime(ret.strip(), \"%Y-%m-%d %H:%M:%S\") def getterm(self, section,",
"elements in the group set with GROUP_NAME line \"\"\" def __init__(self, fn, default_val",
"import os import datetime import logging import collections import ConfigParser DEFAULT_CONFIG_NAME = \"/\".join((os.path.dirname(__file__),",
"fn return super(ExtendedConfigParser, self).read(fn) def update(self, conf, warn = False): # Update existing",
"if fn is not None: conf2 = ExtendedConfigParser() conf2.read(fn) conf.update(conf2, warn = True)",
"conf.get(\"general\", \"import\") == \"\": conf3 = ExtendedConfigParser() conf3.read(conf.get(\"general\", \"import\")) conf.merge(conf3) conf.filename = fn",
"ConfigParser.SafeConfigParser.__init__(self) self.filename = None # source filename def read(self, fn): if not os.path.exists(fn):",
"release_common_logging(ch, logger = None, l_logger_name = None): if logger is not None: logger.removeHandler(ch)",
"l_logger_name is not None: for ln in l_logger_name: temp = logging.getLogger(ln) temp.removeHandler(ch) def",
"val): if self.rgdict.has_key(val): return self.rgdict[val] else: return [] def get_value(self, group): if self.gdict.has_key(group):",
"'r') as f: for line in f: # ignore after comment sygnal line",
"set with GROUP_NAME line \"\"\" def __init__(self, fn, default_val = None): self.gdict =",
"common objects for logging def set_common_logging(conf, logger = None, l_logger_name = [], lv",
"l_logger_name: temp = logging.getLogger(ln) temp.setLevel(lv) temp.addHandler(ch) return ch def release_common_logging(ch, logger = None,",
"self.add_section(section) if warn: warn_sec(section, conf.filename) for option in conf.options(section): value = conf.get(section, option)",
": {0} config\".format(sys.argv[0])) #default_conf = DEFAULT_CONFIG_NAME conf = sys.argv[1] test_config(conf) #output = sys.argv[2]",
"if line == \"\": continue elif line[0] == \"#\": continue elif line[0] ==",
"\"%(asctime)s %(levelname)s (%(processName)s) %(message)s\", datefmt = \"%Y-%m-%d %H:%M:%S\") #lv = logging.INFO if fn",
"set_common_logging(conf, logger = None, l_logger_name = [], lv = logging.INFO): fn = conf.get(\"general\",",
"default_val = None): self.gdict = {} self.rgdict = {} self.default = default_val if",
"num = int(string.partition(\"s\")[0]) return datetime.timedelta(seconds = num) elif \"m\" in string: num =",
"def open_def(self, fn): group = None with open(fn, 'r') as f: for line",
"2: sys.exit(\"usage : {0} config\".format(sys.argv[0])) #default_conf = DEFAULT_CONFIG_NAME conf = sys.argv[1] test_config(conf) #output",
"for group, l_val in self.gdict.iteritems(): for val in l_val: yield group, val def",
"change group to set other lines add elements in the group set with",
"== \"\": return None else: return datetime.datetime.strptime(ret.strip(), \"%Y-%m-%d %H:%M:%S\") def getterm(self, section, name):",
"# Update existing configurations in defaults # If new option found, warn and",
"in self.sections(): self.add_section(section) if warn: warn_sec(section, conf.filename) for option in conf.options(section): value =",
"num) elif \"d\" in string: num = int(string.partition(\"d\")[0]) return datetime.timedelta(days = num) elif",
"return self def gettuple(self, section, name): ret = self.get(section, name) return tuple(e.strip() for",
"ch = logging.FileHandler(fn) ch.setFormatter(fmt) ch.setLevel(lv) if logger is not None: logger.setLevel(lv) logger.addHandler(ch) for",
"_logger = logging.getLogger(LOGGER_NAME) _ch = logging.StreamHandler() _ch.setLevel(logging.WARNING) _logger.setLevel(logging.WARNING) _logger.addHandler(_ch) class ExtendedConfigParser(ConfigParser.SafeConfigParser, object): def",
"== \"#\": continue elif line[0] == \"[\" and line[-1] == \"]\": group =",
"output if len(sys.argv) < 2: sys.exit(\"usage : {0} config\".format(sys.argv[0])) #default_conf = DEFAULT_CONFIG_NAME conf",
"setdefault(self, group): self.default = group def groups(self): return self.gdict.keys() def values(self): return self.rgdict.keys()",
"{} self.default = default_val if fn is None or fn == \"\": pass",
"if self.rgdict.has_key(val): return self.rgdict[val] else: return [] def get_value(self, group): if self.gdict.has_key(group): return",
"fn)) def warn_sec(section, fn): _logger.warning(\"Invalid section name {0} in {1}\".format( section, fn)) for",
"sys.exit(\"usage : {0} config\".format(sys.argv[0])) #default_conf = DEFAULT_CONFIG_NAME conf = sys.argv[1] test_config(conf) #output =",
"value) return self def gettuple(self, section, name): ret = self.get(section, name) return tuple(e.strip()",
"section in conf.sections(): if not section in self.sections(): self.add_section(section) if warn: warn_sec(section, conf.filename)",
"in ret.split(\",\")) def getdur(self, section, name): ret = self.get(section, name) if ret ==",
"if warn: warn_sec(section, conf.filename) for option in conf.options(section): value = conf.get(section, option) if",
"return str2dur(ret) class GroupDef(): \"\"\" Define grouping by external text Rules: description after",
"will be recognized as comment line \"[GROUP_NAME]\" will change group to set other",
"return datetime.timedelta(minutes = num) elif \"h\" in string: num = int(string.partition(\"h\")[0]) return datetime.timedelta(hours",
"= fn return super(ExtendedConfigParser, self).read(fn) def update(self, conf, warn = False): # Update",
"in l_val: yield group, val def str2dur(string): \"\"\" Note: \\d+s: \\d seconds \\d+m:",
"minutes \\d+h: \\d hours \\d+d: \\d days \\d+w: \\d * 7 days \"\"\"",
"== \"\": return None else: return str2dur(ret) class GroupDef(): \"\"\" Define grouping by",
"int(string.partition(\"m\")[0]) return datetime.timedelta(minutes = num) elif \"h\" in string: num = int(string.partition(\"h\")[0]) return",
"= int(string.partition(\"m\")[0]) return datetime.timedelta(minutes = num) elif \"h\" in string: num = int(string.partition(\"h\")[0])",
"comment line \"[GROUP_NAME]\" will change group to set other lines add elements in",
"= logging.StreamHandler() else: ch = logging.FileHandler(fn) ch.setFormatter(fmt) ch.setLevel(lv) if logger is not None:",
"self.set(section, option, value) return self def merge(self, conf): # Do NOT allow updateing",
"not section in self.sections(): self.add_section(section) for option in conf.options(section): if not self.has_option(section, option):",
"in string: num = int(string.partition(\"h\")[0]) return datetime.timedelta(hours = num) elif \"d\" in string:",
"if self.rgdict(val): return val in self.rgdict[val] else: return False def get_group(self, val): if",
"string: num = int(string.partition(\"h\")[0]) return datetime.timedelta(hours = num) elif \"d\" in string: num",
"self.default = group def groups(self): return self.gdict.keys() def values(self): return self.rgdict.keys() def ingroup(self,",
"def merge(self, conf): # Do NOT allow updateing existing options in defaults for",
"= logging.getLogger(ln) temp.removeHandler(ch) def test_config(conf_name): conf = open_config(conf_name) for section in conf.sections(): print",
"ExtendedConfigParser(ConfigParser.SafeConfigParser, object): def __init__(self): #super(ExtendedConfigParser, self).__init__(self) ConfigParser.SafeConfigParser.__init__(self) self.filename = None # source filename",
"gettuple(self, section, name): ret = self.get(section, name) return tuple(e.strip() for e in ret.split(\",\")",
"\"\": return None else: return str2dur(ret) class GroupDef(): \"\"\" Define grouping by external",
"group, val def str2dur(string): \"\"\" Note: \\d+s: \\d seconds \\d+m: \\d minutes \\d+h:",
"not conf.get(\"general\", \"import\") == \"\": conf3 = ExtendedConfigParser() conf3.read(conf.get(\"general\", \"import\")) conf.merge(conf3) conf.filename =",
"ignore it def warn_opt(section, option, fn): _logger.warning(\"\"\" Invalid option name {0} in section",
"print \"[{0}]\".format(section) for option, value in conf.items(section): print \"{0} = {1}\".format(option, value) if",
"if __name__ == \"__main__\": ## import old config, merge it with new default",
"for e in ret.split(\",\")) def getdur(self, section, name): ret = self.get(section, name) if",
"if len(sys.argv) < 2: sys.exit(\"usage : {0} config\".format(sys.argv[0])) #default_conf = DEFAULT_CONFIG_NAME conf =",
"\\d+s: \\d seconds \\d+m: \\d minutes \\d+h: \\d hours \\d+d: \\d days \\d+w:",
"add elements in the group set with GROUP_NAME line \"\"\" def __init__(self, fn,",
"else: return datetime.datetime.strptime(ret.strip(), \"%Y-%m-%d %H:%M:%S\") def getterm(self, section, name): ret = self.get(section, name)",
"tuple(e.strip() for e in ret.split(\",\") if not e.strip() == \"\") def getlist(self, section,",
"Do NOT allow updateing existing options in defaults for section in conf.sections(): if",
"f: for line in f: # ignore after comment sygnal line = line.strip().partition(\"#\")[0]",
"line[0] == \"[\" and line[-1] == \"]\": group = line[1:].strip(\"[]\") else: if group",
"configurations in defaults # If new option found, warn and ignore it def",
"self).read(fn) def update(self, conf, warn = False): # Update existing configurations in defaults",
"self.rgdict = {} self.default = default_val if fn is None or fn ==",
"= self.get(section, name) if ret == \"\": return None else: return tuple(datetime.datetime.strptime(e.strip(), \"%Y-%m-%d",
"\"s\" in string: num = int(string.partition(\"s\")[0]) return datetime.timedelta(seconds = num) elif \"m\" in",
"\"config.conf.default\")) LOGGER_NAME = __name__.rpartition(\".\")[-1] _logger = logging.getLogger(LOGGER_NAME) _ch = logging.StreamHandler() _ch.setLevel(logging.WARNING) _logger.setLevel(logging.WARNING) _logger.addHandler(_ch)",
"= logging.Formatter( fmt = \"%(asctime)s %(levelname)s (%(processName)s) %(message)s\", datefmt = \"%Y-%m-%d %H:%M:%S\") #lv",
"utf-8 import sys import os import datetime import logging import collections import ConfigParser",
"def iter_def(self): for group, l_val in self.gdict.iteritems(): for val in l_val: yield group,",
"or fn == \"\": pass else: self.open_def(fn) def open_def(self, fn): group = None",
"elif line[0] == \"#\": continue elif line[0] == \"[\" and line[-1] == \"]\":",
"import datetime import logging import collections import ConfigParser DEFAULT_CONFIG_NAME = \"/\".join((os.path.dirname(__file__), \"config.conf.default\")) LOGGER_NAME",
"it with new default config, and output if len(sys.argv) < 2: sys.exit(\"usage :",
"read(self, fn): if not os.path.exists(fn): raise IOError(\"{0} not found\".format(fn)) else: self.filename = fn",
"fn, default_val = None): self.gdict = {} self.rgdict = {} self.default = default_val",
"conf.filename) self.set(section, option, value) return self def merge(self, conf): # Do NOT allow",
"option, fn): _logger.warning(\"\"\" Invalid option name {0} in section {1} in {2}, ignored",
"Define grouping by external text Rules: description after # in a line will",
"l_logger_name: temp = logging.getLogger(ln) temp.removeHandler(ch) def test_config(conf_name): conf = open_config(conf_name) for section in",
"logger = None, l_logger_name = None): if logger is not None: logger.removeHandler(ch) if",
"existing options in defaults for section in conf.sections(): if not section in self.sections():",
"else: return False def get_group(self, val): if self.rgdict.has_key(val): return self.rgdict[val] else: return []",
"logging.getLogger(ln) temp.setLevel(lv) temp.addHandler(ch) return ch def release_common_logging(ch, logger = None, l_logger_name = None):",
"for ln in l_logger_name: temp = logging.getLogger(ln) temp.removeHandler(ch) def test_config(conf_name): conf = open_config(conf_name)",
"in defaults for section in conf.sections(): if not section in self.sections(): self.add_section(section) for",
"iter_def(self): for group, l_val in self.gdict.iteritems(): for val in l_val: yield group, val",
"else: raise ValueError(\"Duration string invalid\") def open_config(fn = None): conf = ExtendedConfigParser() conf.read(DEFAULT_CONFIG_NAME)",
"NOT allow updateing existing options in defaults for section in conf.sections(): if not",
"num = int(string.partition(\"m\")[0]) return datetime.timedelta(minutes = num) elif \"h\" in string: num =",
"invalid\") def open_config(fn = None): conf = ExtendedConfigParser() conf.read(DEFAULT_CONFIG_NAME) if fn is not",
"grouping by external text Rules: description after # in a line will be",
"merge it with new default config, and output if len(sys.argv) < 2: sys.exit(\"usage",
"import old config, merge it with new default config, and output if len(sys.argv)",
"fn is None or fn == \"\": pass else: self.open_def(fn) def open_def(self, fn):",
"[]).append(group) def setdefault(self, group): self.default = group def groups(self): return self.gdict.keys() def values(self):",
"def getdt(self, section, name): ret = self.get(section, name) if ret == \"\": return",
"else: self.filename = fn return super(ExtendedConfigParser, self).read(fn) def update(self, conf, warn = False):",
"new option found, warn and ignore it def warn_opt(section, option, fn): _logger.warning(\"\"\" Invalid",
"is None: raise ValueError(\"no group definition before value\") val = line self.gdict.setdefault(group, []).append(val)",
"= default_val if fn is None or fn == \"\": pass else: self.open_def(fn)",
"None # source filename def read(self, fn): if not os.path.exists(fn): raise IOError(\"{0} not",
"option in conf.options(section): value = conf.get(section, option) if not option in self.options(section): if",
"in self.options(section): if warn: warn_opt(section, option, conf.filename) self.set(section, option, value) return self def",
"datetime.timedelta(days = num) elif \"w\" in string: num = int(string.partition(\"w\")[0]) return datetime.timedelta(days =",
"num * 7) else: raise ValueError(\"Duration string invalid\") def open_config(fn = None): conf",
"None else: return str2dur(ret) class GroupDef(): \"\"\" Define grouping by external text Rules:",
"not self.has_option(section, option): value = conf.get(section, option) self.set(section, option, value) return self def",
"def warn_opt(section, option, fn): _logger.warning(\"\"\" Invalid option name {0} in section {1} in",
"__name__ == \"__main__\": ## import old config, merge it with new default config,",
"ret = self.get(section, name) if ret == \"\": return None else: return tuple(datetime.datetime.strptime(e.strip(),",
"if fn == \"\": ch = logging.StreamHandler() else: ch = logging.FileHandler(fn) ch.setFormatter(fmt) ch.setLevel(lv)",
"if not section in self.sections(): self.add_section(section) for option in conf.options(section): if not self.has_option(section,",
"conf3.read(conf.get(\"general\", \"import\")) conf.merge(conf3) conf.filename = fn return conf # common objects for logging",
"line \"\"\" def __init__(self, fn, default_val = None): self.gdict = {} self.rgdict =",
"= [], lv = logging.INFO): fn = conf.get(\"general\", \"info_log\") fmt = logging.Formatter( fmt",
"None: for ln in l_logger_name: temp = logging.getLogger(ln) temp.removeHandler(ch) def test_config(conf_name): conf =",
"\\d * 7 days \"\"\" if \"s\" in string: num = int(string.partition(\"s\")[0]) return",
"None else: return datetime.datetime.strptime(ret.strip(), \"%Y-%m-%d %H:%M:%S\") def getterm(self, section, name): ret = self.get(section,",
"group = line[1:].strip(\"[]\") else: if group is None: raise ValueError(\"no group definition before",
"in string: num = int(string.partition(\"w\")[0]) return datetime.timedelta(days = num * 7) else: raise",
"as f: for line in f: # ignore after comment sygnal line =",
"open(fn, 'r') as f: for line in f: # ignore after comment sygnal",
"the group set with GROUP_NAME line \"\"\" def __init__(self, fn, default_val = None):",
"line will be recognized as comment line \"[GROUP_NAME]\" will change group to set",
"= None, l_logger_name = None): if logger is not None: logger.removeHandler(ch) if l_logger_name",
"logger is not None: logger.removeHandler(ch) if l_logger_name is not None: for ln in",
"return datetime.timedelta(days = num) elif \"w\" in string: num = int(string.partition(\"w\")[0]) return datetime.timedelta(days",
"str2dur(ret) class GroupDef(): \"\"\" Define grouping by external text Rules: description after #",
"def open_config(fn = None): conf = ExtendedConfigParser() conf.read(DEFAULT_CONFIG_NAME) if fn is not None:",
"collections import ConfigParser DEFAULT_CONFIG_NAME = \"/\".join((os.path.dirname(__file__), \"config.conf.default\")) LOGGER_NAME = __name__.rpartition(\".\")[-1] _logger = logging.getLogger(LOGGER_NAME)",
"updateing existing options in defaults for section in conf.sections(): if not section in",
"(%(processName)s) %(message)s\", datefmt = \"%Y-%m-%d %H:%M:%S\") #lv = logging.INFO if fn == \"\":",
"ret == \"\": return None else: return str2dur(ret) class GroupDef(): \"\"\" Define grouping",
"not e.strip() == \"\"] def getdt(self, section, name): ret = self.get(section, name) if",
"super(ExtendedConfigParser, self).read(fn) def update(self, conf, warn = False): # Update existing configurations in",
"= self.get(section, name) if ret == \"\": return None else: return [e.strip() for",
"{0} in section {1} in {2}, ignored \"\"\".strip().format(option, section, fn)) def warn_sec(section, fn):",
"= {} self.rgdict = {} self.default = default_val if fn is None or",
"return conf # common objects for logging def set_common_logging(conf, logger = None, l_logger_name",
"temp.removeHandler(ch) def test_config(conf_name): conf = open_config(conf_name) for section in conf.sections(): print \"[{0}]\".format(section) for",
"def __init__(self, fn, default_val = None): self.gdict = {} self.rgdict = {} self.default",
"{0} config\".format(sys.argv[0])) #default_conf = DEFAULT_CONFIG_NAME conf = sys.argv[1] test_config(conf) #output = sys.argv[2] #overwrite_config(default_conf,",
"num) elif \"h\" in string: num = int(string.partition(\"h\")[0]) return datetime.timedelta(hours = num) elif",
"def setdefault(self, group): self.default = group def groups(self): return self.gdict.keys() def values(self): return",
"self.rgdict.keys() def ingroup(self, group, val): if self.rgdict(val): return val in self.rgdict[val] else: return",
"== \"\": pass else: self.open_def(fn) def open_def(self, fn): group = None with open(fn,",
"self.sections(): self.add_section(section) for option in conf.options(section): if not self.has_option(section, option): value = conf.get(section,",
"ignore after comment sygnal line = line.strip().partition(\"#\")[0] if line == \"\": continue elif",
"ret = self.get(section, name) return tuple(e.strip() for e in ret.split(\",\") if not e.strip()",
"warn_opt(section, option, fn): _logger.warning(\"\"\" Invalid option name {0} in section {1} in {2},",
"datetime.timedelta(days = num * 7) else: raise ValueError(\"Duration string invalid\") def open_config(fn =",
"if not section in self.sections(): self.add_section(section) if warn: warn_sec(section, conf.filename) for option in",
"group to set other lines add elements in the group set with GROUP_NAME",
"num) elif \"w\" in string: num = int(string.partition(\"w\")[0]) return datetime.timedelta(days = num *",
"* 7) else: raise ValueError(\"Duration string invalid\") def open_config(fn = None): conf =",
"line \"[GROUP_NAME]\" will change group to set other lines add elements in the",
"name) if ret == \"\": return None else: return tuple(datetime.datetime.strptime(e.strip(), \"%Y-%m-%d %H:%M:%S\") for",
"class ExtendedConfigParser(ConfigParser.SafeConfigParser, object): def __init__(self): #super(ExtendedConfigParser, self).__init__(self) ConfigParser.SafeConfigParser.__init__(self) self.filename = None # source",
"= None, l_logger_name = [], lv = logging.INFO): fn = conf.get(\"general\", \"info_log\") fmt",
"if conf.has_section(\"general\"): if conf.has_option(\"general\", \"import\"): if not conf.get(\"general\", \"import\") == \"\": conf3 =",
"None with open(fn, 'r') as f: for line in f: # ignore after",
"Invalid option name {0} in section {1} in {2}, ignored \"\"\".strip().format(option, section, fn))",
"return datetime.timedelta(seconds = num) elif \"m\" in string: num = int(string.partition(\"m\")[0]) return datetime.timedelta(minutes",
"with open(fn, 'r') as f: for line in f: # ignore after comment",
"import logging import collections import ConfigParser DEFAULT_CONFIG_NAME = \"/\".join((os.path.dirname(__file__), \"config.conf.default\")) LOGGER_NAME = __name__.rpartition(\".\")[-1]",
"ret = self.get(section, name) if ret == \"\": return None else: return str2dur(ret)",
"value = conf.get(section, option) if not option in self.options(section): if warn: warn_opt(section, option,",
"warn: warn_opt(section, option, conf.filename) self.set(section, option, value) return self def merge(self, conf): #",
"value) return self def merge(self, conf): # Do NOT allow updateing existing options",
"= ExtendedConfigParser() conf3.read(conf.get(\"general\", \"import\")) conf.merge(conf3) conf.filename = fn return conf # common objects",
"config\".format(sys.argv[0])) #default_conf = DEFAULT_CONFIG_NAME conf = sys.argv[1] test_config(conf) #output = sys.argv[2] #overwrite_config(default_conf, conf,",
"= conf.get(section, option) self.set(section, option, value) return self def gettuple(self, section, name): ret",
"conf.update(conf2, warn = True) if conf.has_section(\"general\"): if conf.has_option(\"general\", \"import\"): if not conf.get(\"general\", \"import\")",
"conf.options(section): value = conf.get(section, option) if not option in self.options(section): if warn: warn_opt(section,",
"None): if logger is not None: logger.removeHandler(ch) if l_logger_name is not None: for",
"in conf.items(section): print \"{0} = {1}\".format(option, value) if __name__ == \"__main__\": ## import",
"\\d days \\d+w: \\d * 7 days \"\"\" if \"s\" in string: num",
"self def gettuple(self, section, name): ret = self.get(section, name) return tuple(e.strip() for e",
"def set_common_logging(conf, logger = None, l_logger_name = [], lv = logging.INFO): fn =",
"= self.get(section, name) return tuple(e.strip() for e in ret.split(\",\") if not e.strip() ==",
"Update existing configurations in defaults # If new option found, warn and ignore",
"text Rules: description after # in a line will be recognized as comment",
"elif \"d\" in string: num = int(string.partition(\"d\")[0]) return datetime.timedelta(days = num) elif \"w\"",
"ret = self.get(section, name) if ret == \"\": return None else: return [e.strip()",
"def update(self, conf, warn = False): # Update existing configurations in defaults #",
"for line in f: # ignore after comment sygnal line = line.strip().partition(\"#\")[0] if",
"7) else: raise ValueError(\"Duration string invalid\") def open_config(fn = None): conf = ExtendedConfigParser()",
"return [] def iter_def(self): for group, l_val in self.gdict.iteritems(): for val in l_val:",
"= ExtendedConfigParser() conf.read(DEFAULT_CONFIG_NAME) if fn is not None: conf2 = ExtendedConfigParser() conf2.read(fn) conf.update(conf2,",
"= logging.getLogger(ln) temp.setLevel(lv) temp.addHandler(ch) return ch def release_common_logging(ch, logger = None, l_logger_name =",
"group def groups(self): return self.gdict.keys() def values(self): return self.rgdict.keys() def ingroup(self, group, val):",
"= line[1:].strip(\"[]\") else: if group is None: raise ValueError(\"no group definition before value\")",
"self.rgdict(val): return val in self.rgdict[val] else: return False def get_group(self, val): if self.rgdict.has_key(val):",
"continue elif line[0] == \"#\": continue elif line[0] == \"[\" and line[-1] ==",
"in self.gdict.iteritems(): for val in l_val: yield group, val def str2dur(string): \"\"\" Note:",
"datefmt = \"%Y-%m-%d %H:%M:%S\") #lv = logging.INFO if fn == \"\": ch =",
"days \"\"\" if \"s\" in string: num = int(string.partition(\"s\")[0]) return datetime.timedelta(seconds = num)",
"self.filename = None # source filename def read(self, fn): if not os.path.exists(fn): raise",
"get_value(self, group): if self.gdict.has_key(group): return self.gdict[group] else: return [] def iter_def(self): for group,",
"def getdur(self, section, name): ret = self.get(section, name) if ret == \"\": return",
"definition before value\") val = line self.gdict.setdefault(group, []).append(val) self.rgdict.setdefault(val, []).append(group) def setdefault(self, group):",
"= True) if conf.has_section(\"general\"): if conf.has_option(\"general\", \"import\"): if not conf.get(\"general\", \"import\") == \"\":",
"== \"\": return None else: return tuple(datetime.datetime.strptime(e.strip(), \"%Y-%m-%d %H:%M:%S\") for e in ret.split(\",\"))",
"else: return tuple(datetime.datetime.strptime(e.strip(), \"%Y-%m-%d %H:%M:%S\") for e in ret.split(\",\")) def getdur(self, section, name):",
"self.gdict = {} self.rgdict = {} self.default = default_val if fn is None",
"ExtendedConfigParser() conf.read(DEFAULT_CONFIG_NAME) if fn is not None: conf2 = ExtendedConfigParser() conf2.read(fn) conf.update(conf2, warn",
"temp = logging.getLogger(ln) temp.setLevel(lv) temp.addHandler(ch) return ch def release_common_logging(ch, logger = None, l_logger_name",
"fn): _logger.warning(\"\"\" Invalid option name {0} in section {1} in {2}, ignored \"\"\".strip().format(option,",
"= \"%Y-%m-%d %H:%M:%S\") #lv = logging.INFO if fn == \"\": ch = logging.StreamHandler()",
"allow updateing existing options in defaults for section in conf.sections(): if not section",
"pass else: self.open_def(fn) def open_def(self, fn): group = None with open(fn, 'r') as",
"line[0] == \"#\": continue elif line[0] == \"[\" and line[-1] == \"]\": group",
"logger.setLevel(lv) logger.addHandler(ch) for ln in l_logger_name: temp = logging.getLogger(ln) temp.setLevel(lv) temp.addHandler(ch) return ch",
"not os.path.exists(fn): raise IOError(\"{0} not found\".format(fn)) else: self.filename = fn return super(ExtendedConfigParser, self).read(fn)",
"False): # Update existing configurations in defaults # If new option found, warn",
"_logger.addHandler(_ch) class ExtendedConfigParser(ConfigParser.SafeConfigParser, object): def __init__(self): #super(ExtendedConfigParser, self).__init__(self) ConfigParser.SafeConfigParser.__init__(self) self.filename = None #",
"= False): # Update existing configurations in defaults # If new option found,",
"return ch def release_common_logging(ch, logger = None, l_logger_name = None): if logger is",
"not None: for ln in l_logger_name: temp = logging.getLogger(ln) temp.removeHandler(ch) def test_config(conf_name): conf",
"is None or fn == \"\": pass else: self.open_def(fn) def open_def(self, fn): group",
"import ConfigParser DEFAULT_CONFIG_NAME = \"/\".join((os.path.dirname(__file__), \"config.conf.default\")) LOGGER_NAME = __name__.rpartition(\".\")[-1] _logger = logging.getLogger(LOGGER_NAME) _ch",
"if logger is not None: logger.setLevel(lv) logger.addHandler(ch) for ln in l_logger_name: temp =",
"def test_config(conf_name): conf = open_config(conf_name) for section in conf.sections(): print \"[{0}]\".format(section) for option,",
"conf): # Do NOT allow updateing existing options in defaults for section in",
"in conf.options(section): value = conf.get(section, option) if not option in self.options(section): if warn:",
"elif \"m\" in string: num = int(string.partition(\"m\")[0]) return datetime.timedelta(minutes = num) elif \"h\"",
"\"\": ch = logging.StreamHandler() else: ch = logging.FileHandler(fn) ch.setFormatter(fmt) ch.setLevel(lv) if logger is",
"lines add elements in the group set with GROUP_NAME line \"\"\" def __init__(self,",
"logger = None, l_logger_name = [], lv = logging.INFO): fn = conf.get(\"general\", \"info_log\")",
"value = conf.get(section, option) self.set(section, option, value) return self def gettuple(self, section, name):",
"= \"/\".join((os.path.dirname(__file__), \"config.conf.default\")) LOGGER_NAME = __name__.rpartition(\".\")[-1] _logger = logging.getLogger(LOGGER_NAME) _ch = logging.StreamHandler() _ch.setLevel(logging.WARNING)",
"conf2.read(fn) conf.update(conf2, warn = True) if conf.has_section(\"general\"): if conf.has_option(\"general\", \"import\"): if not conf.get(\"general\",",
"conf.filename = fn return conf # common objects for logging def set_common_logging(conf, logger",
"if conf.has_option(\"general\", \"import\"): if not conf.get(\"general\", \"import\") == \"\": conf3 = ExtendedConfigParser() conf3.read(conf.get(\"general\",",
"= num) elif \"h\" in string: num = int(string.partition(\"h\")[0]) return datetime.timedelta(hours = num)",
"len(sys.argv) < 2: sys.exit(\"usage : {0} config\".format(sys.argv[0])) #default_conf = DEFAULT_CONFIG_NAME conf = sys.argv[1]",
"= {} self.default = default_val if fn is None or fn == \"\":",
"fn): _logger.warning(\"Invalid section name {0} in {1}\".format( section, fn)) for section in conf.sections():",
"== \"\") def getlist(self, section, name): ret = self.get(section, name) if ret ==",
"for option, value in conf.items(section): print \"{0} = {1}\".format(option, value) if __name__ ==",
"== \"\": conf3 = ExtendedConfigParser() conf3.read(conf.get(\"general\", \"import\")) conf.merge(conf3) conf.filename = fn return conf",
"not option in self.options(section): if warn: warn_opt(section, option, conf.filename) self.set(section, option, value) return",
"for option in conf.options(section): value = conf.get(section, option) if not option in self.options(section):",
"set other lines add elements in the group set with GROUP_NAME line \"\"\"",
"conf.sections(): if not section in self.sections(): self.add_section(section) if warn: warn_sec(section, conf.filename) for option",
"raise ValueError(\"no group definition before value\") val = line self.gdict.setdefault(group, []).append(val) self.rgdict.setdefault(val, []).append(group)",
"val = line self.gdict.setdefault(group, []).append(val) self.rgdict.setdefault(val, []).append(group) def setdefault(self, group): self.default = group",
"logging.INFO if fn == \"\": ch = logging.StreamHandler() else: ch = logging.FileHandler(fn) ch.setFormatter(fmt)",
"recognized as comment line \"[GROUP_NAME]\" will change group to set other lines add",
"def __init__(self): #super(ExtendedConfigParser, self).__init__(self) ConfigParser.SafeConfigParser.__init__(self) self.filename = None # source filename def read(self,",
"_ch = logging.StreamHandler() _ch.setLevel(logging.WARNING) _logger.setLevel(logging.WARNING) _logger.addHandler(_ch) class ExtendedConfigParser(ConfigParser.SafeConfigParser, object): def __init__(self): #super(ExtendedConfigParser, self).__init__(self)",
"None): conf = ExtendedConfigParser() conf.read(DEFAULT_CONFIG_NAME) if fn is not None: conf2 = ExtendedConfigParser()",
"datetime import logging import collections import ConfigParser DEFAULT_CONFIG_NAME = \"/\".join((os.path.dirname(__file__), \"config.conf.default\")) LOGGER_NAME =",
"int(string.partition(\"s\")[0]) return datetime.timedelta(seconds = num) elif \"m\" in string: num = int(string.partition(\"m\")[0]) return",
"ret = self.get(section, name) if ret == \"\": return None else: return datetime.datetime.strptime(ret.strip(),",
"name) if ret == \"\": return None else: return str2dur(ret) class GroupDef(): \"\"\"",
"fmt = logging.Formatter( fmt = \"%(asctime)s %(levelname)s (%(processName)s) %(message)s\", datefmt = \"%Y-%m-%d %H:%M:%S\")",
"fn): if not os.path.exists(fn): raise IOError(\"{0} not found\".format(fn)) else: self.filename = fn return",
"in f: # ignore after comment sygnal line = line.strip().partition(\"#\")[0] if line ==",
"== \"__main__\": ## import old config, merge it with new default config, and",
"for logging def set_common_logging(conf, logger = None, l_logger_name = [], lv = logging.INFO):",
"= {1}\".format(option, value) if __name__ == \"__main__\": ## import old config, merge it",
"= int(string.partition(\"w\")[0]) return datetime.timedelta(days = num * 7) else: raise ValueError(\"Duration string invalid\")",
"return tuple(e.strip() for e in ret.split(\",\") if not e.strip() == \"\") def getlist(self,",
"\"\"\".strip().format(option, section, fn)) def warn_sec(section, fn): _logger.warning(\"Invalid section name {0} in {1}\".format( section,",
"tuple(datetime.datetime.strptime(e.strip(), \"%Y-%m-%d %H:%M:%S\") for e in ret.split(\",\")) def getdur(self, section, name): ret =",
"== \"\": continue elif line[0] == \"#\": continue elif line[0] == \"[\" and",
"defaults # If new option found, warn and ignore it def warn_opt(section, option,",
"value\") val = line self.gdict.setdefault(group, []).append(val) self.rgdict.setdefault(val, []).append(group) def setdefault(self, group): self.default =",
"def ingroup(self, group, val): if self.rgdict(val): return val in self.rgdict[val] else: return False",
"default_val if fn is None or fn == \"\": pass else: self.open_def(fn) def",
"= fn return conf # common objects for logging def set_common_logging(conf, logger =",
"temp.addHandler(ch) return ch def release_common_logging(ch, logger = None, l_logger_name = None): if logger",
"section, name): ret = self.get(section, name) if ret == \"\": return None else:",
"in string: num = int(string.partition(\"s\")[0]) return datetime.timedelta(seconds = num) elif \"m\" in string:",
"getdur(self, section, name): ret = self.get(section, name) if ret == \"\": return None",
"None): self.gdict = {} self.rgdict = {} self.default = default_val if fn is",
"return super(ExtendedConfigParser, self).read(fn) def update(self, conf, warn = False): # Update existing configurations",
"= int(string.partition(\"h\")[0]) return datetime.timedelta(hours = num) elif \"d\" in string: num = int(string.partition(\"d\")[0])",
"datetime.datetime.strptime(ret.strip(), \"%Y-%m-%d %H:%M:%S\") def getterm(self, section, name): ret = self.get(section, name) if ret",
"return self def merge(self, conf): # Do NOT allow updateing existing options in",
"is not None: for ln in l_logger_name: temp = logging.getLogger(ln) temp.removeHandler(ch) def test_config(conf_name):",
"= int(string.partition(\"d\")[0]) return datetime.timedelta(days = num) elif \"w\" in string: num = int(string.partition(\"w\")[0])",
"logging.FileHandler(fn) ch.setFormatter(fmt) ch.setLevel(lv) if logger is not None: logger.setLevel(lv) logger.addHandler(ch) for ln in",
"= line.strip().partition(\"#\")[0] if line == \"\": continue elif line[0] == \"#\": continue elif",
"# source filename def read(self, fn): if not os.path.exists(fn): raise IOError(\"{0} not found\".format(fn))",
"\"\"\" def __init__(self, fn, default_val = None): self.gdict = {} self.rgdict = {}",
"section, name): ret = self.get(section, name) return tuple(e.strip() for e in ret.split(\",\") if",
"warn and ignore it def warn_opt(section, option, fn): _logger.warning(\"\"\" Invalid option name {0}",
"def gettuple(self, section, name): ret = self.get(section, name) return tuple(e.strip() for e in",
"in ret.split(\",\") if not e.strip() == \"\") def getlist(self, section, name): ret =",
"e in ret.split(\",\") if not e.strip() == \"\"] def getdt(self, section, name): ret",
"\"d\" in string: num = int(string.partition(\"d\")[0]) return datetime.timedelta(days = num) elif \"w\" in",
"datetime.timedelta(hours = num) elif \"d\" in string: num = int(string.partition(\"d\")[0]) return datetime.timedelta(days =",
"fmt = \"%(asctime)s %(levelname)s (%(processName)s) %(message)s\", datefmt = \"%Y-%m-%d %H:%M:%S\") #lv = logging.INFO",
"== \"]\": group = line[1:].strip(\"[]\") else: if group is None: raise ValueError(\"no group",
"sygnal line = line.strip().partition(\"#\")[0] if line == \"\": continue elif line[0] == \"#\":",
"def getterm(self, section, name): ret = self.get(section, name) if ret == \"\": return",
"f: # ignore after comment sygnal line = line.strip().partition(\"#\")[0] if line == \"\":",
"return [e.strip() for e in ret.split(\",\") if not e.strip() == \"\"] def getdt(self,",
"return False def get_group(self, val): if self.rgdict.has_key(val): return self.rgdict[val] else: return [] def",
"None else: return [e.strip() for e in ret.split(\",\") if not e.strip() == \"\"]",
"if ret == \"\": return None else: return tuple(datetime.datetime.strptime(e.strip(), \"%Y-%m-%d %H:%M:%S\") for e",
"merge(self, conf): # Do NOT allow updateing existing options in defaults for section",
"l_val in self.gdict.iteritems(): for val in l_val: yield group, val def str2dur(string): \"\"\"",
"{2}, ignored \"\"\".strip().format(option, section, fn)) def warn_sec(section, fn): _logger.warning(\"Invalid section name {0} in",
"#default_conf = DEFAULT_CONFIG_NAME conf = sys.argv[1] test_config(conf) #output = sys.argv[2] #overwrite_config(default_conf, conf, output)",
"if not option in self.options(section): if warn: warn_opt(section, option, conf.filename) self.set(section, option, value)",
"yield group, val def str2dur(string): \"\"\" Note: \\d+s: \\d seconds \\d+m: \\d minutes",
"conf3 = ExtendedConfigParser() conf3.read(conf.get(\"general\", \"import\")) conf.merge(conf3) conf.filename = fn return conf # common",
"self.gdict.iteritems(): for val in l_val: yield group, val def str2dur(string): \"\"\" Note: \\d+s:",
"line.strip().partition(\"#\")[0] if line == \"\": continue elif line[0] == \"#\": continue elif line[0]",
"ln in l_logger_name: temp = logging.getLogger(ln) temp.removeHandler(ch) def test_config(conf_name): conf = open_config(conf_name) for",
"import collections import ConfigParser DEFAULT_CONFIG_NAME = \"/\".join((os.path.dirname(__file__), \"config.conf.default\")) LOGGER_NAME = __name__.rpartition(\".\")[-1] _logger =",
"not e.strip() == \"\") def getlist(self, section, name): ret = self.get(section, name) if",
"self.rgdict.has_key(val): return self.rgdict[val] else: return [] def get_value(self, group): if self.gdict.has_key(group): return self.gdict[group]",
"num) elif \"m\" in string: num = int(string.partition(\"m\")[0]) return datetime.timedelta(minutes = num) elif",
"\"\": return None else: return datetime.datetime.strptime(ret.strip(), \"%Y-%m-%d %H:%M:%S\") def getterm(self, section, name): ret",
"and ignore it def warn_opt(section, option, fn): _logger.warning(\"\"\" Invalid option name {0} in",
"Rules: description after # in a line will be recognized as comment line",
"return None else: return tuple(datetime.datetime.strptime(e.strip(), \"%Y-%m-%d %H:%M:%S\") for e in ret.split(\",\")) def getdur(self,",
"\"/\".join((os.path.dirname(__file__), \"config.conf.default\")) LOGGER_NAME = __name__.rpartition(\".\")[-1] _logger = logging.getLogger(LOGGER_NAME) _ch = logging.StreamHandler() _ch.setLevel(logging.WARNING) _logger.setLevel(logging.WARNING)",
"False def get_group(self, val): if self.rgdict.has_key(val): return self.rgdict[val] else: return [] def get_value(self,",
"\"__main__\": ## import old config, merge it with new default config, and output",
"\\d+h: \\d hours \\d+d: \\d days \\d+w: \\d * 7 days \"\"\" if",
"config, and output if len(sys.argv) < 2: sys.exit(\"usage : {0} config\".format(sys.argv[0])) #default_conf =",
"option) if not option in self.options(section): if warn: warn_opt(section, option, conf.filename) self.set(section, option,",
"= logging.StreamHandler() _ch.setLevel(logging.WARNING) _logger.setLevel(logging.WARNING) _logger.addHandler(_ch) class ExtendedConfigParser(ConfigParser.SafeConfigParser, object): def __init__(self): #super(ExtendedConfigParser, self).__init__(self) ConfigParser.SafeConfigParser.__init__(self)",
"for ln in l_logger_name: temp = logging.getLogger(ln) temp.setLevel(lv) temp.addHandler(ch) return ch def release_common_logging(ch,",
"datetime.timedelta(seconds = num) elif \"m\" in string: num = int(string.partition(\"m\")[0]) return datetime.timedelta(minutes =",
"seconds \\d+m: \\d minutes \\d+h: \\d hours \\d+d: \\d days \\d+w: \\d *",
"open_config(fn = None): conf = ExtendedConfigParser() conf.read(DEFAULT_CONFIG_NAME) if fn is not None: conf2",
"to set other lines add elements in the group set with GROUP_NAME line",
"section name {0} in {1}\".format( section, fn)) for section in conf.sections(): if not",
"= num) elif \"m\" in string: num = int(string.partition(\"m\")[0]) return datetime.timedelta(minutes = num)",
"l_logger_name = None): if logger is not None: logger.removeHandler(ch) if l_logger_name is not",
"%H:%M:%S\") def getterm(self, section, name): ret = self.get(section, name) if ret == \"\":",
"as comment line \"[GROUP_NAME]\" will change group to set other lines add elements",
"if ret == \"\": return None else: return [e.strip() for e in ret.split(\",\")",
"# in a line will be recognized as comment line \"[GROUP_NAME]\" will change",
"= logging.INFO if fn == \"\": ch = logging.StreamHandler() else: ch = logging.FileHandler(fn)",
"def release_common_logging(ch, logger = None, l_logger_name = None): if logger is not None:",
"[], lv = logging.INFO): fn = conf.get(\"general\", \"info_log\") fmt = logging.Formatter( fmt =",
"\"\"] def getdt(self, section, name): ret = self.get(section, name) if ret == \"\":",
"* 7 days \"\"\" if \"s\" in string: num = int(string.partition(\"s\")[0]) return datetime.timedelta(seconds",
"logger.removeHandler(ch) if l_logger_name is not None: for ln in l_logger_name: temp = logging.getLogger(ln)",
"self.rgdict[val] else: return [] def get_value(self, group): if self.gdict.has_key(group): return self.gdict[group] else: return",
"group): self.default = group def groups(self): return self.gdict.keys() def values(self): return self.rgdict.keys() def",
"[e.strip() for e in ret.split(\",\") if not e.strip() == \"\"] def getdt(self, section,",
"option, value) return self def merge(self, conf): # Do NOT allow updateing existing",
"__init__(self, fn, default_val = None): self.gdict = {} self.rgdict = {} self.default =",
"[] def iter_def(self): for group, l_val in self.gdict.iteritems(): for val in l_val: yield",
"def warn_sec(section, fn): _logger.warning(\"Invalid section name {0} in {1}\".format( section, fn)) for section",
"conf.read(DEFAULT_CONFIG_NAME) if fn is not None: conf2 = ExtendedConfigParser() conf2.read(fn) conf.update(conf2, warn =",
"os.path.exists(fn): raise IOError(\"{0} not found\".format(fn)) else: self.filename = fn return super(ExtendedConfigParser, self).read(fn) def",
"\"{0} = {1}\".format(option, value) if __name__ == \"__main__\": ## import old config, merge",
"conf.get(\"general\", \"info_log\") fmt = logging.Formatter( fmt = \"%(asctime)s %(levelname)s (%(processName)s) %(message)s\", datefmt =",
"else: return [e.strip() for e in ret.split(\",\") if not e.strip() == \"\"] def",
"line = line.strip().partition(\"#\")[0] if line == \"\": continue elif line[0] == \"#\": continue",
"days \\d+w: \\d * 7 days \"\"\" if \"s\" in string: num =",
"in the group set with GROUP_NAME line \"\"\" def __init__(self, fn, default_val =",
"_logger.warning(\"\"\" Invalid option name {0} in section {1} in {2}, ignored \"\"\".strip().format(option, section,",
"in string: num = int(string.partition(\"m\")[0]) return datetime.timedelta(minutes = num) elif \"h\" in string:",
"def str2dur(string): \"\"\" Note: \\d+s: \\d seconds \\d+m: \\d minutes \\d+h: \\d hours",
"def getlist(self, section, name): ret = self.get(section, name) if ret == \"\": return",
"else: return str2dur(ret) class GroupDef(): \"\"\" Define grouping by external text Rules: description",
"logging.getLogger(ln) temp.removeHandler(ch) def test_config(conf_name): conf = open_config(conf_name) for section in conf.sections(): print \"[{0}]\".format(section)",
"{0} in {1}\".format( section, fn)) for section in conf.sections(): if not section in",
"= int(string.partition(\"s\")[0]) return datetime.timedelta(seconds = num) elif \"m\" in string: num = int(string.partition(\"m\")[0])",
"return self.rgdict[val] else: return [] def get_value(self, group): if self.gdict.has_key(group): return self.gdict[group] else:",
"for section in conf.sections(): if not section in self.sections(): self.add_section(section) if warn: warn_sec(section,",
"in ret.split(\",\") if not e.strip() == \"\"] def getdt(self, section, name): ret =",
"= num * 7) else: raise ValueError(\"Duration string invalid\") def open_config(fn = None):",
"conf.has_section(\"general\"): if conf.has_option(\"general\", \"import\"): if not conf.get(\"general\", \"import\") == \"\": conf3 = ExtendedConfigParser()",
"in conf.sections(): if not section in self.sections(): self.add_section(section) for option in conf.options(section): if",
"line[-1] == \"]\": group = line[1:].strip(\"[]\") else: if group is None: raise ValueError(\"no",
"ch def release_common_logging(ch, logger = None, l_logger_name = None): if logger is not",
"fn == \"\": ch = logging.StreamHandler() else: ch = logging.FileHandler(fn) ch.setFormatter(fmt) ch.setLevel(lv) if",
"None: logger.setLevel(lv) logger.addHandler(ch) for ln in l_logger_name: temp = logging.getLogger(ln) temp.setLevel(lv) temp.addHandler(ch) return",
"config, merge it with new default config, and output if len(sys.argv) < 2:",
"conf.merge(conf3) conf.filename = fn return conf # common objects for logging def set_common_logging(conf,",
"7 days \"\"\" if \"s\" in string: num = int(string.partition(\"s\")[0]) return datetime.timedelta(seconds =",
"return datetime.datetime.strptime(ret.strip(), \"%Y-%m-%d %H:%M:%S\") def getterm(self, section, name): ret = self.get(section, name) if",
"= num) elif \"w\" in string: num = int(string.partition(\"w\")[0]) return datetime.timedelta(days = num",
"conf.has_option(\"general\", \"import\"): if not conf.get(\"general\", \"import\") == \"\": conf3 = ExtendedConfigParser() conf3.read(conf.get(\"general\", \"import\"))",
"\"\": return None else: return [e.strip() for e in ret.split(\",\") if not e.strip()",
"{} self.rgdict = {} self.default = default_val if fn is None or fn",
"existing configurations in defaults # If new option found, warn and ignore it",
"val def str2dur(string): \"\"\" Note: \\d+s: \\d seconds \\d+m: \\d minutes \\d+h: \\d",
"\"[{0}]\".format(section) for option, value in conf.items(section): print \"{0} = {1}\".format(option, value) if __name__",
"__name__.rpartition(\".\")[-1] _logger = logging.getLogger(LOGGER_NAME) _ch = logging.StreamHandler() _ch.setLevel(logging.WARNING) _logger.setLevel(logging.WARNING) _logger.addHandler(_ch) class ExtendedConfigParser(ConfigParser.SafeConfigParser, object):",
"ignored \"\"\".strip().format(option, section, fn)) def warn_sec(section, fn): _logger.warning(\"Invalid section name {0} in {1}\".format(",
"open_config(conf_name) for section in conf.sections(): print \"[{0}]\".format(section) for option, value in conf.items(section): print",
"option in self.options(section): if warn: warn_opt(section, option, conf.filename) self.set(section, option, value) return self",
"= __name__.rpartition(\".\")[-1] _logger = logging.getLogger(LOGGER_NAME) _ch = logging.StreamHandler() _ch.setLevel(logging.WARNING) _logger.setLevel(logging.WARNING) _logger.addHandler(_ch) class ExtendedConfigParser(ConfigParser.SafeConfigParser,",
"logging.StreamHandler() else: ch = logging.FileHandler(fn) ch.setFormatter(fmt) ch.setLevel(lv) if logger is not None: logger.setLevel(lv)",
"section {1} in {2}, ignored \"\"\".strip().format(option, section, fn)) def warn_sec(section, fn): _logger.warning(\"Invalid section",
"python # coding: utf-8 import sys import os import datetime import logging import",
"def groups(self): return self.gdict.keys() def values(self): return self.rgdict.keys() def ingroup(self, group, val): if",
"ConfigParser DEFAULT_CONFIG_NAME = \"/\".join((os.path.dirname(__file__), \"config.conf.default\")) LOGGER_NAME = __name__.rpartition(\".\")[-1] _logger = logging.getLogger(LOGGER_NAME) _ch =",
"= line self.gdict.setdefault(group, []).append(val) self.rgdict.setdefault(val, []).append(group) def setdefault(self, group): self.default = group def",
"self.gdict.keys() def values(self): return self.rgdict.keys() def ingroup(self, group, val): if self.rgdict(val): return val",
"section in conf.sections(): if not section in self.sections(): self.add_section(section) for option in conf.options(section):",
"elif line[0] == \"[\" and line[-1] == \"]\": group = line[1:].strip(\"[]\") else: if",
"== \"[\" and line[-1] == \"]\": group = line[1:].strip(\"[]\") else: if group is",
"conf.get(section, option) self.set(section, option, value) return self def gettuple(self, section, name): ret =",
"with new default config, and output if len(sys.argv) < 2: sys.exit(\"usage : {0}",
"else: return [] def get_value(self, group): if self.gdict.has_key(group): return self.gdict[group] else: return []",
"external text Rules: description after # in a line will be recognized as",
"class GroupDef(): \"\"\" Define grouping by external text Rules: description after # in",
"return datetime.timedelta(days = num * 7) else: raise ValueError(\"Duration string invalid\") def open_config(fn",
"= logging.FileHandler(fn) ch.setFormatter(fmt) ch.setLevel(lv) if logger is not None: logger.setLevel(lv) logger.addHandler(ch) for ln",
"option, value in conf.items(section): print \"{0} = {1}\".format(option, value) if __name__ == \"__main__\":",
"logging def set_common_logging(conf, logger = None, l_logger_name = [], lv = logging.INFO): fn",
"self.options(section): if warn: warn_opt(section, option, conf.filename) self.set(section, option, value) return self def merge(self,",
"val): if self.rgdict(val): return val in self.rgdict[val] else: return False def get_group(self, val):",
"None: logger.removeHandler(ch) if l_logger_name is not None: for ln in l_logger_name: temp =",
"\"#\": continue elif line[0] == \"[\" and line[-1] == \"]\": group = line[1:].strip(\"[]\")",
"if not e.strip() == \"\") def getlist(self, section, name): ret = self.get(section, name)",
"{1}\".format(option, value) if __name__ == \"__main__\": ## import old config, merge it with",
"source filename def read(self, fn): if not os.path.exists(fn): raise IOError(\"{0} not found\".format(fn)) else:",
"# Do NOT allow updateing existing options in defaults for section in conf.sections():",
"if fn is None or fn == \"\": pass else: self.open_def(fn) def open_def(self,",
"{1}\".format( section, fn)) for section in conf.sections(): if not section in self.sections(): self.add_section(section)",
"logging.Formatter( fmt = \"%(asctime)s %(levelname)s (%(processName)s) %(message)s\", datefmt = \"%Y-%m-%d %H:%M:%S\") #lv =",
"[]).append(val) self.rgdict.setdefault(val, []).append(group) def setdefault(self, group): self.default = group def groups(self): return self.gdict.keys()",
"found, warn and ignore it def warn_opt(section, option, fn): _logger.warning(\"\"\" Invalid option name",
"return self.gdict.keys() def values(self): return self.rgdict.keys() def ingroup(self, group, val): if self.rgdict(val): return",
"self).__init__(self) ConfigParser.SafeConfigParser.__init__(self) self.filename = None # source filename def read(self, fn): if not",
"group definition before value\") val = line self.gdict.setdefault(group, []).append(val) self.rgdict.setdefault(val, []).append(group) def setdefault(self,",
"#super(ExtendedConfigParser, self).__init__(self) ConfigParser.SafeConfigParser.__init__(self) self.filename = None # source filename def read(self, fn): if",
"group): if self.gdict.has_key(group): return self.gdict[group] else: return [] def iter_def(self): for group, l_val",
"DEFAULT_CONFIG_NAME = \"/\".join((os.path.dirname(__file__), \"config.conf.default\")) LOGGER_NAME = __name__.rpartition(\".\")[-1] _logger = logging.getLogger(LOGGER_NAME) _ch = logging.StreamHandler()",
"raise IOError(\"{0} not found\".format(fn)) else: self.filename = fn return super(ExtendedConfigParser, self).read(fn) def update(self,",
"section, fn)) for section in conf.sections(): if not section in self.sections(): self.add_section(section) if",
"name {0} in {1}\".format( section, fn)) for section in conf.sections(): if not section",
"self def merge(self, conf): # Do NOT allow updateing existing options in defaults",
"getdt(self, section, name): ret = self.get(section, name) if ret == \"\": return None",
"None: raise ValueError(\"no group definition before value\") val = line self.gdict.setdefault(group, []).append(val) self.rgdict.setdefault(val,",
"name {0} in section {1} in {2}, ignored \"\"\".strip().format(option, section, fn)) def warn_sec(section,",
"in conf.sections(): print \"[{0}]\".format(section) for option, value in conf.items(section): print \"{0} = {1}\".format(option,",
"line == \"\": continue elif line[0] == \"#\": continue elif line[0] == \"[\"",
"old config, merge it with new default config, and output if len(sys.argv) <",
"#lv = logging.INFO if fn == \"\": ch = logging.StreamHandler() else: ch =",
"option, value) return self def gettuple(self, section, name): ret = self.get(section, name) return",
"LOGGER_NAME = __name__.rpartition(\".\")[-1] _logger = logging.getLogger(LOGGER_NAME) _ch = logging.StreamHandler() _ch.setLevel(logging.WARNING) _logger.setLevel(logging.WARNING) _logger.addHandler(_ch) class",
"ch.setFormatter(fmt) ch.setLevel(lv) if logger is not None: logger.setLevel(lv) logger.addHandler(ch) for ln in l_logger_name:",
"None, l_logger_name = [], lv = logging.INFO): fn = conf.get(\"general\", \"info_log\") fmt =",
"section in self.sections(): self.add_section(section) if warn: warn_sec(section, conf.filename) for option in conf.options(section): value",
"warn_sec(section, conf.filename) for option in conf.options(section): value = conf.get(section, option) if not option",
"def read(self, fn): if not os.path.exists(fn): raise IOError(\"{0} not found\".format(fn)) else: self.filename =",
"conf.get(section, option) if not option in self.options(section): if warn: warn_opt(section, option, conf.filename) self.set(section,",
"option): value = conf.get(section, option) self.set(section, option, value) return self def gettuple(self, section,",
"# ignore after comment sygnal line = line.strip().partition(\"#\")[0] if line == \"\": continue",
"\"[GROUP_NAME]\" will change group to set other lines add elements in the group",
"name) if ret == \"\": return None else: return datetime.datetime.strptime(ret.strip(), \"%Y-%m-%d %H:%M:%S\") def",
"l_val: yield group, val def str2dur(string): \"\"\" Note: \\d+s: \\d seconds \\d+m: \\d",
"_ch.setLevel(logging.WARNING) _logger.setLevel(logging.WARNING) _logger.addHandler(_ch) class ExtendedConfigParser(ConfigParser.SafeConfigParser, object): def __init__(self): #super(ExtendedConfigParser, self).__init__(self) ConfigParser.SafeConfigParser.__init__(self) self.filename =",
"\"\"\" if \"s\" in string: num = int(string.partition(\"s\")[0]) return datetime.timedelta(seconds = num) elif",
"\\d minutes \\d+h: \\d hours \\d+d: \\d days \\d+w: \\d * 7 days",
"if self.gdict.has_key(group): return self.gdict[group] else: return [] def iter_def(self): for group, l_val in",
"GroupDef(): \"\"\" Define grouping by external text Rules: description after # in a",
"else: if group is None: raise ValueError(\"no group definition before value\") val =",
"if ret == \"\": return None else: return str2dur(ret) class GroupDef(): \"\"\" Define",
"conf = open_config(conf_name) for section in conf.sections(): print \"[{0}]\".format(section) for option, value in",
"groups(self): return self.gdict.keys() def values(self): return self.rgdict.keys() def ingroup(self, group, val): if self.rgdict(val):",
"elif \"h\" in string: num = int(string.partition(\"h\")[0]) return datetime.timedelta(hours = num) elif \"d\"",
"self.gdict[group] else: return [] def iter_def(self): for group, l_val in self.gdict.iteritems(): for val",
"logging.getLogger(LOGGER_NAME) _ch = logging.StreamHandler() _ch.setLevel(logging.WARNING) _logger.setLevel(logging.WARNING) _logger.addHandler(_ch) class ExtendedConfigParser(ConfigParser.SafeConfigParser, object): def __init__(self): #super(ExtendedConfigParser,",
"be recognized as comment line \"[GROUP_NAME]\" will change group to set other lines",
"warn = True) if conf.has_section(\"general\"): if conf.has_option(\"general\", \"import\"): if not conf.get(\"general\", \"import\") ==",
"if not os.path.exists(fn): raise IOError(\"{0} not found\".format(fn)) else: self.filename = fn return super(ExtendedConfigParser,",
"option in conf.options(section): if not self.has_option(section, option): value = conf.get(section, option) self.set(section, option,",
"if l_logger_name is not None: for ln in l_logger_name: temp = logging.getLogger(ln) temp.removeHandler(ch)",
"%(message)s\", datefmt = \"%Y-%m-%d %H:%M:%S\") #lv = logging.INFO if fn == \"\": ch",
"conf.options(section): if not self.has_option(section, option): value = conf.get(section, option) self.set(section, option, value) return",
"line in f: # ignore after comment sygnal line = line.strip().partition(\"#\")[0] if line",
"%H:%M:%S\") for e in ret.split(\",\")) def getdur(self, section, name): ret = self.get(section, name)",
"= open_config(conf_name) for section in conf.sections(): print \"[{0}]\".format(section) for option, value in conf.items(section):",
"return val in self.rgdict[val] else: return False def get_group(self, val): if self.rgdict.has_key(val): return",
"num = int(string.partition(\"w\")[0]) return datetime.timedelta(days = num * 7) else: raise ValueError(\"Duration string",
"ExtendedConfigParser() conf2.read(fn) conf.update(conf2, warn = True) if conf.has_section(\"general\"): if conf.has_option(\"general\", \"import\"): if not",
"after # in a line will be recognized as comment line \"[GROUP_NAME]\" will",
"== \"\"] def getdt(self, section, name): ret = self.get(section, name) if ret ==",
"string: num = int(string.partition(\"m\")[0]) return datetime.timedelta(minutes = num) elif \"h\" in string: num",
"after comment sygnal line = line.strip().partition(\"#\")[0] if line == \"\": continue elif line[0]",
"and output if len(sys.argv) < 2: sys.exit(\"usage : {0} config\".format(sys.argv[0])) #default_conf = DEFAULT_CONFIG_NAME",
"string: num = int(string.partition(\"d\")[0]) return datetime.timedelta(days = num) elif \"w\" in string: num",
"\"%Y-%m-%d %H:%M:%S\") #lv = logging.INFO if fn == \"\": ch = logging.StreamHandler() else:",
"e in ret.split(\",\") if not e.strip() == \"\") def getlist(self, section, name): ret",
"warn = False): # Update existing configurations in defaults # If new option",
"in self.rgdict[val] else: return False def get_group(self, val): if self.rgdict.has_key(val): return self.rgdict[val] else:",
"logger is not None: logger.setLevel(lv) logger.addHandler(ch) for ln in l_logger_name: temp = logging.getLogger(ln)",
"name): ret = self.get(section, name) return tuple(e.strip() for e in ret.split(\",\") if not",
"_logger.warning(\"Invalid section name {0} in {1}\".format( section, fn)) for section in conf.sections(): if",
"getlist(self, section, name): ret = self.get(section, name) if ret == \"\": return None",
"\\d+d: \\d days \\d+w: \\d * 7 days \"\"\" if \"s\" in string:",
"int(string.partition(\"d\")[0]) return datetime.timedelta(days = num) elif \"w\" in string: num = int(string.partition(\"w\")[0]) return",
"in l_logger_name: temp = logging.getLogger(ln) temp.removeHandler(ch) def test_config(conf_name): conf = open_config(conf_name) for section",
"if not self.has_option(section, option): value = conf.get(section, option) self.set(section, option, value) return self",
"option name {0} in section {1} in {2}, ignored \"\"\".strip().format(option, section, fn)) def",
"temp = logging.getLogger(ln) temp.removeHandler(ch) def test_config(conf_name): conf = open_config(conf_name) for section in conf.sections():",
"self.get(section, name) if ret == \"\": return None else: return str2dur(ret) class GroupDef():",
"comment sygnal line = line.strip().partition(\"#\")[0] if line == \"\": continue elif line[0] ==",
"update(self, conf, warn = False): # Update existing configurations in defaults # If",
"if warn: warn_opt(section, option, conf.filename) self.set(section, option, value) return self def merge(self, conf):",
"group, val): if self.rgdict(val): return val in self.rgdict[val] else: return False def get_group(self,",
"val in l_val: yield group, val def str2dur(string): \"\"\" Note: \\d+s: \\d seconds",
"string: num = int(string.partition(\"s\")[0]) return datetime.timedelta(seconds = num) elif \"m\" in string: num",
"\"m\" in string: num = int(string.partition(\"m\")[0]) return datetime.timedelta(minutes = num) elif \"h\" in",
"coding: utf-8 import sys import os import datetime import logging import collections import",
"a line will be recognized as comment line \"[GROUP_NAME]\" will change group to",
"\\d hours \\d+d: \\d days \\d+w: \\d * 7 days \"\"\" if \"s\"",
"\"import\"): if not conf.get(\"general\", \"import\") == \"\": conf3 = ExtendedConfigParser() conf3.read(conf.get(\"general\", \"import\")) conf.merge(conf3)",
"logger.addHandler(ch) for ln in l_logger_name: temp = logging.getLogger(ln) temp.setLevel(lv) temp.addHandler(ch) return ch def",
"ch = logging.StreamHandler() else: ch = logging.FileHandler(fn) ch.setFormatter(fmt) ch.setLevel(lv) if logger is not",
"name) return tuple(e.strip() for e in ret.split(\",\") if not e.strip() == \"\") def",
"{1} in {2}, ignored \"\"\".strip().format(option, section, fn)) def warn_sec(section, fn): _logger.warning(\"Invalid section name",
"e in ret.split(\",\")) def getdur(self, section, name): ret = self.get(section, name) if ret",
"self.gdict.has_key(group): return self.gdict[group] else: return [] def iter_def(self): for group, l_val in self.gdict.iteritems():",
"= self.get(section, name) if ret == \"\": return None else: return str2dur(ret) class",
"for section in conf.sections(): print \"[{0}]\".format(section) for option, value in conf.items(section): print \"{0}",
"default config, and output if len(sys.argv) < 2: sys.exit(\"usage : {0} config\".format(sys.argv[0])) #default_conf",
"If new option found, warn and ignore it def warn_opt(section, option, fn): _logger.warning(\"\"\"",
"not None: logger.setLevel(lv) logger.addHandler(ch) for ln in l_logger_name: temp = logging.getLogger(ln) temp.setLevel(lv) temp.addHandler(ch)",
"for section in conf.sections(): if not section in self.sections(): self.add_section(section) for option in",
"\"\") def getlist(self, section, name): ret = self.get(section, name) if ret == \"\":",
"return tuple(datetime.datetime.strptime(e.strip(), \"%Y-%m-%d %H:%M:%S\") for e in ret.split(\",\")) def getdur(self, section, name): ret",
"return self.rgdict.keys() def ingroup(self, group, val): if self.rgdict(val): return val in self.rgdict[val] else:",
"conf2 = ExtendedConfigParser() conf2.read(fn) conf.update(conf2, warn = True) if conf.has_section(\"general\"): if conf.has_option(\"general\", \"import\"):",
"option found, warn and ignore it def warn_opt(section, option, fn): _logger.warning(\"\"\" Invalid option",
"num = int(string.partition(\"d\")[0]) return datetime.timedelta(days = num) elif \"w\" in string: num =",
"self.rgdict.setdefault(val, []).append(group) def setdefault(self, group): self.default = group def groups(self): return self.gdict.keys() def",
"options in defaults for section in conf.sections(): if not section in self.sections(): self.add_section(section)",
"in a line will be recognized as comment line \"[GROUP_NAME]\" will change group",
"= \"%(asctime)s %(levelname)s (%(processName)s) %(message)s\", datefmt = \"%Y-%m-%d %H:%M:%S\") #lv = logging.INFO if",
"in self.sections(): self.add_section(section) for option in conf.options(section): if not self.has_option(section, option): value =",
"import sys import os import datetime import logging import collections import ConfigParser DEFAULT_CONFIG_NAME",
"line[1:].strip(\"[]\") else: if group is None: raise ValueError(\"no group definition before value\") val",
"def values(self): return self.rgdict.keys() def ingroup(self, group, val): if self.rgdict(val): return val in",
"conf.sections(): print \"[{0}]\".format(section) for option, value in conf.items(section): print \"{0} = {1}\".format(option, value)",
"\"\"\" Define grouping by external text Rules: description after # in a line",
"\"[\" and line[-1] == \"]\": group = line[1:].strip(\"[]\") else: if group is None:",
"self.add_section(section) for option in conf.options(section): if not self.has_option(section, option): value = conf.get(section, option)",
"elif \"w\" in string: num = int(string.partition(\"w\")[0]) return datetime.timedelta(days = num * 7)",
"= self.get(section, name) if ret == \"\": return None else: return datetime.datetime.strptime(ret.strip(), \"%Y-%m-%d",
"name) if ret == \"\": return None else: return [e.strip() for e in",
"conf.items(section): print \"{0} = {1}\".format(option, value) if __name__ == \"__main__\": ## import old",
"\"info_log\") fmt = logging.Formatter( fmt = \"%(asctime)s %(levelname)s (%(processName)s) %(message)s\", datefmt = \"%Y-%m-%d",
"## import old config, merge it with new default config, and output if",
"%(levelname)s (%(processName)s) %(message)s\", datefmt = \"%Y-%m-%d %H:%M:%S\") #lv = logging.INFO if fn ==",
"not None: logger.removeHandler(ch) if l_logger_name is not None: for ln in l_logger_name: temp",
"ret == \"\": return None else: return [e.strip() for e in ret.split(\",\") if",
"test_config(conf_name): conf = open_config(conf_name) for section in conf.sections(): print \"[{0}]\".format(section) for option, value",
"if \"s\" in string: num = int(string.partition(\"s\")[0]) return datetime.timedelta(seconds = num) elif \"m\"",
"group set with GROUP_NAME line \"\"\" def __init__(self, fn, default_val = None): self.gdict",
"self.default = default_val if fn is None or fn == \"\": pass else:",
"in l_logger_name: temp = logging.getLogger(ln) temp.setLevel(lv) temp.addHandler(ch) return ch def release_common_logging(ch, logger =",
"in {2}, ignored \"\"\".strip().format(option, section, fn)) def warn_sec(section, fn): _logger.warning(\"Invalid section name {0}",
"def get_value(self, group): if self.gdict.has_key(group): return self.gdict[group] else: return [] def iter_def(self): for",
"conf.sections(): if not section in self.sections(): self.add_section(section) for option in conf.options(section): if not",
"get_group(self, val): if self.rgdict.has_key(val): return self.rgdict[val] else: return [] def get_value(self, group): if",
"\\d seconds \\d+m: \\d minutes \\d+h: \\d hours \\d+d: \\d days \\d+w: \\d",
"l_logger_name = [], lv = logging.INFO): fn = conf.get(\"general\", \"info_log\") fmt = logging.Formatter(",
"ret == \"\": return None else: return tuple(datetime.datetime.strptime(e.strip(), \"%Y-%m-%d %H:%M:%S\") for e in",
"= None with open(fn, 'r') as f: for line in f: # ignore",
"= logging.getLogger(LOGGER_NAME) _ch = logging.StreamHandler() _ch.setLevel(logging.WARNING) _logger.setLevel(logging.WARNING) _logger.addHandler(_ch) class ExtendedConfigParser(ConfigParser.SafeConfigParser, object): def __init__(self):",
"None, l_logger_name = None): if logger is not None: logger.removeHandler(ch) if l_logger_name is",
"if ret == \"\": return None else: return datetime.datetime.strptime(ret.strip(), \"%Y-%m-%d %H:%M:%S\") def getterm(self,",
"self.rgdict[val] else: return False def get_group(self, val): if self.rgdict.has_key(val): return self.rgdict[val] else: return",
"for val in l_val: yield group, val def str2dur(string): \"\"\" Note: \\d+s: \\d",
"and line[-1] == \"]\": group = line[1:].strip(\"[]\") else: if group is None: raise",
"# coding: utf-8 import sys import os import datetime import logging import collections",
"== \"\": return None else: return [e.strip() for e in ret.split(\",\") if not",
"\"\": conf3 = ExtendedConfigParser() conf3.read(conf.get(\"general\", \"import\")) conf.merge(conf3) conf.filename = fn return conf #",
"\"%Y-%m-%d %H:%M:%S\") for e in ret.split(\",\")) def getdur(self, section, name): ret = self.get(section,",
"= group def groups(self): return self.gdict.keys() def values(self): return self.rgdict.keys() def ingroup(self, group,",
"not found\".format(fn)) else: self.filename = fn return super(ExtendedConfigParser, self).read(fn) def update(self, conf, warn",
"fn == \"\": pass else: self.open_def(fn) def open_def(self, fn): group = None with",
"ret.split(\",\") if not e.strip() == \"\"] def getdt(self, section, name): ret = self.get(section,",
"fn return conf # common objects for logging def set_common_logging(conf, logger = None,"
] |
[
"c in cols] RESULT+=\"\\n\"+Begin+\" \"+Category+\" \"+title+\" \"+size toplevel = Toplevel() label= Label(toplevel,text=RESULT,height=0,width=100) label.pack()",
"BeautifulSoup as BS class window(Tkinter.Tk): Ip_text = '' def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent =",
"= httplib.HTTPConnection(\"www.iknowwhatyoudownload.com/en/peer/?ip=\"+IP) conn.request(\"GET\",\"/\") response = conn.getresponse() data =response.read() soup = BS(data,\"html.parser\") table =",
"have no Internet Connection') if __name__ == \"__main__\": app = window(None) app.title('Torrent IP",
"Tkinter.Tk.__init__(self,parent) self.parent = parent self.iconbitmap(default='eye.ico') self.geometry(\"500x100\") self.resizable(0, 0) self.initialize() def initialize(self): L =",
"print RESULT def checkIp(self): IP=self.E.get() try: urllib2.urlopen('http://172.16.17.32',timeout=1) print IP self.work(IP) except urllib2.URLError as",
"= conn.getresponse() data =response.read() soup = BS(data,\"html.parser\") table = soup.find('tbody') rows = table.findAll('tr')",
"IP self.work(IP) except urllib2.URLError as err: tkMessageBox.showerror('No Internet Connection','You have no Internet Connection')",
"import BeautifulSoup as BS class window(Tkinter.Tk): Ip_text = '' def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent",
"tkMessageBox.showerror('No Internet Connection','You have no Internet Connection') if __name__ == \"__main__\": app =",
"0) self.initialize() def initialize(self): L = Tkinter.Label(master=self,text=\"Targeted IP:\") L.pack() self.E = Tkinter.Entry(master=self,width=50) self.E.pack()",
"tr.findAll('td') Begin,End,Category,title,size=[c.text for c in cols] RESULT+=\"\\n\"+Begin+\" \"+Category+\" \"+title+\" \"+size toplevel = Toplevel()",
"print IP self.work(IP) except urllib2.URLError as err: tkMessageBox.showerror('No Internet Connection','You have no Internet",
"soup = BS(data,\"html.parser\") table = soup.find('tbody') rows = table.findAll('tr') for tr in rows:",
"table = soup.find('tbody') rows = table.findAll('tr') for tr in rows: cols = tr.findAll('td')",
"= soup.find('tbody') rows = table.findAll('tr') for tr in rows: cols = tr.findAll('td') Begin,End,Category,title,size=[c.text",
"table.findAll('tr') for tr in rows: cols = tr.findAll('td') Begin,End,Category,title,size=[c.text for c in cols]",
"Label(toplevel,text=RESULT,height=0,width=100) label.pack() print RESULT def checkIp(self): IP=self.E.get() try: urllib2.urlopen('http://172.16.17.32',timeout=1) print IP self.work(IP) except",
"except urllib2.URLError as err: tkMessageBox.showerror('No Internet Connection','You have no Internet Connection') if __name__",
"httplib from bs4 import BeautifulSoup as BS class window(Tkinter.Tk): Ip_text = '' def",
"conn = httplib.HTTPConnection(\"www.iknowwhatyoudownload.com/en/peer/?ip=\"+IP) conn.request(\"GET\",\"/\") response = conn.getresponse() data =response.read() soup = BS(data,\"html.parser\") table",
"#!/usr/bin/python import Tkinter import ctypes import tkMessageBox import socket import sys import urllib2",
"= BS(data,\"html.parser\") table = soup.find('tbody') rows = table.findAll('tr') for tr in rows: cols",
"app.title('Torrent IP tracker - By <NAME> v0.1') AppID= \"Torrent Tracker By Houssem. Torrent",
"Begin,End,Category,title,size=[c.text for c in cols] RESULT+=\"\\n\"+Begin+\" \"+Category+\" \"+title+\" \"+size toplevel = Toplevel() label=",
"IP=self.E.get() try: urllib2.urlopen('http://172.16.17.32',timeout=1) print IP self.work(IP) except urllib2.URLError as err: tkMessageBox.showerror('No Internet Connection','You",
"def work(IP): conn = httplib.HTTPConnection(\"www.iknowwhatyoudownload.com/en/peer/?ip=\"+IP) conn.request(\"GET\",\"/\") response = conn.getresponse() data =response.read() soup =",
"label= Label(toplevel,text=RESULT,height=0,width=100) label.pack() print RESULT def checkIp(self): IP=self.E.get() try: urllib2.urlopen('http://172.16.17.32',timeout=1) print IP self.work(IP)",
"urllib2.URLError as err: tkMessageBox.showerror('No Internet Connection','You have no Internet Connection') if __name__ ==",
"import sys import urllib2 import httplib from bs4 import BeautifulSoup as BS class",
"self.work(IP) except urllib2.URLError as err: tkMessageBox.showerror('No Internet Connection','You have no Internet Connection') if",
"\"+size toplevel = Toplevel() label= Label(toplevel,text=RESULT,height=0,width=100) label.pack() print RESULT def checkIp(self): IP=self.E.get() try:",
"- By <NAME> v0.1') AppID= \"Torrent Tracker By Houssem. Torrent IP Tracker.V0.1\" ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(AppID)",
"L.pack() self.E = Tkinter.Entry(master=self,width=50) self.E.pack() B= Tkinter.Button(master=self,text='Check IP',command=self.checkIp) B.pack() self.grid() def work(IP): conn",
"sys import urllib2 import httplib from bs4 import BeautifulSoup as BS class window(Tkinter.Tk):",
"for c in cols] RESULT+=\"\\n\"+Begin+\" \"+Category+\" \"+title+\" \"+size toplevel = Toplevel() label= Label(toplevel,text=RESULT,height=0,width=100)",
"def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent = parent self.iconbitmap(default='eye.ico') self.geometry(\"500x100\") self.resizable(0, 0) self.initialize() def initialize(self):",
"if __name__ == \"__main__\": app = window(None) app.title('Torrent IP tracker - By <NAME>",
"tkMessageBox import socket import sys import urllib2 import httplib from bs4 import BeautifulSoup",
"B= Tkinter.Button(master=self,text='Check IP',command=self.checkIp) B.pack() self.grid() def work(IP): conn = httplib.HTTPConnection(\"www.iknowwhatyoudownload.com/en/peer/?ip=\"+IP) conn.request(\"GET\",\"/\") response =",
"tracker - By <NAME> v0.1') AppID= \"Torrent Tracker By Houssem. Torrent IP Tracker.V0.1\"",
"rows: cols = tr.findAll('td') Begin,End,Category,title,size=[c.text for c in cols] RESULT+=\"\\n\"+Begin+\" \"+Category+\" \"+title+\" \"+size",
"IP tracker - By <NAME> v0.1') AppID= \"Torrent Tracker By Houssem. Torrent IP",
"BS class window(Tkinter.Tk): Ip_text = '' def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent = parent self.iconbitmap(default='eye.ico')",
"soup.find('tbody') rows = table.findAll('tr') for tr in rows: cols = tr.findAll('td') Begin,End,Category,title,size=[c.text for",
"initialize(self): L = Tkinter.Label(master=self,text=\"Targeted IP:\") L.pack() self.E = Tkinter.Entry(master=self,width=50) self.E.pack() B= Tkinter.Button(master=self,text='Check IP',command=self.checkIp)",
"L = Tkinter.Label(master=self,text=\"Targeted IP:\") L.pack() self.E = Tkinter.Entry(master=self,width=50) self.E.pack() B= Tkinter.Button(master=self,text='Check IP',command=self.checkIp) B.pack()",
"self.E = Tkinter.Entry(master=self,width=50) self.E.pack() B= Tkinter.Button(master=self,text='Check IP',command=self.checkIp) B.pack() self.grid() def work(IP): conn =",
"as BS class window(Tkinter.Tk): Ip_text = '' def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent = parent",
"__init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent = parent self.iconbitmap(default='eye.ico') self.geometry(\"500x100\") self.resizable(0, 0) self.initialize() def initialize(self): L",
"as err: tkMessageBox.showerror('No Internet Connection','You have no Internet Connection') if __name__ == \"__main__\":",
"Tkinter.Button(master=self,text='Check IP',command=self.checkIp) B.pack() self.grid() def work(IP): conn = httplib.HTTPConnection(\"www.iknowwhatyoudownload.com/en/peer/?ip=\"+IP) conn.request(\"GET\",\"/\") response = conn.getresponse()",
"self.parent = parent self.iconbitmap(default='eye.ico') self.geometry(\"500x100\") self.resizable(0, 0) self.initialize() def initialize(self): L = Tkinter.Label(master=self,text=\"Targeted",
"label.pack() print RESULT def checkIp(self): IP=self.E.get() try: urllib2.urlopen('http://172.16.17.32',timeout=1) print IP self.work(IP) except urllib2.URLError",
"= tr.findAll('td') Begin,End,Category,title,size=[c.text for c in cols] RESULT+=\"\\n\"+Begin+\" \"+Category+\" \"+title+\" \"+size toplevel =",
"self.resizable(0, 0) self.initialize() def initialize(self): L = Tkinter.Label(master=self,text=\"Targeted IP:\") L.pack() self.E = Tkinter.Entry(master=self,width=50)",
"= parent self.iconbitmap(default='eye.ico') self.geometry(\"500x100\") self.resizable(0, 0) self.initialize() def initialize(self): L = Tkinter.Label(master=self,text=\"Targeted IP:\")",
"conn.getresponse() data =response.read() soup = BS(data,\"html.parser\") table = soup.find('tbody') rows = table.findAll('tr') for",
"By <NAME> v0.1') AppID= \"Torrent Tracker By Houssem. Torrent IP Tracker.V0.1\" ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(AppID) app.mainloop()",
"Internet Connection') if __name__ == \"__main__\": app = window(None) app.title('Torrent IP tracker -",
"= table.findAll('tr') for tr in rows: cols = tr.findAll('td') Begin,End,Category,title,size=[c.text for c in",
"urllib2.urlopen('http://172.16.17.32',timeout=1) print IP self.work(IP) except urllib2.URLError as err: tkMessageBox.showerror('No Internet Connection','You have no",
"'' def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent = parent self.iconbitmap(default='eye.ico') self.geometry(\"500x100\") self.resizable(0, 0) self.initialize() def",
"self.iconbitmap(default='eye.ico') self.geometry(\"500x100\") self.resizable(0, 0) self.initialize() def initialize(self): L = Tkinter.Label(master=self,text=\"Targeted IP:\") L.pack() self.E",
"import tkMessageBox import socket import sys import urllib2 import httplib from bs4 import",
"socket import sys import urllib2 import httplib from bs4 import BeautifulSoup as BS",
"data =response.read() soup = BS(data,\"html.parser\") table = soup.find('tbody') rows = table.findAll('tr') for tr",
"\"__main__\": app = window(None) app.title('Torrent IP tracker - By <NAME> v0.1') AppID= \"Torrent",
"window(None) app.title('Torrent IP tracker - By <NAME> v0.1') AppID= \"Torrent Tracker By Houssem.",
"toplevel = Toplevel() label= Label(toplevel,text=RESULT,height=0,width=100) label.pack() print RESULT def checkIp(self): IP=self.E.get() try: urllib2.urlopen('http://172.16.17.32',timeout=1)",
"in rows: cols = tr.findAll('td') Begin,End,Category,title,size=[c.text for c in cols] RESULT+=\"\\n\"+Begin+\" \"+Category+\" \"+title+\"",
"Internet Connection','You have no Internet Connection') if __name__ == \"__main__\": app = window(None)",
"import httplib from bs4 import BeautifulSoup as BS class window(Tkinter.Tk): Ip_text = ''",
"=response.read() soup = BS(data,\"html.parser\") table = soup.find('tbody') rows = table.findAll('tr') for tr in",
"Tkinter.Entry(master=self,width=50) self.E.pack() B= Tkinter.Button(master=self,text='Check IP',command=self.checkIp) B.pack() self.grid() def work(IP): conn = httplib.HTTPConnection(\"www.iknowwhatyoudownload.com/en/peer/?ip=\"+IP) conn.request(\"GET\",\"/\")",
"Toplevel() label= Label(toplevel,text=RESULT,height=0,width=100) label.pack() print RESULT def checkIp(self): IP=self.E.get() try: urllib2.urlopen('http://172.16.17.32',timeout=1) print IP",
"IP',command=self.checkIp) B.pack() self.grid() def work(IP): conn = httplib.HTTPConnection(\"www.iknowwhatyoudownload.com/en/peer/?ip=\"+IP) conn.request(\"GET\",\"/\") response = conn.getresponse() data",
"ctypes import tkMessageBox import socket import sys import urllib2 import httplib from bs4",
"bs4 import BeautifulSoup as BS class window(Tkinter.Tk): Ip_text = '' def __init__(self,parent): Tkinter.Tk.__init__(self,parent)",
"\"+Category+\" \"+title+\" \"+size toplevel = Toplevel() label= Label(toplevel,text=RESULT,height=0,width=100) label.pack() print RESULT def checkIp(self):",
"response = conn.getresponse() data =response.read() soup = BS(data,\"html.parser\") table = soup.find('tbody') rows =",
"rows = table.findAll('tr') for tr in rows: cols = tr.findAll('td') Begin,End,Category,title,size=[c.text for c",
"= Toplevel() label= Label(toplevel,text=RESULT,height=0,width=100) label.pack() print RESULT def checkIp(self): IP=self.E.get() try: urllib2.urlopen('http://172.16.17.32',timeout=1) print",
"= window(None) app.title('Torrent IP tracker - By <NAME> v0.1') AppID= \"Torrent Tracker By",
"def checkIp(self): IP=self.E.get() try: urllib2.urlopen('http://172.16.17.32',timeout=1) print IP self.work(IP) except urllib2.URLError as err: tkMessageBox.showerror('No",
"Tkinter import ctypes import tkMessageBox import socket import sys import urllib2 import httplib",
"in cols] RESULT+=\"\\n\"+Begin+\" \"+Category+\" \"+title+\" \"+size toplevel = Toplevel() label= Label(toplevel,text=RESULT,height=0,width=100) label.pack() print",
"import urllib2 import httplib from bs4 import BeautifulSoup as BS class window(Tkinter.Tk): Ip_text",
"B.pack() self.grid() def work(IP): conn = httplib.HTTPConnection(\"www.iknowwhatyoudownload.com/en/peer/?ip=\"+IP) conn.request(\"GET\",\"/\") response = conn.getresponse() data =response.read()",
"= Tkinter.Label(master=self,text=\"Targeted IP:\") L.pack() self.E = Tkinter.Entry(master=self,width=50) self.E.pack() B= Tkinter.Button(master=self,text='Check IP',command=self.checkIp) B.pack() self.grid()",
"import socket import sys import urllib2 import httplib from bs4 import BeautifulSoup as",
"class window(Tkinter.Tk): Ip_text = '' def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent = parent self.iconbitmap(default='eye.ico') self.geometry(\"500x100\")",
"checkIp(self): IP=self.E.get() try: urllib2.urlopen('http://172.16.17.32',timeout=1) print IP self.work(IP) except urllib2.URLError as err: tkMessageBox.showerror('No Internet",
"conn.request(\"GET\",\"/\") response = conn.getresponse() data =response.read() soup = BS(data,\"html.parser\") table = soup.find('tbody') rows",
"self.grid() def work(IP): conn = httplib.HTTPConnection(\"www.iknowwhatyoudownload.com/en/peer/?ip=\"+IP) conn.request(\"GET\",\"/\") response = conn.getresponse() data =response.read() soup",
"no Internet Connection') if __name__ == \"__main__\": app = window(None) app.title('Torrent IP tracker",
"Ip_text = '' def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent = parent self.iconbitmap(default='eye.ico') self.geometry(\"500x100\") self.resizable(0, 0)",
"from bs4 import BeautifulSoup as BS class window(Tkinter.Tk): Ip_text = '' def __init__(self,parent):",
"app = window(None) app.title('Torrent IP tracker - By <NAME> v0.1') AppID= \"Torrent Tracker",
"= Tkinter.Entry(master=self,width=50) self.E.pack() B= Tkinter.Button(master=self,text='Check IP',command=self.checkIp) B.pack() self.grid() def work(IP): conn = httplib.HTTPConnection(\"www.iknowwhatyoudownload.com/en/peer/?ip=\"+IP)",
"BS(data,\"html.parser\") table = soup.find('tbody') rows = table.findAll('tr') for tr in rows: cols =",
"err: tkMessageBox.showerror('No Internet Connection','You have no Internet Connection') if __name__ == \"__main__\": app",
"import ctypes import tkMessageBox import socket import sys import urllib2 import httplib from",
"IP:\") L.pack() self.E = Tkinter.Entry(master=self,width=50) self.E.pack() B= Tkinter.Button(master=self,text='Check IP',command=self.checkIp) B.pack() self.grid() def work(IP):",
"window(Tkinter.Tk): Ip_text = '' def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent = parent self.iconbitmap(default='eye.ico') self.geometry(\"500x100\") self.resizable(0,",
"parent self.iconbitmap(default='eye.ico') self.geometry(\"500x100\") self.resizable(0, 0) self.initialize() def initialize(self): L = Tkinter.Label(master=self,text=\"Targeted IP:\") L.pack()",
"\"+title+\" \"+size toplevel = Toplevel() label= Label(toplevel,text=RESULT,height=0,width=100) label.pack() print RESULT def checkIp(self): IP=self.E.get()",
"Connection') if __name__ == \"__main__\": app = window(None) app.title('Torrent IP tracker - By",
"for tr in rows: cols = tr.findAll('td') Begin,End,Category,title,size=[c.text for c in cols] RESULT+=\"\\n\"+Begin+\"",
"cols = tr.findAll('td') Begin,End,Category,title,size=[c.text for c in cols] RESULT+=\"\\n\"+Begin+\" \"+Category+\" \"+title+\" \"+size toplevel",
"Tkinter.Label(master=self,text=\"Targeted IP:\") L.pack() self.E = Tkinter.Entry(master=self,width=50) self.E.pack() B= Tkinter.Button(master=self,text='Check IP',command=self.checkIp) B.pack() self.grid() def",
"__name__ == \"__main__\": app = window(None) app.title('Torrent IP tracker - By <NAME> v0.1')",
"self.E.pack() B= Tkinter.Button(master=self,text='Check IP',command=self.checkIp) B.pack() self.grid() def work(IP): conn = httplib.HTTPConnection(\"www.iknowwhatyoudownload.com/en/peer/?ip=\"+IP) conn.request(\"GET\",\"/\") response",
"tr in rows: cols = tr.findAll('td') Begin,End,Category,title,size=[c.text for c in cols] RESULT+=\"\\n\"+Begin+\" \"+Category+\"",
"cols] RESULT+=\"\\n\"+Begin+\" \"+Category+\" \"+title+\" \"+size toplevel = Toplevel() label= Label(toplevel,text=RESULT,height=0,width=100) label.pack() print RESULT",
"import Tkinter import ctypes import tkMessageBox import socket import sys import urllib2 import",
"httplib.HTTPConnection(\"www.iknowwhatyoudownload.com/en/peer/?ip=\"+IP) conn.request(\"GET\",\"/\") response = conn.getresponse() data =response.read() soup = BS(data,\"html.parser\") table = soup.find('tbody')",
"Connection','You have no Internet Connection') if __name__ == \"__main__\": app = window(None) app.title('Torrent",
"def initialize(self): L = Tkinter.Label(master=self,text=\"Targeted IP:\") L.pack() self.E = Tkinter.Entry(master=self,width=50) self.E.pack() B= Tkinter.Button(master=self,text='Check",
"= '' def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent = parent self.iconbitmap(default='eye.ico') self.geometry(\"500x100\") self.resizable(0, 0) self.initialize()",
"urllib2 import httplib from bs4 import BeautifulSoup as BS class window(Tkinter.Tk): Ip_text =",
"try: urllib2.urlopen('http://172.16.17.32',timeout=1) print IP self.work(IP) except urllib2.URLError as err: tkMessageBox.showerror('No Internet Connection','You have",
"== \"__main__\": app = window(None) app.title('Torrent IP tracker - By <NAME> v0.1') AppID=",
"RESULT+=\"\\n\"+Begin+\" \"+Category+\" \"+title+\" \"+size toplevel = Toplevel() label= Label(toplevel,text=RESULT,height=0,width=100) label.pack() print RESULT def",
"RESULT def checkIp(self): IP=self.E.get() try: urllib2.urlopen('http://172.16.17.32',timeout=1) print IP self.work(IP) except urllib2.URLError as err:",
"self.initialize() def initialize(self): L = Tkinter.Label(master=self,text=\"Targeted IP:\") L.pack() self.E = Tkinter.Entry(master=self,width=50) self.E.pack() B=",
"work(IP): conn = httplib.HTTPConnection(\"www.iknowwhatyoudownload.com/en/peer/?ip=\"+IP) conn.request(\"GET\",\"/\") response = conn.getresponse() data =response.read() soup = BS(data,\"html.parser\")",
"self.geometry(\"500x100\") self.resizable(0, 0) self.initialize() def initialize(self): L = Tkinter.Label(master=self,text=\"Targeted IP:\") L.pack() self.E ="
] |
[
"}) db.session.add(subview) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) resp = jsonify({'view_id': view.id}) resp.status_code",
"'refresh_time' in request_data.iterkeys(): if not view.check_refresh_time(request_data['refresh_time']): abort(400) for key, value in request_data.iteritems(): if",
"add_view(): view = ViewWrapper.from_dict(json.loads(request.data)) db.session.add(view) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) resp =",
"[view.to_dict() for view in query_all_views(g.current_user.id)]}) @api.route('/view/<id>', methods=['GET']) def get_view(id): view = query_get_view_by_id(id, g.current_user.id)",
"value) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) resp = jsonify(view.to_dict()) resp.status_code = 201",
"@api.route('/view/dynamic/remove', methods=['GET']) def remove_dynamic_view(): view_id = request.args.get('view_id') db.session.delete(query_get_view_by_id(view_id, g.current_user.id)) try: db.session.commit() except IntegrityError:",
"..models import ViewWrapper, View, Subview from ..queries import query_all_views, query_get_view_by_id, query_get_sensor_by_name @api.route('/views', methods=['GET'])",
"db.session.commit() except IntegrityError: db.session.rollback() abort(400) resp = jsonify(view.to_dict()) resp.status_code = 201 return resp",
"10, 'user_id': g.current_user.id }) db.session.add(view) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) subview =",
"= 201 resp.headers['Location'] = url_for('api.get_view', id=view.id) return resp @api.route('/view/<id>', methods=['PUT']) def modify_view(id): view",
"remove_dynamic_view(): view_id = request.args.get('view_id') db.session.delete(query_get_view_by_id(view_id, g.current_user.id)) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) return",
"db.session.rollback() abort(400) resp = jsonify(view.to_dict()) resp.status_code = 201 resp.headers['Location'] = url_for('api.get_view', id=view.id) return",
"return jsonify({'views': [view.to_dict() for view in query_all_views(g.current_user.id)]}) @api.route('/view/<id>', methods=['GET']) def get_view(id): view =",
"subview = Subview.from_dict({ 'sensor_id': sensor_id, 'chartconfig_id': 1, 'view_id': view.id }) db.session.add(subview) try: db.session.commit()",
"remove_view(id): view = query_get_view_by_id(id, g.current_user.id) db.session.delete(view) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) return",
"return resp @api.route('/view/<id>', methods=['PUT']) def modify_view(id): view = query_get_view_by_id(id, g.current_user.id) request_data = json.loads(request.data)",
"view.check_count(request_data['count']): abort(400) if 'refresh_time' in request_data.iterkeys(): if not view.check_refresh_time(request_data['refresh_time']): abort(400) for key, value",
"request from sqlalchemy.exc import IntegrityError from . import api from .. import db",
"import ViewWrapper, View, Subview from ..queries import query_all_views, query_get_view_by_id, query_get_sensor_by_name @api.route('/views', methods=['GET']) def",
"db from ..models import ViewWrapper, View, Subview from ..queries import query_all_views, query_get_view_by_id, query_get_sensor_by_name",
"}) db.session.add(view) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) subview = Subview.from_dict({ 'sensor_id': sensor_id,",
"db.session.commit() except IntegrityError: db.session.rollback() abort(400) subview = Subview.from_dict({ 'sensor_id': sensor_id, 'chartconfig_id': 1, 'view_id':",
"db.session.delete(view) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) return '', 204 @api.route('/view/dynamic/add', methods=['GET']) def",
"if 'count' in request_data.iterkeys(): if not view.check_count(request_data['count']): abort(400) if 'refresh_time' in request_data.iterkeys(): if",
"@api.route('/view/<id>', methods=['GET']) def get_view(id): view = query_get_view_by_id(id, g.current_user.id) return jsonify(view.to_dict()) @api.route('/view', methods=['POST']) def",
"key, value) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) resp = jsonify(view.to_dict()) resp.status_code =",
"try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) return '', 204 @api.route('/view/dynamic/add', methods=['GET']) def add_dynamic_view():",
"@api.route('/view/<id>', methods=['DELETE']) def remove_view(id): view = query_get_view_by_id(id, g.current_user.id) db.session.delete(view) try: db.session.commit() except IntegrityError:",
"'dynamic', 'count': 1, 'refresh_time': 10, 'user_id': g.current_user.id }) db.session.add(view) try: db.session.commit() except IntegrityError:",
"import query_all_views, query_get_view_by_id, query_get_sensor_by_name @api.route('/views', methods=['GET']) def get_views(): return jsonify({'views': [view.to_dict() for view",
"@api.route('/view/<id>', methods=['PUT']) def modify_view(id): view = query_get_view_by_id(id, g.current_user.id) request_data = json.loads(request.data) if 'count'",
"= query_get_view_by_id(id, g.current_user.id) request_data = json.loads(request.data) if 'count' in request_data.iterkeys(): if not view.check_count(request_data['count']):",
"request_data = json.loads(request.data) if 'count' in request_data.iterkeys(): if not view.check_count(request_data['count']): abort(400) if 'refresh_time'",
"resp.headers['Location'] = url_for('api.get_view', id=view.id) return resp @api.route('/view/<id>', methods=['PUT']) def modify_view(id): view = query_get_view_by_id(id,",
"201 resp.headers['Location'] = url_for('api.get_view', id=view.id) return resp @api.route('/view/<id>', methods=['PUT']) def modify_view(id): view =",
"view = query_get_view_by_id(id, g.current_user.id) request_data = json.loads(request.data) if 'count' in request_data.iterkeys(): if not",
"setattr(view, key, value) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) resp = jsonify(view.to_dict()) resp.status_code",
"if not view.check_count(request_data['count']): abort(400) if 'refresh_time' in request_data.iterkeys(): if not view.check_refresh_time(request_data['refresh_time']): abort(400) for",
"'name': 'dynamic', 'count': 1, 'refresh_time': 10, 'user_id': g.current_user.id }) db.session.add(view) try: db.session.commit() except",
"methods=['POST']) def add_view(): view = ViewWrapper.from_dict(json.loads(request.data)) db.session.add(view) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400)",
"request_data.iterkeys(): if not view.check_count(request_data['count']): abort(400) if 'refresh_time' in request_data.iterkeys(): if not view.check_refresh_time(request_data['refresh_time']): abort(400)",
"resp = jsonify(view.to_dict()) resp.status_code = 201 resp.headers['Location'] = url_for('api.get_view', id=view.id) return resp @api.route('/view/<id>',",
"url_for, jsonify, abort, request from sqlalchemy.exc import IntegrityError from . import api from",
"'count' in request_data.iterkeys(): if not view.check_count(request_data['count']): abort(400) if 'refresh_time' in request_data.iterkeys(): if not",
"jsonify({'view_id': view.id}) resp.status_code = 201 return resp @api.route('/view/dynamic/remove', methods=['GET']) def remove_dynamic_view(): view_id =",
"IntegrityError: db.session.rollback() abort(400) return '', 204 @api.route('/view/dynamic/add', methods=['GET']) def add_dynamic_view(): sensor_name = request.args.get('sensor_name')",
"def add_dynamic_view(): sensor_name = request.args.get('sensor_name') sensor_id = query_get_sensor_by_name(sensor_name, g.current_user.id).id view = View.from_dict({ 'name':",
"= 201 return resp @api.route('/view/dynamic/remove', methods=['GET']) def remove_dynamic_view(): view_id = request.args.get('view_id') db.session.delete(query_get_view_by_id(view_id, g.current_user.id))",
"1, 'refresh_time': 10, 'user_id': g.current_user.id }) db.session.add(view) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400)",
"except IntegrityError: db.session.rollback() abort(400) resp = jsonify(view.to_dict()) resp.status_code = 201 resp.headers['Location'] = url_for('api.get_view',",
"import api from .. import db from ..models import ViewWrapper, View, Subview from",
"Subview from ..queries import query_all_views, query_get_view_by_id, query_get_sensor_by_name @api.route('/views', methods=['GET']) def get_views(): return jsonify({'views':",
"view.id }) db.session.add(subview) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) resp = jsonify({'view_id': view.id})",
"from flask import g, url_for, jsonify, abort, request from sqlalchemy.exc import IntegrityError from",
"in query_all_views(g.current_user.id)]}) @api.route('/view/<id>', methods=['GET']) def get_view(id): view = query_get_view_by_id(id, g.current_user.id) return jsonify(view.to_dict()) @api.route('/view',",
"abort(400) subview = Subview.from_dict({ 'sensor_id': sensor_id, 'chartconfig_id': 1, 'view_id': view.id }) db.session.add(subview) try:",
"methods=['GET']) def remove_dynamic_view(): view_id = request.args.get('view_id') db.session.delete(query_get_view_by_id(view_id, g.current_user.id)) try: db.session.commit() except IntegrityError: db.session.rollback()",
"abort(400) resp = jsonify(view.to_dict()) resp.status_code = 201 resp.headers['Location'] = url_for('api.get_view', id=view.id) return resp",
"db.session.rollback() abort(400) return '', 204 @api.route('/view/dynamic/add', methods=['GET']) def add_dynamic_view(): sensor_name = request.args.get('sensor_name') sensor_id",
"query_get_view_by_id(id, g.current_user.id) request_data = json.loads(request.data) if 'count' in request_data.iterkeys(): if not view.check_count(request_data['count']): abort(400)",
"key, value in request_data.iteritems(): if key is not 'id': setattr(view, key, value) try:",
"view.check_refresh_time(request_data['refresh_time']): abort(400) for key, value in request_data.iteritems(): if key is not 'id': setattr(view,",
"not view.check_count(request_data['count']): abort(400) if 'refresh_time' in request_data.iterkeys(): if not view.check_refresh_time(request_data['refresh_time']): abort(400) for key,",
"query_get_sensor_by_name(sensor_name, g.current_user.id).id view = View.from_dict({ 'name': 'dynamic', 'count': 1, 'refresh_time': 10, 'user_id': g.current_user.id",
"methods=['PUT']) def modify_view(id): view = query_get_view_by_id(id, g.current_user.id) request_data = json.loads(request.data) if 'count' in",
"jsonify, abort, request from sqlalchemy.exc import IntegrityError from . import api from ..",
"sensor_name = request.args.get('sensor_name') sensor_id = query_get_sensor_by_name(sensor_name, g.current_user.id).id view = View.from_dict({ 'name': 'dynamic', 'count':",
"methods=['GET']) def get_views(): return jsonify({'views': [view.to_dict() for view in query_all_views(g.current_user.id)]}) @api.route('/view/<id>', methods=['GET']) def",
"except IntegrityError: db.session.rollback() abort(400) resp = jsonify(view.to_dict()) resp.status_code = 201 return resp @api.route('/view/<id>',",
"ViewWrapper, View, Subview from ..queries import query_all_views, query_get_view_by_id, query_get_sensor_by_name @api.route('/views', methods=['GET']) def get_views():",
"'user_id': g.current_user.id }) db.session.add(view) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) subview = Subview.from_dict({",
"1, 'view_id': view.id }) db.session.add(subview) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) resp =",
"= jsonify(view.to_dict()) resp.status_code = 201 resp.headers['Location'] = url_for('api.get_view', id=view.id) return resp @api.route('/view/<id>', methods=['PUT'])",
"jsonify({'views': [view.to_dict() for view in query_all_views(g.current_user.id)]}) @api.route('/view/<id>', methods=['GET']) def get_view(id): view = query_get_view_by_id(id,",
"sensor_id = query_get_sensor_by_name(sensor_name, g.current_user.id).id view = View.from_dict({ 'name': 'dynamic', 'count': 1, 'refresh_time': 10,",
"view = query_get_view_by_id(id, g.current_user.id) db.session.delete(view) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) return '',",
"import db from ..models import ViewWrapper, View, Subview from ..queries import query_all_views, query_get_view_by_id,",
"view = ViewWrapper.from_dict(json.loads(request.data)) db.session.add(view) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) resp = jsonify(view.to_dict())",
"'refresh_time': 10, 'user_id': g.current_user.id }) db.session.add(view) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) subview",
"import json from flask import g, url_for, jsonify, abort, request from sqlalchemy.exc import",
"except IntegrityError: db.session.rollback() abort(400) subview = Subview.from_dict({ 'sensor_id': sensor_id, 'chartconfig_id': 1, 'view_id': view.id",
"abort, request from sqlalchemy.exc import IntegrityError from . import api from .. import",
"from ..queries import query_all_views, query_get_view_by_id, query_get_sensor_by_name @api.route('/views', methods=['GET']) def get_views(): return jsonify({'views': [view.to_dict()",
"g.current_user.id) return jsonify(view.to_dict()) @api.route('/view', methods=['POST']) def add_view(): view = ViewWrapper.from_dict(json.loads(request.data)) db.session.add(view) try: db.session.commit()",
"try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) resp = jsonify(view.to_dict()) resp.status_code = 201 return",
"for key, value in request_data.iteritems(): if key is not 'id': setattr(view, key, value)",
"jsonify(view.to_dict()) resp.status_code = 201 return resp @api.route('/view/<id>', methods=['DELETE']) def remove_view(id): view = query_get_view_by_id(id,",
"@api.route('/view/dynamic/add', methods=['GET']) def add_dynamic_view(): sensor_name = request.args.get('sensor_name') sensor_id = query_get_sensor_by_name(sensor_name, g.current_user.id).id view =",
"get_views(): return jsonify({'views': [view.to_dict() for view in query_all_views(g.current_user.id)]}) @api.route('/view/<id>', methods=['GET']) def get_view(id): view",
"return resp @api.route('/view/<id>', methods=['DELETE']) def remove_view(id): view = query_get_view_by_id(id, g.current_user.id) db.session.delete(view) try: db.session.commit()",
"201 return resp @api.route('/view/<id>', methods=['DELETE']) def remove_view(id): view = query_get_view_by_id(id, g.current_user.id) db.session.delete(view) try:",
"sensor_id, 'chartconfig_id': 1, 'view_id': view.id }) db.session.add(subview) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400)",
"resp.status_code = 201 resp.headers['Location'] = url_for('api.get_view', id=view.id) return resp @api.route('/view/<id>', methods=['PUT']) def modify_view(id):",
"def remove_dynamic_view(): view_id = request.args.get('view_id') db.session.delete(query_get_view_by_id(view_id, g.current_user.id)) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400)",
"view = query_get_view_by_id(id, g.current_user.id) return jsonify(view.to_dict()) @api.route('/view', methods=['POST']) def add_view(): view = ViewWrapper.from_dict(json.loads(request.data))",
"db.session.commit() except IntegrityError: db.session.rollback() abort(400) resp = jsonify(view.to_dict()) resp.status_code = 201 resp.headers['Location'] =",
"in request_data.iterkeys(): if not view.check_refresh_time(request_data['refresh_time']): abort(400) for key, value in request_data.iteritems(): if key",
"view.id}) resp.status_code = 201 return resp @api.route('/view/dynamic/remove', methods=['GET']) def remove_dynamic_view(): view_id = request.args.get('view_id')",
"resp @api.route('/view/<id>', methods=['PUT']) def modify_view(id): view = query_get_view_by_id(id, g.current_user.id) request_data = json.loads(request.data) if",
"abort(400) return '', 204 @api.route('/view/dynamic/add', methods=['GET']) def add_dynamic_view(): sensor_name = request.args.get('sensor_name') sensor_id =",
"= query_get_sensor_by_name(sensor_name, g.current_user.id).id view = View.from_dict({ 'name': 'dynamic', 'count': 1, 'refresh_time': 10, 'user_id':",
"g, url_for, jsonify, abort, request from sqlalchemy.exc import IntegrityError from . import api",
"g.current_user.id) db.session.delete(view) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) return '', 204 @api.route('/view/dynamic/add', methods=['GET'])",
"api from .. import db from ..models import ViewWrapper, View, Subview from ..queries",
"modify_view(id): view = query_get_view_by_id(id, g.current_user.id) request_data = json.loads(request.data) if 'count' in request_data.iterkeys(): if",
"except IntegrityError: db.session.rollback() abort(400) return '', 204 @api.route('/view/dynamic/add', methods=['GET']) def add_dynamic_view(): sensor_name =",
"@api.route('/views', methods=['GET']) def get_views(): return jsonify({'views': [view.to_dict() for view in query_all_views(g.current_user.id)]}) @api.route('/view/<id>', methods=['GET'])",
"db.session.add(view) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) resp = jsonify(view.to_dict()) resp.status_code = 201",
"view in query_all_views(g.current_user.id)]}) @api.route('/view/<id>', methods=['GET']) def get_view(id): view = query_get_view_by_id(id, g.current_user.id) return jsonify(view.to_dict())",
"Subview.from_dict({ 'sensor_id': sensor_id, 'chartconfig_id': 1, 'view_id': view.id }) db.session.add(subview) try: db.session.commit() except IntegrityError:",
".. import db from ..models import ViewWrapper, View, Subview from ..queries import query_all_views,",
"def modify_view(id): view = query_get_view_by_id(id, g.current_user.id) request_data = json.loads(request.data) if 'count' in request_data.iterkeys():",
"not view.check_refresh_time(request_data['refresh_time']): abort(400) for key, value in request_data.iteritems(): if key is not 'id':",
"= jsonify(view.to_dict()) resp.status_code = 201 return resp @api.route('/view/<id>', methods=['DELETE']) def remove_view(id): view =",
"'', 204 @api.route('/view/dynamic/add', methods=['GET']) def add_dynamic_view(): sensor_name = request.args.get('sensor_name') sensor_id = query_get_sensor_by_name(sensor_name, g.current_user.id).id",
"request_data.iteritems(): if key is not 'id': setattr(view, key, value) try: db.session.commit() except IntegrityError:",
"db.session.commit() except IntegrityError: db.session.rollback() abort(400) resp = jsonify({'view_id': view.id}) resp.status_code = 201 return",
"IntegrityError: db.session.rollback() abort(400) resp = jsonify(view.to_dict()) resp.status_code = 201 return resp @api.route('/view/<id>', methods=['DELETE'])",
"db.session.rollback() abort(400) resp = jsonify(view.to_dict()) resp.status_code = 201 return resp @api.route('/view/<id>', methods=['DELETE']) def",
"add_dynamic_view(): sensor_name = request.args.get('sensor_name') sensor_id = query_get_sensor_by_name(sensor_name, g.current_user.id).id view = View.from_dict({ 'name': 'dynamic',",
"try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) subview = Subview.from_dict({ 'sensor_id': sensor_id, 'chartconfig_id': 1,",
"..queries import query_all_views, query_get_view_by_id, query_get_sensor_by_name @api.route('/views', methods=['GET']) def get_views(): return jsonify({'views': [view.to_dict() for",
"abort(400) for key, value in request_data.iteritems(): if key is not 'id': setattr(view, key,",
"View.from_dict({ 'name': 'dynamic', 'count': 1, 'refresh_time': 10, 'user_id': g.current_user.id }) db.session.add(view) try: db.session.commit()",
"g.current_user.id }) db.session.add(view) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) subview = Subview.from_dict({ 'sensor_id':",
"query_get_view_by_id, query_get_sensor_by_name @api.route('/views', methods=['GET']) def get_views(): return jsonify({'views': [view.to_dict() for view in query_all_views(g.current_user.id)]})",
"resp @api.route('/view/dynamic/remove', methods=['GET']) def remove_dynamic_view(): view_id = request.args.get('view_id') db.session.delete(query_get_view_by_id(view_id, g.current_user.id)) try: db.session.commit() except",
"not 'id': setattr(view, key, value) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) resp =",
"from ..models import ViewWrapper, View, Subview from ..queries import query_all_views, query_get_view_by_id, query_get_sensor_by_name @api.route('/views',",
"IntegrityError: db.session.rollback() abort(400) subview = Subview.from_dict({ 'sensor_id': sensor_id, 'chartconfig_id': 1, 'view_id': view.id })",
"request_data.iterkeys(): if not view.check_refresh_time(request_data['refresh_time']): abort(400) for key, value in request_data.iteritems(): if key is",
"try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) resp = jsonify(view.to_dict()) resp.status_code = 201 resp.headers['Location']",
"'view_id': view.id }) db.session.add(subview) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) resp = jsonify({'view_id':",
"query_all_views(g.current_user.id)]}) @api.route('/view/<id>', methods=['GET']) def get_view(id): view = query_get_view_by_id(id, g.current_user.id) return jsonify(view.to_dict()) @api.route('/view', methods=['POST'])",
"db.session.add(subview) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) resp = jsonify({'view_id': view.id}) resp.status_code =",
"= jsonify({'view_id': view.id}) resp.status_code = 201 return resp @api.route('/view/dynamic/remove', methods=['GET']) def remove_dynamic_view(): view_id",
"= json.loads(request.data) if 'count' in request_data.iterkeys(): if not view.check_count(request_data['count']): abort(400) if 'refresh_time' in",
"except IntegrityError: db.session.rollback() abort(400) resp = jsonify({'view_id': view.id}) resp.status_code = 201 return resp",
"= View.from_dict({ 'name': 'dynamic', 'count': 1, 'refresh_time': 10, 'user_id': g.current_user.id }) db.session.add(view) try:",
"json from flask import g, url_for, jsonify, abort, request from sqlalchemy.exc import IntegrityError",
"def get_view(id): view = query_get_view_by_id(id, g.current_user.id) return jsonify(view.to_dict()) @api.route('/view', methods=['POST']) def add_view(): view",
"key is not 'id': setattr(view, key, value) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400)",
"query_all_views, query_get_view_by_id, query_get_sensor_by_name @api.route('/views', methods=['GET']) def get_views(): return jsonify({'views': [view.to_dict() for view in",
"g.current_user.id).id view = View.from_dict({ 'name': 'dynamic', 'count': 1, 'refresh_time': 10, 'user_id': g.current_user.id })",
"methods=['DELETE']) def remove_view(id): view = query_get_view_by_id(id, g.current_user.id) db.session.delete(view) try: db.session.commit() except IntegrityError: db.session.rollback()",
"json.loads(request.data) if 'count' in request_data.iterkeys(): if not view.check_count(request_data['count']): abort(400) if 'refresh_time' in request_data.iterkeys():",
"View, Subview from ..queries import query_all_views, query_get_view_by_id, query_get_sensor_by_name @api.route('/views', methods=['GET']) def get_views(): return",
"methods=['GET']) def get_view(id): view = query_get_view_by_id(id, g.current_user.id) return jsonify(view.to_dict()) @api.route('/view', methods=['POST']) def add_view():",
"IntegrityError: db.session.rollback() abort(400) resp = jsonify({'view_id': view.id}) resp.status_code = 201 return resp @api.route('/view/dynamic/remove',",
"query_get_view_by_id(id, g.current_user.id) db.session.delete(view) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) return '', 204 @api.route('/view/dynamic/add',",
"= Subview.from_dict({ 'sensor_id': sensor_id, 'chartconfig_id': 1, 'view_id': view.id }) db.session.add(subview) try: db.session.commit() except",
"in request_data.iterkeys(): if not view.check_count(request_data['count']): abort(400) if 'refresh_time' in request_data.iterkeys(): if not view.check_refresh_time(request_data['refresh_time']):",
"import IntegrityError from . import api from .. import db from ..models import",
"in request_data.iteritems(): if key is not 'id': setattr(view, key, value) try: db.session.commit() except",
"'chartconfig_id': 1, 'view_id': view.id }) db.session.add(subview) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) resp",
"resp.status_code = 201 return resp @api.route('/view/dynamic/remove', methods=['GET']) def remove_dynamic_view(): view_id = request.args.get('view_id') db.session.delete(query_get_view_by_id(view_id,",
"@api.route('/view', methods=['POST']) def add_view(): view = ViewWrapper.from_dict(json.loads(request.data)) db.session.add(view) try: db.session.commit() except IntegrityError: db.session.rollback()",
"import g, url_for, jsonify, abort, request from sqlalchemy.exc import IntegrityError from . import",
"g.current_user.id) request_data = json.loads(request.data) if 'count' in request_data.iterkeys(): if not view.check_count(request_data['count']): abort(400) if",
"query_get_view_by_id(id, g.current_user.id) return jsonify(view.to_dict()) @api.route('/view', methods=['POST']) def add_view(): view = ViewWrapper.from_dict(json.loads(request.data)) db.session.add(view) try:",
"'sensor_id': sensor_id, 'chartconfig_id': 1, 'view_id': view.id }) db.session.add(subview) try: db.session.commit() except IntegrityError: db.session.rollback()",
"if 'refresh_time' in request_data.iterkeys(): if not view.check_refresh_time(request_data['refresh_time']): abort(400) for key, value in request_data.iteritems():",
"<gh_stars>0 import json from flask import g, url_for, jsonify, abort, request from sqlalchemy.exc",
". import api from .. import db from ..models import ViewWrapper, View, Subview",
"abort(400) resp = jsonify({'view_id': view.id}) resp.status_code = 201 return resp @api.route('/view/dynamic/remove', methods=['GET']) def",
"value in request_data.iteritems(): if key is not 'id': setattr(view, key, value) try: db.session.commit()",
"db.session.add(view) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) subview = Subview.from_dict({ 'sensor_id': sensor_id, 'chartconfig_id':",
"from .. import db from ..models import ViewWrapper, View, Subview from ..queries import",
"view_id = request.args.get('view_id') db.session.delete(query_get_view_by_id(view_id, g.current_user.id)) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) return '',",
"resp = jsonify(view.to_dict()) resp.status_code = 201 return resp @api.route('/view/<id>', methods=['DELETE']) def remove_view(id): view",
"IntegrityError: db.session.rollback() abort(400) resp = jsonify(view.to_dict()) resp.status_code = 201 resp.headers['Location'] = url_for('api.get_view', id=view.id)",
"sqlalchemy.exc import IntegrityError from . import api from .. import db from ..models",
"view = View.from_dict({ 'name': 'dynamic', 'count': 1, 'refresh_time': 10, 'user_id': g.current_user.id }) db.session.add(view)",
"'count': 1, 'refresh_time': 10, 'user_id': g.current_user.id }) db.session.add(view) try: db.session.commit() except IntegrityError: db.session.rollback()",
"request.args.get('sensor_name') sensor_id = query_get_sensor_by_name(sensor_name, g.current_user.id).id view = View.from_dict({ 'name': 'dynamic', 'count': 1, 'refresh_time':",
"return jsonify(view.to_dict()) @api.route('/view', methods=['POST']) def add_view(): view = ViewWrapper.from_dict(json.loads(request.data)) db.session.add(view) try: db.session.commit() except",
"= 201 return resp @api.route('/view/<id>', methods=['DELETE']) def remove_view(id): view = query_get_view_by_id(id, g.current_user.id) db.session.delete(view)",
"db.session.commit() except IntegrityError: db.session.rollback() abort(400) return '', 204 @api.route('/view/dynamic/add', methods=['GET']) def add_dynamic_view(): sensor_name",
"resp = jsonify({'view_id': view.id}) resp.status_code = 201 return resp @api.route('/view/dynamic/remove', methods=['GET']) def remove_dynamic_view():",
"is not 'id': setattr(view, key, value) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) resp",
"jsonify(view.to_dict()) resp.status_code = 201 resp.headers['Location'] = url_for('api.get_view', id=view.id) return resp @api.route('/view/<id>', methods=['PUT']) def",
"methods=['GET']) def add_dynamic_view(): sensor_name = request.args.get('sensor_name') sensor_id = query_get_sensor_by_name(sensor_name, g.current_user.id).id view = View.from_dict({",
"url_for('api.get_view', id=view.id) return resp @api.route('/view/<id>', methods=['PUT']) def modify_view(id): view = query_get_view_by_id(id, g.current_user.id) request_data",
"return resp @api.route('/view/dynamic/remove', methods=['GET']) def remove_dynamic_view(): view_id = request.args.get('view_id') db.session.delete(query_get_view_by_id(view_id, g.current_user.id)) try: db.session.commit()",
"def add_view(): view = ViewWrapper.from_dict(json.loads(request.data)) db.session.add(view) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) resp",
"abort(400) if 'refresh_time' in request_data.iterkeys(): if not view.check_refresh_time(request_data['refresh_time']): abort(400) for key, value in",
"from sqlalchemy.exc import IntegrityError from . import api from .. import db from",
"def get_views(): return jsonify({'views': [view.to_dict() for view in query_all_views(g.current_user.id)]}) @api.route('/view/<id>', methods=['GET']) def get_view(id):",
"query_get_sensor_by_name @api.route('/views', methods=['GET']) def get_views(): return jsonify({'views': [view.to_dict() for view in query_all_views(g.current_user.id)]}) @api.route('/view/<id>',",
"get_view(id): view = query_get_view_by_id(id, g.current_user.id) return jsonify(view.to_dict()) @api.route('/view', methods=['POST']) def add_view(): view =",
"db.session.rollback() abort(400) resp = jsonify({'view_id': view.id}) resp.status_code = 201 return resp @api.route('/view/dynamic/remove', methods=['GET'])",
"jsonify(view.to_dict()) @api.route('/view', methods=['POST']) def add_view(): view = ViewWrapper.from_dict(json.loads(request.data)) db.session.add(view) try: db.session.commit() except IntegrityError:",
"if key is not 'id': setattr(view, key, value) try: db.session.commit() except IntegrityError: db.session.rollback()",
"flask import g, url_for, jsonify, abort, request from sqlalchemy.exc import IntegrityError from .",
"if not view.check_refresh_time(request_data['refresh_time']): abort(400) for key, value in request_data.iteritems(): if key is not",
"try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) resp = jsonify({'view_id': view.id}) resp.status_code = 201",
"db.session.rollback() abort(400) subview = Subview.from_dict({ 'sensor_id': sensor_id, 'chartconfig_id': 1, 'view_id': view.id }) db.session.add(subview)",
"= ViewWrapper.from_dict(json.loads(request.data)) db.session.add(view) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) resp = jsonify(view.to_dict()) resp.status_code",
"= request.args.get('view_id') db.session.delete(query_get_view_by_id(view_id, g.current_user.id)) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) return '', 204",
"abort(400) resp = jsonify(view.to_dict()) resp.status_code = 201 return resp @api.route('/view/<id>', methods=['DELETE']) def remove_view(id):",
"resp.status_code = 201 return resp @api.route('/view/<id>', methods=['DELETE']) def remove_view(id): view = query_get_view_by_id(id, g.current_user.id)",
"= url_for('api.get_view', id=view.id) return resp @api.route('/view/<id>', methods=['PUT']) def modify_view(id): view = query_get_view_by_id(id, g.current_user.id)",
"= query_get_view_by_id(id, g.current_user.id) return jsonify(view.to_dict()) @api.route('/view', methods=['POST']) def add_view(): view = ViewWrapper.from_dict(json.loads(request.data)) db.session.add(view)",
"= query_get_view_by_id(id, g.current_user.id) db.session.delete(view) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) return '', 204",
"201 return resp @api.route('/view/dynamic/remove', methods=['GET']) def remove_dynamic_view(): view_id = request.args.get('view_id') db.session.delete(query_get_view_by_id(view_id, g.current_user.id)) try:",
"= request.args.get('sensor_name') sensor_id = query_get_sensor_by_name(sensor_name, g.current_user.id).id view = View.from_dict({ 'name': 'dynamic', 'count': 1,",
"ViewWrapper.from_dict(json.loads(request.data)) db.session.add(view) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) resp = jsonify(view.to_dict()) resp.status_code =",
"IntegrityError from . import api from .. import db from ..models import ViewWrapper,",
"def remove_view(id): view = query_get_view_by_id(id, g.current_user.id) db.session.delete(view) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400)",
"return '', 204 @api.route('/view/dynamic/add', methods=['GET']) def add_dynamic_view(): sensor_name = request.args.get('sensor_name') sensor_id = query_get_sensor_by_name(sensor_name,",
"for view in query_all_views(g.current_user.id)]}) @api.route('/view/<id>', methods=['GET']) def get_view(id): view = query_get_view_by_id(id, g.current_user.id) return",
"'id': setattr(view, key, value) try: db.session.commit() except IntegrityError: db.session.rollback() abort(400) resp = jsonify(view.to_dict())",
"resp @api.route('/view/<id>', methods=['DELETE']) def remove_view(id): view = query_get_view_by_id(id, g.current_user.id) db.session.delete(view) try: db.session.commit() except",
"from . import api from .. import db from ..models import ViewWrapper, View,",
"id=view.id) return resp @api.route('/view/<id>', methods=['PUT']) def modify_view(id): view = query_get_view_by_id(id, g.current_user.id) request_data =",
"204 @api.route('/view/dynamic/add', methods=['GET']) def add_dynamic_view(): sensor_name = request.args.get('sensor_name') sensor_id = query_get_sensor_by_name(sensor_name, g.current_user.id).id view"
] |
[
"CORS from fileIO import commit_file # importing methods from SQL handler module for",
"API documentation for available API endpoints and methods.\" # defination for Items #",
"# extract item details from request body form param=request.form['details'] print (param) # insert",
"pass id to handler method to remove record commit = remove_item (id) #",
"Resource, Api from flask_cors import CORS from fileIO import commit_file # importing methods",
"the request form parmeter sold_items = json.loads(request.form['sold']) # pass the list to update",
"class Items(Resource): # POST method def post(self): id = request.form['item_id'] # calling get_item",
"CRUD operations from sql_handler import get_item, insert_item, remove_item, sell_item, list_items import json app",
"method def post(self): id = request.form['item_id'] # calling get_item method from database handler",
"to SBN Point of Sale application endpoint. Please refer to API documentation for",
"jsonify({\"status\":commit[0],\"desc\":commit[1]}) class Sale(Resource): def post(self): # get list of items sold form the",
"def get(self): return\"Welcome to SBN Point of Sale application endpoint. Please refer to",
"commit status return jsonify({\"status\":commit[0],\"desc\":commit[1]}) class Sale(Resource): def post(self): # get list of items",
"sql_handler import get_item, insert_item, remove_item, sell_item, list_items import json app = Flask(__name__) CORS(app)",
"in database resp = list_items() # return item list return jsonify(resp) class log_sale(Resource):",
"parmeter sold_items = json.loads(request.form['sold']) # pass the list to update the items in",
"return commit status return jsonify({\"status\":commit[0],\"desc\":commit[1]}) class Sale(Resource): def post(self): # get list of",
"the list to update the items in database through handler resp = sell_item",
"resources routing api.add_resource(HelloWorld, '/') api.add_resource(Items, '/item') api.add_resource(Sale, '/update_item') api.add_resource(get_all, '/get_items') api.add_resource(log_sale, '/log_sale') if",
"POST method def post(self): id = request.form['item_id'] # calling get_item method from database",
"and generating response if item_detail!=[]: resp={ \"id\":item_detail[0], \"name\":item_detail[1], \"category\":item_detail[2], \"total_count\":item_detail[3], \"price\":item_detail[4], \"date_created\":item_detail[5] }",
"get_item method from database handler module item_detail = get_item(id) # checking database response",
"refer to API documentation for available API endpoints and methods.\" # defination for",
"\"id\":item_detail[0], \"name\":item_detail[1], \"category\":item_detail[2], \"total_count\":item_detail[3], \"price\":item_detail[4], \"date_created\":item_detail[5] } else: resp={\"Error\":\"No matching record for given",
"the inventory table in database resp = list_items() # return item list return",
"extract item details from request body form data=request.form['order_details'] # insert item details into",
"method to remove record commit = remove_item (id) # return commit status return",
"body form data=request.form['order_details'] # insert item details into the database response = commit_file(data)",
"return status keyword and description return jsonify({\"status\":commit[0],\"desc\":commit[1]}) # DELETE by ID def delete(self):",
"class log_sale(Resource): def put(self): # extract item details from request body form data=request.form['order_details']",
"# API resources routing api.add_resource(HelloWorld, '/') api.add_resource(Items, '/item') api.add_resource(Sale, '/update_item') api.add_resource(get_all, '/get_items') api.add_resource(log_sale,",
"Please refer to API documentation for available API endpoints and methods.\" # defination",
"form id=request.form['item_id'] # pass id to handler method to remove record commit =",
"json app = Flask(__name__) CORS(app) api=Api(app) # base route defination class HelloWorld(Resource): def",
"item details based on id and add a new item to the DB",
"request form id=request.form['item_id'] # pass id to handler method to remove record commit",
"item_detail!=[]: resp={ \"id\":item_detail[0], \"name\":item_detail[1], \"category\":item_detail[2], \"total_count\":item_detail[3], \"price\":item_detail[4], \"date_created\":item_detail[5] } else: resp={\"Error\":\"No matching record",
"list of items sold form the request form parmeter sold_items = json.loads(request.form['sold']) #",
"# return commit status return jsonify({\"status\":commit[0],\"desc\":commit[1]}) class Sale(Resource): def post(self): # get list",
"table in database resp = list_items() # return item list return jsonify(resp) class",
"database response = commit_file(data) return (response) # API resources routing api.add_resource(HelloWorld, '/') api.add_resource(Items,",
"SQL handler module for CRUD operations from sql_handler import get_item, insert_item, remove_item, sell_item,",
"database resp = list_items() # return item list return jsonify(resp) class log_sale(Resource): def",
"of items sold form the request form parmeter sold_items = json.loads(request.form['sold']) # pass",
"status return jsonify({\"status\":commit[0],\"desc\":commit[1]}) class Sale(Resource): def post(self): # get list of items sold",
"into the database response = commit_file(data) return (response) # API resources routing api.add_resource(HelloWorld,",
"response for given ID and generating response if item_detail!=[]: resp={ \"id\":item_detail[0], \"name\":item_detail[1], \"category\":item_detail[2],",
"resp={ \"id\":item_detail[0], \"name\":item_detail[1], \"category\":item_detail[2], \"total_count\":item_detail[3], \"price\":item_detail[4], \"date_created\":item_detail[5] } else: resp={\"Error\":\"No matching record for",
"handler resp = sell_item (sold_items) # return handler response return jsonify(resp) class get_all(Resource):",
"delete(self): # get item id from request form id=request.form['item_id'] # pass id to",
"to update the items in database through handler resp = sell_item (sold_items) #",
"fileIO import commit_file # importing methods from SQL handler module for CRUD operations",
"= Flask(__name__) CORS(app) api=Api(app) # base route defination class HelloWorld(Resource): def get(self): return\"Welcome",
"item to the DB class Items(Resource): # POST method def post(self): id =",
"# extract item details from request body form data=request.form['order_details'] # insert item details",
"def post(self): id = request.form['item_id'] # calling get_item method from database handler module",
"response if item_detail!=[]: resp={ \"id\":item_detail[0], \"name\":item_detail[1], \"category\":item_detail[2], \"total_count\":item_detail[3], \"price\":item_detail[4], \"date_created\":item_detail[5] } else: resp={\"Error\":\"No",
"json.loads(request.form['sold']) # pass the list to update the items in database through handler",
"matching record for given ID\"} return jsonify(resp) # PUT method def put(self): #",
"sold_items = json.loads(request.form['sold']) # pass the list to update the items in database",
"request body form param=request.form['details'] print (param) # insert item details into the database",
"from flask_restful import Resource, Api from flask_cors import CORS from fileIO import commit_file",
"to the DB class Items(Resource): # POST method def post(self): id = request.form['item_id']",
"calling get_item method from database handler module item_detail = get_item(id) # checking database",
"keyword and description return jsonify({\"status\":commit[0],\"desc\":commit[1]}) # DELETE by ID def delete(self): # get",
"item details from request body form param=request.form['details'] print (param) # insert item details",
"\"total_count\":item_detail[3], \"price\":item_detail[4], \"date_created\":item_detail[5] } else: resp={\"Error\":\"No matching record for given ID\"} return jsonify(resp)",
"list to update the items in database through handler resp = sell_item (sold_items)",
"= sell_item (sold_items) # return handler response return jsonify(resp) class get_all(Resource): def get(self):",
"(response) # API resources routing api.add_resource(HelloWorld, '/') api.add_resource(Items, '/item') api.add_resource(Sale, '/update_item') api.add_resource(get_all, '/get_items')",
"'/') api.add_resource(Items, '/item') api.add_resource(Sale, '/update_item') api.add_resource(get_all, '/get_items') api.add_resource(log_sale, '/log_sale') if __name__ == '__main__':",
"from flask_cors import CORS from fileIO import commit_file # importing methods from SQL",
"\"category\":item_detail[2], \"total_count\":item_detail[3], \"price\":item_detail[4], \"date_created\":item_detail[5] } else: resp={\"Error\":\"No matching record for given ID\"} return",
"body form param=request.form['details'] print (param) # insert item details into the database commit",
"get item details based on id and add a new item to the",
"request from flask_restful import Resource, Api from flask_cors import CORS from fileIO import",
"importing methods from SQL handler module for CRUD operations from sql_handler import get_item,",
"from request body form param=request.form['details'] print (param) # insert item details into the",
"flask_cors import CORS from fileIO import commit_file # importing methods from SQL handler",
"and description return jsonify({\"status\":commit[0],\"desc\":commit[1]}) # DELETE by ID def delete(self): # get item",
"return jsonify(resp) # PUT method def put(self): # extract item details from request",
"sold form the request form parmeter sold_items = json.loads(request.form['sold']) # pass the list",
"record for given ID\"} return jsonify(resp) # PUT method def put(self): # extract",
"return item list return jsonify(resp) class log_sale(Resource): def put(self): # extract item details",
"= commit_file(data) return (response) # API resources routing api.add_resource(HelloWorld, '/') api.add_resource(Items, '/item') api.add_resource(Sale,",
"application endpoint. Please refer to API documentation for available API endpoints and methods.\"",
"defination class HelloWorld(Resource): def get(self): return\"Welcome to SBN Point of Sale application endpoint.",
"# allowes to get item details based on id and add a new",
"routing api.add_resource(HelloWorld, '/') api.add_resource(Items, '/item') api.add_resource(Sale, '/update_item') api.add_resource(get_all, '/get_items') api.add_resource(log_sale, '/log_sale') if __name__",
"list_items import json app = Flask(__name__) CORS(app) api=Api(app) # base route defination class",
"commit_file(data) return (response) # API resources routing api.add_resource(HelloWorld, '/') api.add_resource(Items, '/item') api.add_resource(Sale, '/update_item')",
"request form parmeter sold_items = json.loads(request.form['sold']) # pass the list to update the",
"post(self): id = request.form['item_id'] # calling get_item method from database handler module item_detail",
"available API endpoints and methods.\" # defination for Items # allowes to get",
"records from the inventory table in database resp = list_items() # return item",
"pass the list to update the items in database through handler resp =",
"from the inventory table in database resp = list_items() # return item list",
"api.add_resource(Items, '/item') api.add_resource(Sale, '/update_item') api.add_resource(get_all, '/get_items') api.add_resource(log_sale, '/log_sale') if __name__ == '__main__': app.run(host='0.0.0.0',debug=True)",
"import Resource, Api from flask_cors import CORS from fileIO import commit_file # importing",
"get_item(id) # checking database response for given ID and generating response if item_detail!=[]:",
"details based on id and add a new item to the DB class",
"data=request.form['order_details'] # insert item details into the database response = commit_file(data) return (response)",
"(id) # return commit status return jsonify({\"status\":commit[0],\"desc\":commit[1]}) class Sale(Resource): def post(self): # get",
"else: resp={\"Error\":\"No matching record for given ID\"} return jsonify(resp) # PUT method def",
"methods from SQL handler module for CRUD operations from sql_handler import get_item, insert_item,",
"get(self): return\"Welcome to SBN Point of Sale application endpoint. Please refer to API",
"= remove_item (id) # return commit status return jsonify({\"status\":commit[0],\"desc\":commit[1]}) class Sale(Resource): def post(self):",
"for given ID\"} return jsonify(resp) # PUT method def put(self): # extract item",
"return jsonify(resp) class get_all(Resource): def get(self): # get all records from the inventory",
"ID\"} return jsonify(resp) # PUT method def put(self): # extract item details from",
"# get item id from request form id=request.form['item_id'] # pass id to handler",
"return (response) # API resources routing api.add_resource(HelloWorld, '/') api.add_resource(Items, '/item') api.add_resource(Sale, '/update_item') api.add_resource(get_all,",
"api.add_resource(HelloWorld, '/') api.add_resource(Items, '/item') api.add_resource(Sale, '/update_item') api.add_resource(get_all, '/get_items') api.add_resource(log_sale, '/log_sale') if __name__ ==",
"in database through handler resp = sell_item (sold_items) # return handler response return",
"def delete(self): # get item id from request form id=request.form['item_id'] # pass id",
"a new item to the DB class Items(Resource): # POST method def post(self):",
"remove record commit = remove_item (id) # return commit status return jsonify({\"status\":commit[0],\"desc\":commit[1]}) class",
"= insert_item(json.loads(param)) # return status keyword and description return jsonify({\"status\":commit[0],\"desc\":commit[1]}) # DELETE by",
"form param=request.form['details'] print (param) # insert item details into the database commit =",
"jsonify(resp) # PUT method def put(self): # extract item details from request body",
"def put(self): # extract item details from request body form data=request.form['order_details'] # insert",
"Api from flask_cors import CORS from fileIO import commit_file # importing methods from",
"print (param) # insert item details into the database commit = insert_item(json.loads(param)) #",
"route defination class HelloWorld(Resource): def get(self): return\"Welcome to SBN Point of Sale application",
"methods.\" # defination for Items # allowes to get item details based on",
"description return jsonify({\"status\":commit[0],\"desc\":commit[1]}) # DELETE by ID def delete(self): # get item id",
"(sold_items) # return handler response return jsonify(resp) class get_all(Resource): def get(self): # get",
"= json.loads(request.form['sold']) # pass the list to update the items in database through",
"and add a new item to the DB class Items(Resource): # POST method",
"the database response = commit_file(data) return (response) # API resources routing api.add_resource(HelloWorld, '/')",
"return jsonify(resp) class log_sale(Resource): def put(self): # extract item details from request body",
"insert item details into the database commit = insert_item(json.loads(param)) # return status keyword",
"the DB class Items(Resource): # POST method def post(self): id = request.form['item_id'] #",
"for Items # allowes to get item details based on id and add",
"list return jsonify(resp) class log_sale(Resource): def put(self): # extract item details from request",
"return\"Welcome to SBN Point of Sale application endpoint. Please refer to API documentation",
"item list return jsonify(resp) class log_sale(Resource): def put(self): # extract item details from",
"post(self): # get list of items sold form the request form parmeter sold_items",
"add a new item to the DB class Items(Resource): # POST method def",
"# get list of items sold form the request form parmeter sold_items =",
"from flask import Flask, jsonify, request from flask_restful import Resource, Api from flask_cors",
"jsonify(resp) class get_all(Resource): def get(self): # get all records from the inventory table",
"base route defination class HelloWorld(Resource): def get(self): return\"Welcome to SBN Point of Sale",
"on id and add a new item to the DB class Items(Resource): #",
"# PUT method def put(self): # extract item details from request body form",
"details into the database commit = insert_item(json.loads(param)) # return status keyword and description",
"for given ID and generating response if item_detail!=[]: resp={ \"id\":item_detail[0], \"name\":item_detail[1], \"category\":item_detail[2], \"total_count\":item_detail[3],",
"module for CRUD operations from sql_handler import get_item, insert_item, remove_item, sell_item, list_items import",
"SBN Point of Sale application endpoint. Please refer to API documentation for available",
"to get item details based on id and add a new item to",
"CORS(app) api=Api(app) # base route defination class HelloWorld(Resource): def get(self): return\"Welcome to SBN",
"get_all(Resource): def get(self): # get all records from the inventory table in database",
"items sold form the request form parmeter sold_items = json.loads(request.form['sold']) # pass the",
"param=request.form['details'] print (param) # insert item details into the database commit = insert_item(json.loads(param))",
"ID and generating response if item_detail!=[]: resp={ \"id\":item_detail[0], \"name\":item_detail[1], \"category\":item_detail[2], \"total_count\":item_detail[3], \"price\":item_detail[4], \"date_created\":item_detail[5]",
"by ID def delete(self): # get item id from request form id=request.form['item_id'] #",
"record commit = remove_item (id) # return commit status return jsonify({\"status\":commit[0],\"desc\":commit[1]}) class Sale(Resource):",
"class get_all(Resource): def get(self): # get all records from the inventory table in",
"endpoints and methods.\" # defination for Items # allowes to get item details",
"get all records from the inventory table in database resp = list_items() #",
"id from request form id=request.form['item_id'] # pass id to handler method to remove",
"to handler method to remove record commit = remove_item (id) # return commit",
"get_item, insert_item, remove_item, sell_item, list_items import json app = Flask(__name__) CORS(app) api=Api(app) #",
"based on id and add a new item to the DB class Items(Resource):",
"= request.form['item_id'] # calling get_item method from database handler module item_detail = get_item(id)",
"remove_item (id) # return commit status return jsonify({\"status\":commit[0],\"desc\":commit[1]}) class Sale(Resource): def post(self): #",
"details into the database response = commit_file(data) return (response) # API resources routing",
"\"name\":item_detail[1], \"category\":item_detail[2], \"total_count\":item_detail[3], \"price\":item_detail[4], \"date_created\":item_detail[5] } else: resp={\"Error\":\"No matching record for given ID\"}",
"database response for given ID and generating response if item_detail!=[]: resp={ \"id\":item_detail[0], \"name\":item_detail[1],",
"# pass id to handler method to remove record commit = remove_item (id)",
"Flask(__name__) CORS(app) api=Api(app) # base route defination class HelloWorld(Resource): def get(self): return\"Welcome to",
"sell_item (sold_items) # return handler response return jsonify(resp) class get_all(Resource): def get(self): #",
"log_sale(Resource): def put(self): # extract item details from request body form data=request.form['order_details'] #",
"# checking database response for given ID and generating response if item_detail!=[]: resp={",
"item id from request form id=request.form['item_id'] # pass id to handler method to",
"from request body form data=request.form['order_details'] # insert item details into the database response",
"return handler response return jsonify(resp) class get_all(Resource): def get(self): # get all records",
"and methods.\" # defination for Items # allowes to get item details based",
"from request form id=request.form['item_id'] # pass id to handler method to remove record",
"form parmeter sold_items = json.loads(request.form['sold']) # pass the list to update the items",
"import CORS from fileIO import commit_file # importing methods from SQL handler module",
"for CRUD operations from sql_handler import get_item, insert_item, remove_item, sell_item, list_items import json",
"form data=request.form['order_details'] # insert item details into the database response = commit_file(data) return",
"get item id from request form id=request.form['item_id'] # pass id to handler method",
"api=Api(app) # base route defination class HelloWorld(Resource): def get(self): return\"Welcome to SBN Point",
"Point of Sale application endpoint. Please refer to API documentation for available API",
"def get(self): # get all records from the inventory table in database resp",
"# POST method def post(self): id = request.form['item_id'] # calling get_item method from",
"API endpoints and methods.\" # defination for Items # allowes to get item",
"(param) # insert item details into the database commit = insert_item(json.loads(param)) # return",
"checking database response for given ID and generating response if item_detail!=[]: resp={ \"id\":item_detail[0],",
"jsonify({\"status\":commit[0],\"desc\":commit[1]}) # DELETE by ID def delete(self): # get item id from request",
"return jsonify({\"status\":commit[0],\"desc\":commit[1]}) class Sale(Resource): def post(self): # get list of items sold form",
"remove_item, sell_item, list_items import json app = Flask(__name__) CORS(app) api=Api(app) # base route",
"documentation for available API endpoints and methods.\" # defination for Items # allowes",
"id = request.form['item_id'] # calling get_item method from database handler module item_detail =",
"form the request form parmeter sold_items = json.loads(request.form['sold']) # pass the list to",
"class HelloWorld(Resource): def get(self): return\"Welcome to SBN Point of Sale application endpoint. Please",
"of Sale application endpoint. Please refer to API documentation for available API endpoints",
"# pass the list to update the items in database through handler resp",
"# return item list return jsonify(resp) class log_sale(Resource): def put(self): # extract item",
"API resources routing api.add_resource(HelloWorld, '/') api.add_resource(Items, '/item') api.add_resource(Sale, '/update_item') api.add_resource(get_all, '/get_items') api.add_resource(log_sale, '/log_sale')",
"details from request body form param=request.form['details'] print (param) # insert item details into",
"commit_file # importing methods from SQL handler module for CRUD operations from sql_handler",
"# return status keyword and description return jsonify({\"status\":commit[0],\"desc\":commit[1]}) # DELETE by ID def",
"\"price\":item_detail[4], \"date_created\":item_detail[5] } else: resp={\"Error\":\"No matching record for given ID\"} return jsonify(resp) #",
"the database commit = insert_item(json.loads(param)) # return status keyword and description return jsonify({\"status\":commit[0],\"desc\":commit[1]})",
"put(self): # extract item details from request body form data=request.form['order_details'] # insert item",
"to API documentation for available API endpoints and methods.\" # defination for Items",
"request body form data=request.form['order_details'] # insert item details into the database response =",
"new item to the DB class Items(Resource): # POST method def post(self): id",
"import get_item, insert_item, remove_item, sell_item, list_items import json app = Flask(__name__) CORS(app) api=Api(app)",
"resp = list_items() # return item list return jsonify(resp) class log_sale(Resource): def put(self):",
"= get_item(id) # checking database response for given ID and generating response if",
"database commit = insert_item(json.loads(param)) # return status keyword and description return jsonify({\"status\":commit[0],\"desc\":commit[1]}) #",
"resp = sell_item (sold_items) # return handler response return jsonify(resp) class get_all(Resource): def",
"insert item details into the database response = commit_file(data) return (response) # API",
"operations from sql_handler import get_item, insert_item, remove_item, sell_item, list_items import json app =",
"item details from request body form data=request.form['order_details'] # insert item details into the",
"details from request body form data=request.form['order_details'] # insert item details into the database",
"DELETE by ID def delete(self): # get item id from request form id=request.form['item_id']",
"for available API endpoints and methods.\" # defination for Items # allowes to",
"Sale application endpoint. Please refer to API documentation for available API endpoints and",
"Items(Resource): # POST method def post(self): id = request.form['item_id'] # calling get_item method",
"item details into the database commit = insert_item(json.loads(param)) # return status keyword and",
"module item_detail = get_item(id) # checking database response for given ID and generating",
"insert_item, remove_item, sell_item, list_items import json app = Flask(__name__) CORS(app) api=Api(app) # base",
"from fileIO import commit_file # importing methods from SQL handler module for CRUD",
"put(self): # extract item details from request body form param=request.form['details'] print (param) #",
"through handler resp = sell_item (sold_items) # return handler response return jsonify(resp) class",
"update the items in database through handler resp = sell_item (sold_items) # return",
"flask import Flask, jsonify, request from flask_restful import Resource, Api from flask_cors import",
"<reponame>Dkadariya/SBN_pos_server from flask import Flask, jsonify, request from flask_restful import Resource, Api from",
"id and add a new item to the DB class Items(Resource): # POST",
"generating response if item_detail!=[]: resp={ \"id\":item_detail[0], \"name\":item_detail[1], \"category\":item_detail[2], \"total_count\":item_detail[3], \"price\":item_detail[4], \"date_created\":item_detail[5] } else:",
"\"date_created\":item_detail[5] } else: resp={\"Error\":\"No matching record for given ID\"} return jsonify(resp) # PUT",
"# DELETE by ID def delete(self): # get item id from request form",
"PUT method def put(self): # extract item details from request body form param=request.form['details']",
"status keyword and description return jsonify({\"status\":commit[0],\"desc\":commit[1]}) # DELETE by ID def delete(self): #",
"from sql_handler import get_item, insert_item, remove_item, sell_item, list_items import json app = Flask(__name__)",
"return jsonify({\"status\":commit[0],\"desc\":commit[1]}) # DELETE by ID def delete(self): # get item id from",
"def post(self): # get list of items sold form the request form parmeter",
"the items in database through handler resp = sell_item (sold_items) # return handler",
"def put(self): # extract item details from request body form param=request.form['details'] print (param)",
"extract item details from request body form param=request.form['details'] print (param) # insert item",
"class Sale(Resource): def post(self): # get list of items sold form the request",
"jsonify(resp) class log_sale(Resource): def put(self): # extract item details from request body form",
"# defination for Items # allowes to get item details based on id",
"if item_detail!=[]: resp={ \"id\":item_detail[0], \"name\":item_detail[1], \"category\":item_detail[2], \"total_count\":item_detail[3], \"price\":item_detail[4], \"date_created\":item_detail[5] } else: resp={\"Error\":\"No matching",
"flask_restful import Resource, Api from flask_cors import CORS from fileIO import commit_file #",
"database handler module item_detail = get_item(id) # checking database response for given ID",
"handler module item_detail = get_item(id) # checking database response for given ID and",
"to remove record commit = remove_item (id) # return commit status return jsonify({\"status\":commit[0],\"desc\":commit[1]})",
"sell_item, list_items import json app = Flask(__name__) CORS(app) api=Api(app) # base route defination",
"# insert item details into the database commit = insert_item(json.loads(param)) # return status",
"app = Flask(__name__) CORS(app) api=Api(app) # base route defination class HelloWorld(Resource): def get(self):",
"item_detail = get_item(id) # checking database response for given ID and generating response",
"allowes to get item details based on id and add a new item",
"all records from the inventory table in database resp = list_items() # return",
"from SQL handler module for CRUD operations from sql_handler import get_item, insert_item, remove_item,",
"inventory table in database resp = list_items() # return item list return jsonify(resp)",
"commit = insert_item(json.loads(param)) # return status keyword and description return jsonify({\"status\":commit[0],\"desc\":commit[1]}) # DELETE",
"import Flask, jsonify, request from flask_restful import Resource, Api from flask_cors import CORS",
"# importing methods from SQL handler module for CRUD operations from sql_handler import",
"request.form['item_id'] # calling get_item method from database handler module item_detail = get_item(id) #",
"handler module for CRUD operations from sql_handler import get_item, insert_item, remove_item, sell_item, list_items",
"get list of items sold form the request form parmeter sold_items = json.loads(request.form['sold'])",
"handler method to remove record commit = remove_item (id) # return commit status",
"import commit_file # importing methods from SQL handler module for CRUD operations from",
"= list_items() # return item list return jsonify(resp) class log_sale(Resource): def put(self): #",
"defination for Items # allowes to get item details based on id and",
"DB class Items(Resource): # POST method def post(self): id = request.form['item_id'] # calling",
"endpoint. Please refer to API documentation for available API endpoints and methods.\" #",
"# base route defination class HelloWorld(Resource): def get(self): return\"Welcome to SBN Point of",
"id=request.form['item_id'] # pass id to handler method to remove record commit = remove_item",
"commit = remove_item (id) # return commit status return jsonify({\"status\":commit[0],\"desc\":commit[1]}) class Sale(Resource): def",
"response = commit_file(data) return (response) # API resources routing api.add_resource(HelloWorld, '/') api.add_resource(Items, '/item')",
"# return handler response return jsonify(resp) class get_all(Resource): def get(self): # get all",
"} else: resp={\"Error\":\"No matching record for given ID\"} return jsonify(resp) # PUT method",
"Flask, jsonify, request from flask_restful import Resource, Api from flask_cors import CORS from",
"get(self): # get all records from the inventory table in database resp =",
"# get all records from the inventory table in database resp = list_items()",
"# calling get_item method from database handler module item_detail = get_item(id) # checking",
"insert_item(json.loads(param)) # return status keyword and description return jsonify({\"status\":commit[0],\"desc\":commit[1]}) # DELETE by ID",
"items in database through handler resp = sell_item (sold_items) # return handler response",
"list_items() # return item list return jsonify(resp) class log_sale(Resource): def put(self): # extract",
"given ID\"} return jsonify(resp) # PUT method def put(self): # extract item details",
"method from database handler module item_detail = get_item(id) # checking database response for",
"given ID and generating response if item_detail!=[]: resp={ \"id\":item_detail[0], \"name\":item_detail[1], \"category\":item_detail[2], \"total_count\":item_detail[3], \"price\":item_detail[4],",
"resp={\"Error\":\"No matching record for given ID\"} return jsonify(resp) # PUT method def put(self):",
"into the database commit = insert_item(json.loads(param)) # return status keyword and description return",
"jsonify, request from flask_restful import Resource, Api from flask_cors import CORS from fileIO",
"from database handler module item_detail = get_item(id) # checking database response for given",
"ID def delete(self): # get item id from request form id=request.form['item_id'] # pass",
"id to handler method to remove record commit = remove_item (id) # return",
"Sale(Resource): def post(self): # get list of items sold form the request form",
"method def put(self): # extract item details from request body form param=request.form['details'] print",
"HelloWorld(Resource): def get(self): return\"Welcome to SBN Point of Sale application endpoint. Please refer",
"response return jsonify(resp) class get_all(Resource): def get(self): # get all records from the",
"# insert item details into the database response = commit_file(data) return (response) #",
"handler response return jsonify(resp) class get_all(Resource): def get(self): # get all records from",
"Items # allowes to get item details based on id and add a",
"import json app = Flask(__name__) CORS(app) api=Api(app) # base route defination class HelloWorld(Resource):",
"item details into the database response = commit_file(data) return (response) # API resources",
"database through handler resp = sell_item (sold_items) # return handler response return jsonify(resp)"
] |
[
"= color_space[:,2].tolist() # Publish ColorSpace-message self.pub_color_space.publish(color_space_msg) class Pointfinder(): def __init__(self, debug_printer, threshold, kernel_radius):",
"Set params self.queue_max_size = vision_config['dynamic_color_space_queue_max_size'] self.color_value_queue = deque(maxlen=self.queue_max_size) self.pointfinder = Pointfinder( self.debug_printer, vision_config['dynamic_color_space_threshold'],",
"rospkg.RosPack() self.package_path = rospack.get_path('bitbots_vision') rospy.init_node('bitbots_dynamic_color_space') rospy.loginfo('Initializing dynamic color-space...') self.bridge = CvBridge() # Init",
"(np.array, np.array, np.array) -> np.array \"\"\" This method filters a given list of",
"dtype=np.int32) return colors return np.array([[]]) def queue_to_color_space(self, queue): # type: (deque) -> np.array",
"colors under the field boundary \"\"\" # Calls a function to calculate the",
"to their position relative to the field boundary. Only colors that occur under",
"self.vision_config = {} # Subscribe to 'vision_config'-message # The message topic name MUST",
"colors values from a given image at pixel coordinates from given list. :param",
"color code) :param np.array input_matrix: serialized colors :return: original colors with 3 channels",
"a whitelist of allowed colors using the original image and the field-boundary-mask. :param",
"self.threshold = threshold self.kernel_radius = kernel_radius self.kernel_edge_size = 2 * self.kernel_radius + 1",
"1], 256) \\ + input_matrix[:, 2], dtype=np.int32) def deserialize(self, input_matrix): # type: (np.array)",
"coordinates \"\"\" # Create list of color values from image at given coordinates",
"of the count of the matrix elements # In case the value of",
"method handles the processing of an Image-message. New colors are calculated, appended to",
"node to better recognize the field color. DynamicColorSpace is able to calculate dynamically",
"self.image_callback, queue_size=vision_config['ROS_img_queue_size'], tcp_nodelay=True, buff_size=60000000) # https://github.com/ros/ros_comm/issues/536 self.vision_config = vision_config def image_callback(self, image_msg): #",
"space via ColorSpace-message. :param Image image_msg: 'image_raw'-message :return: None \"\"\" # Get color",
"the queue gets to large, even when the size is limeted to 1.",
"type: (np.array, np.array) -> np.array \"\"\" Returns array of unique colors values from",
"the image return np.unique(serialized_img, axis=0) def serialize(self, input_matrix): # type: (np.array) -> np.array",
"# Stack every color space in the queue for new_color_value_list in queue: color_space",
"unique colors \"\"\" # Simplifies the handling by merging the 3 color channels",
"image at pixel coordinates \"\"\" # Create list of color values from image",
"class Heuristic: def __init__(self, debug_printer): # type: (DebugPrinter) -> None \"\"\" Filters new",
"mask partitions. :param np.array image: image :param np.array mask: field-boundary-mask :return np.array: colors",
":return: None \"\"\" # Init params self.debug_printer = debug_printer self.threshold = threshold self.kernel_radius",
"a set and removing duplicated colors color_set = set(color_list) # Generates whitelist whitelist",
"dequeue queue: queue of array of color values :return np.array: color space \"\"\"",
"dynamically calculated color values. Those values were filtered by the heuristic. :param np.array",
"to the 'vision_config'-message. This node publishes ColorSpace-messages. Initiating 'bitbots_dynamic_color_space' node. :return: None \"\"\"",
"debug_printer: Debug-printer :return: None \"\"\" self.debug_printer = debug_printer def run(self, color_list, image, mask):",
"contains all colors from the queue return color_space def publish(self, image_msg): # type:",
"return unique_colors def get_new_dynamic_colors(self, image): # type: (np.array) -> np.array \"\"\" Returns array",
"int(image.size / 3), 3))[0]) # Returns unique colors in the image return np.unique(serialized_img,",
":param Image image_msg: new Image-message from Image-message subscriber :return: None \"\"\" # Turn",
"Handle config changes. This callback is delayed (about 30 seconds) after changes through",
"'pub_color_space'): self.pub_color_space.unregister() self.pub_color_space = rospy.Publisher( vision_config['ROS_dynamic_color_space_msg_topic'], ColorSpace, queue_size=1) # Set Color- and FieldBoundaryDetector",
"empty color space color_space = np.array([]).reshape(0,3) # Stack every color space in the",
"vision.py self.sub_vision_config_msg = rospy.Subscriber( 'vision_config', Config, self.vision_config_callback, queue_size=1, tcp_nodelay=True) rospy.spin() def vision_config_callback(self, msg):",
"Image-message. New colors are calculated, appended to queue and published. :param Image image_msg:",
"pixel coordinates :return np.array: array of unique color values from image at pixel",
"all colors from the queue. :param dequeue queue: queue of array of color",
"def publish(self, image_msg): # type: (Image) -> None \"\"\" Publishes the current color",
"Resolves the serialization of colors into different channels. (Like a HTML color code)",
"whitelisted values color_set = color_set.intersection(whitelist) # Restructures the color channels return self.deserialize(np.array(list(color_set))) def",
"# type: (DebugPrinter, float, int) -> None \"\"\" Pointfinder is used to find",
":param np.array input_matrix: list of colors values with 3 channels :return: list of",
"a ROS node, that is used by the vision node to better recognize",
"np.array( np.multiply(input_matrix[:, 0], 256 ** 2) \\ + np.multiply(input_matrix[:, 1], 256) \\ +",
"image: image :return np.array: array of new dynamic color values \"\"\" # Masks",
"else: rospy.logwarn('Dynamic color space turned OFF.') # Set publisher of ColorSpace-messages if 'ROS_dynamic_color_space_msg_topic'",
"image_msg): # type: (Image) -> None \"\"\" This method is called by the",
"msg): # type: (Config) -> None \"\"\" This method is called by the",
"None \"\"\" # Converting the ROS image message to CV2-image image = self.bridge.imgmsg_to_cv2(image_msg,",
"Init params self.vision_config = {} # Subscribe to 'vision_config'-message # The message topic",
"# Set value of the center element of the matrix to the negative",
"under the field boundary \"\"\" # Calls a function to calculate the number",
"used_by_dyn_color_detector=True) # Reset queue if hasattr(self, 'color_value_queue'): self.color_value_queue.clear() # Set params self.queue_max_size =",
"space turned OFF.') # Set publisher of ColorSpace-messages if 'ROS_dynamic_color_space_msg_topic' not in self.vision_config",
"\\ + np.multiply(input_matrix[:, 1], 256) \\ + input_matrix[:, 2], dtype=np.int32) def deserialize(self, input_matrix):",
"= debug_printer self.threshold = threshold self.kernel_radius = kernel_radius self.kernel_edge_size = 2 * self.kernel_radius",
"Get mask from field_boundary detector self.field_boundary_detector.set_image(image) mask = self.field_boundary_detector.get_mask() if mask is not",
"= self.pointfinder.get_coordinates_of_color_candidates(mask_image) # Get unique color values from the candidate pixels color_candidates =",
"color_candidates = self.get_unique_color_values(image, pixel_coordinates) # Filters the colors using the heuristic. colors =",
"image :param np.array mask: field-boundary-mask :return set: whitelist \"\"\" # Generates whitelist colors_over_field_boundary,",
"bitbots_msgs.msg import ColorSpace, Config from bitbots_vision.vision_modules import field_boundary, color, debug, evaluator class DynamicColorSpace:",
"position relative to the field boundary. Only colors that occur under the field",
"\"\"\" This method handles the processing of an Image-message. New colors are calculated,",
"partitions. :param np.array image: image :param np.array mask: field-boundary-mask :return np.array: colors over",
"vision_config = yaml.load(msg.data) self.debug_printer = debug.DebugPrinter( debug_classes=debug.DebugPrinter.generate_debug_class_list_from_string( vision_config['vision_debug_printer_classes'])) self.runtime_evaluator = evaluator.RuntimeEvaluator(None) # Print",
"channels of a list of colors in an single channel. (Like a HTML",
"color space colors according to their position relative to the field boundary. Only",
"of pixel :return: None \"\"\" # Init params self.debug_printer = debug_printer self.threshold =",
"np.array mask: binary field-boundary-mask :return np.array: filtered list of colors \"\"\" # Simplifies",
"an empty color space color_space = np.array([]).reshape(0,3) # Stack every color space in",
":param np.array image: image :param np.array mask: field-boundary-mask :return set: whitelist \"\"\" #",
"unique colors in the image return np.unique(serialized_img, axis=0) def serialize(self, input_matrix): # type:",
"higher true-color/ false-color ratio as threshold in their surrounding in masked image. :param",
"space mask_image = self.color_detector.mask_image(image) # Get mask from field_boundary detector self.field_boundary_detector.set_image(image) mask =",
"serialized colors :return: original colors with 3 channels \"\"\" new_matrix = np.zeros((input_matrix.size, 3))",
"colors over the field boundary :return np.array: colors under the field boundary \"\"\"",
"the field-boundary-mask. :param np.array image: image :param np.array mask: field-boundary-mask :return set: whitelist",
"HTML color code) :param np.array input_matrix: list of colors values with 3 channels",
"rospy import rospkg import numpy as np from cv_bridge import CvBridge from collections",
"image. :param np.array masked_image: masked image :return np.array: list of indices \"\"\" #",
"debug-printer :param float threshold: necessary amount of previously detected color in percentage :param",
"color space, if parameter of config is false if 'dynamic_color_space_active' not in self.vision_config",
"dynamic color space, if parameter of config is false if 'dynamic_color_space_active' not in",
"queue_size=vision_config['ROS_img_queue_size'], tcp_nodelay=True, buff_size=60000000) # https://github.com/ros/ros_comm/issues/536 self.vision_config = vision_config def image_callback(self, image_msg): # type:",
"self.get_unique_color_values(image, pixel_coordinates) # Filters the colors using the heuristic. colors = np.array(self.heuristic.run(color_candidates, image,",
"array of all queue elements stacked, which contains all colors from the queue.",
"self.unique_colors_for_partitions(image, mask) return set(colors_under_field_boundary) - set(colors_over_field_boundary) def unique_colors_for_partitions(self, image, mask): # type: (np.array,",
"a list of colors in an single channel. (Like a HTML color code)",
"Normalizes the masked image to values of 1 or 0 normalized_image = np.floor_divide(masked_image,",
"= color_space[:,0].tolist() color_space_msg.green = color_space[:,1].tolist() color_space_msg.red = color_space[:,2].tolist() # Publish ColorSpace-message self.pub_color_space.publish(color_space_msg) class",
"appended to queue and published. :param Image image_msg: Image-message :return: None \"\"\" #",
"# np.unique requires list with at least one element if colors.size > 0:",
"necessary amount of previously detected color in percentage :param int kernel_radius: radius surrounding",
"\"\"\" Resolves the serialization of colors into different channels. (Like a HTML color",
"pixel_coordinates = self.pointfinder.get_coordinates_of_color_candidates(mask_image) # Get unique color values from the candidate pixels color_candidates",
"debug_printer def run(self, color_list, image, mask): # type: (np.array, np.array, np.array) -> np.array",
"self.vision_config = vision_config def image_callback(self, image_msg): # type: (Image) -> None \"\"\" This",
"color values from image at given coordinates colors = image[coordinate_list[0], coordinate_list[1]] # np.unique",
"self.debug_printer, vision_config['dynamic_color_space_threshold'], vision_config['dynamic_color_space_kernel_radius']) self.heuristic = Heuristic(self.debug_printer) # Subscribe to Image-message if 'ROS_img_msg_topic' not",
"space from queue color_space = self.queue_to_color_space(self.color_value_queue) # Create ColorSpace-message color_space_msg = ColorSpace() color_space_msg.header.frame_id",
"of 1 or 0 normalized_image = np.floor_divide(masked_image, 255, dtype=np.int16) # Calculates the count",
"None \"\"\" # Init params self.debug_printer = debug_printer self.threshold = threshold self.kernel_radius =",
"of all colors in the image return (self.get_unique_colors(cv2.bitwise_and(image, image, mask=255 - mask)), self.get_unique_colors(cv2.bitwise_and(image,",
"self.queue_max_size = vision_config['dynamic_color_space_queue_max_size'] self.color_value_queue = deque(maxlen=self.queue_max_size) self.pointfinder = Pointfinder( self.debug_printer, vision_config['dynamic_color_space_threshold'], vision_config['dynamic_color_space_kernel_radius']) self.heuristic",
"# Defines kernel # Init kernel as M x M matrix of ONEs",
"/ 2), int(np.size(self.kernel, 1) / 2)] = - self.kernel.size def get_coordinates_of_color_candidates(self, masked_image): #",
"= np.ones((self.kernel_edge_size, self.kernel_edge_size)) # Set value of the center element of the matrix",
"image: image :return np.array: unique colors \"\"\" # Simplifies the handling by merging",
"of occurrences of all colors in the image return (self.get_unique_colors(cv2.bitwise_and(image, image, mask=255 -",
"msg.data vision_config = yaml.load(msg.data) self.debug_printer = debug.DebugPrinter( debug_classes=debug.DebugPrinter.generate_debug_class_list_from_string( vision_config['vision_debug_printer_classes'])) self.runtime_evaluator = evaluator.RuntimeEvaluator(None) #",
"MUST be the same as in the config publisher in vision.py self.sub_vision_config_msg =",
"from the candidate pixels color_candidates = self.get_unique_color_values(image, pixel_coordinates) # Filters the colors using",
"color values :return np.array: color space \"\"\" # Initializes an empty color space",
"FieldBoundaryDetector self.color_detector = color.DynamicPixelListColorDetector( self.debug_printer, self.package_path, vision_config) self.field_boundary_detector = field_boundary.FieldBoundaryDetector( self.color_detector, vision_config, self.debug_printer,",
"input_matrix: list of colors values with 3 channels :return: list of serialized colors",
"\"\"\" # Normalizes the masked image to values of 1 or 0 normalized_image",
"if mask is not None: # Get array of pixel coordinates of color",
"self.threshold * (self.kernel.size - 1))) class Heuristic: def __init__(self, debug_printer): # type: (DebugPrinter)",
"image_msg): # type: (Image) -> None \"\"\" This method handles the processing of",
"# Filters the colors using the heuristic. colors = np.array(self.heuristic.run(color_candidates, image, mask), dtype=np.int32)",
"of serialized colors \"\"\" return np.array( np.multiply(input_matrix[:, 0], 256 ** 2) \\ +",
"handling by merging the three color channels color_list = self.serialize(color_list) # Making a",
"return np.unique(serialized_img, axis=0) def serialize(self, input_matrix): # type: (np.array) -> np.array \"\"\" Serializes",
"type: (np.array) -> np.array \"\"\" Returns array of new dynamically calculated color values.",
"config changes. This callback is delayed (about 30 seconds) after changes through dynamic",
"of ONEs self.kernel = None self.kernel = np.ones((self.kernel_edge_size, self.kernel_edge_size)) # Set value of",
"# Masks new image with current color space mask_image = self.color_detector.mask_image(image) # Get",
"hasattr(self, 'sub_image_msg'): self.sub_image_msg.unregister() self.sub_image_msg = rospy.Subscriber( vision_config['ROS_img_msg_topic'], Image, self.image_callback, queue_size=vision_config['ROS_img_queue_size'], tcp_nodelay=True, buff_size=60000000) #",
"new_matrix[:, 1] = np.array((input_matrix - (new_matrix[:, 0] * 256 ** 2)) / 256,",
"to values of 1 or 0 normalized_image = np.floor_divide(masked_image, 255, dtype=np.int16) # Calculates",
"image :return np.array: array of new dynamic color values \"\"\" # Masks new",
"different color channels of a list of colors in an single channel. (Like",
"the value of this pixel is 1, it's value in the sum_array would",
"Making a set and removing duplicated colors color_set = set(color_list) # Generates whitelist",
"= color_space[:,1].tolist() color_space_msg.red = color_space[:,2].tolist() # Publish ColorSpace-message self.pub_color_space.publish(color_space_msg) class Pointfinder(): def __init__(self,",
"queue: queue of array of color values :return np.array: color space \"\"\" #",
":return: None \"\"\" # Turn off dynamic color space, if parameter of config",
"# Add new colors to the queue self.color_value_queue.append(colors) # Publishes to 'ROS_dynamic_color_space_msg_topic' self.publish(image_msg)",
"(np.array, np.array) -> np.array \"\"\" Returns array of unique colors values from a",
"256 ** 2) - (new_matrix[:, 1] * 256)), dtype=np.uint8) return new_matrix if __name__",
"self.kernel[int(np.size(self.kernel, 0) / 2), int(np.size(self.kernel, 1) / 2)] = - self.kernel.size def get_coordinates_of_color_candidates(self,",
"in self.vision_config or \\ vision_config['dynamic_color_space_active'] != self.vision_config['dynamic_color_space_active']: if vision_config['dynamic_color_space_active']: rospy.loginfo('Dynamic color space turned",
"debug_printer): # type: (DebugPrinter) -> None \"\"\" Filters new color space colors according",
"This node publishes ColorSpace-messages. Initiating 'bitbots_dynamic_color_space' node. :return: None \"\"\" # Init package",
"subscriber :return: None \"\"\" # Load dict from string in yaml-format in msg.data",
"from given list. :param np.array image: image :param np.array coordinate_list: list of pixel",
"the size is limeted to 1. That's, why we drop old images manually.",
"to the negative of the count of the matrix elements # In case",
"type: (np.array, np.array, np.array) -> np.array \"\"\" This method filters a given list",
"of color candidates pixel_coordinates = self.pointfinder.get_coordinates_of_color_candidates(mask_image) # Get unique color values from the",
"= rospack.get_path('bitbots_vision') rospy.init_node('bitbots_dynamic_color_space') rospy.loginfo('Initializing dynamic color-space...') self.bridge = CvBridge() # Init params self.vision_config",
"and update vision config. Handle config changes. This callback is delayed (about 30",
"color_space_msg.header.stamp = image_msg.header.stamp color_space_msg.blue = color_space[:,0].tolist() color_space_msg.green = color_space[:,1].tolist() color_space_msg.red = color_space[:,2].tolist() #",
"from image at pixel coordinates \"\"\" # Create list of color values from",
"masked image. :param DebugPrinter: debug-printer :param float threshold: necessary amount of previously detected",
"256) \\ + input_matrix[:, 2], dtype=np.int32) def deserialize(self, input_matrix): # type: (np.array) ->",
"\"\"\" Calculates unique color for an input image. :param np.array image: image :return",
"in the image return np.unique(serialized_img, axis=0) def serialize(self, input_matrix): # type: (np.array) ->",
"binary field-boundary-mask :return np.array: filtered list of colors \"\"\" # Simplifies the handling",
"new color space colors according to their position relative to the field boundary.",
"color_set = set(color_list) # Generates whitelist whitelist = self.recalculate(image, mask) # Takes only",
"self.color_value_queue.clear() # Set params self.queue_max_size = vision_config['dynamic_color_space_queue_max_size'] self.color_value_queue = deque(maxlen=self.queue_max_size) self.pointfinder = Pointfinder(",
"0 normalized_image = np.floor_divide(masked_image, 255, dtype=np.int16) # Calculates the count of neighbors for",
"OFF.') # Set publisher of ColorSpace-messages if 'ROS_dynamic_color_space_msg_topic' not in self.vision_config or \\",
"0 self.kernel[int(np.size(self.kernel, 0) / 2), int(np.size(self.kernel, 1) / 2)] = - self.kernel.size def",
"= rospy.Subscriber( 'vision_config', Config, self.vision_config_callback, queue_size=1, tcp_nodelay=True) rospy.spin() def vision_config_callback(self, msg): # type:",
"node publishes ColorSpace-messages. Initiating 'bitbots_dynamic_color_space' node. :return: None \"\"\" # Init package rospack",
"the count of neighbors for each pixel sum_array = cv2.filter2D(normalized_image, -1, self.kernel, borderType=0)",
"Subscribe to 'vision_config'-message # The message topic name MUST be the same as",
"\"\"\" self.debug_printer = debug_printer def run(self, color_list, image, mask): # type: (np.array, np.array,",
"= self.bridge.imgmsg_to_cv2(image_msg, 'bgr8') # Get new dynamic colors from image colors = self.get_new_dynamic_colors(image)",
"self.get_new_dynamic_colors(image) # Add new colors to the queue self.color_value_queue.append(colors) # Publishes to 'ROS_dynamic_color_space_msg_topic'",
"self.sub_image_msg.unregister() self.sub_image_msg = rospy.Subscriber( vision_config['ROS_img_msg_topic'], Image, self.image_callback, queue_size=vision_config['ROS_img_queue_size'], tcp_nodelay=True, buff_size=60000000) # https://github.com/ros/ros_comm/issues/536 self.vision_config",
"better recognize the field color. DynamicColorSpace is able to calculate dynamically changing color",
"color values, that need to be filtered :param np.array image: raw vision image",
"using the heuristic. colors = np.array(self.heuristic.run(color_candidates, image, mask), dtype=np.int32) return colors return np.array([[]])",
"radius surrounding the center element of kernel matrix, defines relevant surrounding of pixel",
"-> np.array \"\"\" Serializes the different color channels of a list of colors",
"threshold, kernel_radius): # type: (DebugPrinter, float, int) -> None \"\"\" Pointfinder is used",
"that need to be filtered :param np.array image: raw vision image :param np.array",
"None \"\"\" This method is called by the 'vision_config'-message subscriber. Load and update",
"In case the value of this pixel is 1, it's value in the",
"(self.get_unique_colors(cv2.bitwise_and(image, image, mask=255 - mask)), self.get_unique_colors(cv2.bitwise_and(image, image, mask=mask))) def get_unique_colors(self, image): # type:",
"of a list of colors in an single channel. (Like a HTML color",
"calculate the number of occurrences of all colors in the image return (self.get_unique_colors(cv2.bitwise_and(image,",
"space in the queue for new_color_value_list in queue: color_space = np.append(color_space, new_color_value_list[:,:], axis=0)",
"to CV2-image image = self.bridge.imgmsg_to_cv2(image_msg, 'bgr8') # Get new dynamic colors from image",
"Pointfinder(): def __init__(self, debug_printer, threshold, kernel_radius): # type: (DebugPrinter, float, int) -> None",
"reconfigure :param Config msg: new 'vision_config'-message subscriber :return: None \"\"\" # Load dict",
"sensor_msgs.msg import Image from bitbots_msgs.msg import ColorSpace, Config from bitbots_vision.vision_modules import field_boundary, color,",
"This method filters a given list of colors using the original image and",
"= debug_printer def run(self, color_list, image, mask): # type: (np.array, np.array, np.array) ->",
"with a higher true-color/ false-color ratio as threshold in their surrounding in masked",
"= self.field_boundary_detector.get_mask() if mask is not None: # Get array of pixel coordinates",
"pixels color_candidates = self.get_unique_color_values(image, pixel_coordinates) # Filters the colors using the heuristic. colors",
"input_matrix): # type: (np.array) -> np.array \"\"\" Serializes the different color channels of",
"new_color_value_list[:,:], axis=0) # Return a color space, which contains all colors from the",
"queue if hasattr(self, 'color_value_queue'): self.color_value_queue.clear() # Set params self.queue_max_size = vision_config['dynamic_color_space_queue_max_size'] self.color_value_queue =",
"update vision config. Handle config changes. This callback is delayed (about 30 seconds)",
"Heuristic: def __init__(self, debug_printer): # type: (DebugPrinter) -> None \"\"\" Filters new color",
"image: image :param np.array coordinate_list: list of pixel coordinates :return np.array: array of",
"occurrences over the field boundary get picked. :param DebugPrinter debug_printer: Debug-printer :return: None",
"= rospy.Subscriber( vision_config['ROS_img_msg_topic'], Image, self.image_callback, queue_size=vision_config['ROS_img_queue_size'], tcp_nodelay=True, buff_size=60000000) # https://github.com/ros/ros_comm/issues/536 self.vision_config = vision_config",
"mask from field_boundary detector self.field_boundary_detector.set_image(image) mask = self.field_boundary_detector.get_mask() if mask is not None:",
"in yaml-format in msg.data vision_config = yaml.load(msg.data) self.debug_printer = debug.DebugPrinter( debug_classes=debug.DebugPrinter.generate_debug_class_list_from_string( vision_config['vision_debug_printer_classes'])) self.runtime_evaluator",
"Set Color- and FieldBoundaryDetector self.color_detector = color.DynamicPixelListColorDetector( self.debug_printer, self.package_path, vision_config) self.field_boundary_detector = field_boundary.FieldBoundaryDetector(",
"space colors according to their position relative to the field boundary. Only colors",
"(default: image_raw) and to the 'vision_config'-message. This node publishes ColorSpace-messages. Initiating 'bitbots_dynamic_color_space' node.",
"'dynamic_color_space_active' parameter if 'dynamic_color_space_active' not in self.vision_config or \\ vision_config['dynamic_color_space_active'] != self.vision_config['dynamic_color_space_active']: if",
":param np.array image: image :return np.array: unique colors \"\"\" # Simplifies the handling",
"self.field_boundary_detector.get_mask() if mask is not None: # Get array of pixel coordinates of",
"vision config. Handle config changes. This callback is delayed (about 30 seconds) after",
"ColorSpace-message color_space_msg = ColorSpace() color_space_msg.header.frame_id = image_msg.header.frame_id color_space_msg.header.stamp = image_msg.header.stamp color_space_msg.blue = color_space[:,0].tolist()",
"Image, self.image_callback, queue_size=vision_config['ROS_img_queue_size'], tcp_nodelay=True, buff_size=60000000) # https://github.com/ros/ros_comm/issues/536 self.vision_config = vision_config def image_callback(self, image_msg):",
"false-color ratio as threshold in their surrounding in masked image. :param DebugPrinter: debug-printer",
"image, mask): # type: (np.array, np.array, np.array) -> np.array \"\"\" This method filters",
"\"\"\" DynamicColorSpace is a ROS node, that is used by the vision node",
"current color space mask_image = self.color_detector.mask_image(image) # Get mask from field_boundary detector self.field_boundary_detector.set_image(image)",
"center element of the matrix to the negative of the count of the",
"colors_over_field_boundary, colors_under_field_boundary = self.unique_colors_for_partitions(image, mask) return set(colors_under_field_boundary) - set(colors_over_field_boundary) def unique_colors_for_partitions(self, image, mask):",
"self.kernel_edge_size)) # Set value of the center element of the matrix to the",
"# Set publisher of ColorSpace-messages if 'ROS_dynamic_color_space_msg_topic' not in self.vision_config or \\ self.vision_config['ROS_dynamic_color_space_msg_topic']",
"mask) return set(colors_under_field_boundary) - set(colors_over_field_boundary) def unique_colors_for_partitions(self, image, mask): # type: (np.array, np.array)",
"colors using the original image and a field-boundary-mask. :param np.array color_list: list of",
"or \\ not self.vision_config['dynamic_color_space_active']: return # Drops old images image_age = rospy.get_rostime() -",
"subscriber. Old Image-messages were dropped. Sometimes the queue gets to large, even when",
"the queue for new_color_value_list in queue: color_space = np.append(color_space, new_color_value_list[:,:], axis=0) # Return",
"pixel coordinates of color candidates pixel_coordinates = self.pointfinder.get_coordinates_of_color_candidates(mask_image) # Get unique color values",
"deque from sensor_msgs.msg import Image from bitbots_msgs.msg import ColorSpace, Config from bitbots_vision.vision_modules import",
"relevant surrounding of pixel :return: None \"\"\" # Init params self.debug_printer = debug_printer",
"set \"\"\" Generates a whitelist of allowed colors using the original image and",
"the matrix elements # In case the value of this pixel is 1,",
"subscriber. Load and update vision config. Handle config changes. This callback is delayed",
"is called by the 'vision_config'-message subscriber. Load and update vision config. Handle config",
"the field color. DynamicColorSpace is able to calculate dynamically changing color spaces to",
"message topic name MUST be the same as in the config publisher in",
"used by the vision node to better recognize the field color. DynamicColorSpace is",
"surrounding of pixel :return: None \"\"\" # Init params self.debug_printer = debug_printer self.threshold",
"Init params self.debug_printer = debug_printer self.threshold = threshold self.kernel_radius = kernel_radius self.kernel_edge_size =",
"of neighbors for each pixel sum_array = cv2.filter2D(normalized_image, -1, self.kernel, borderType=0) # Returns",
"# type: (DebugPrinter) -> None \"\"\" Filters new color space colors according to",
"field color. DynamicColorSpace is able to calculate dynamically changing color spaces to accommodate",
"Publishes to 'ROS_dynamic_color_space_msg_topic' self.publish(image_msg) def get_unique_color_values(self, image, coordinate_list): # type: (np.array, np.array) ->",
"all colors in the image return (self.get_unique_colors(cv2.bitwise_and(image, image, mask=255 - mask)), self.get_unique_colors(cv2.bitwise_and(image, image,",
"vision_config['dynamic_color_space_threshold'], vision_config['dynamic_color_space_kernel_radius']) self.heuristic = Heuristic(self.debug_printer) # Subscribe to Image-message if 'ROS_img_msg_topic' not in",
"Debug-printer :return: None \"\"\" self.debug_printer = debug_printer def run(self, color_list, image, mask): #",
"* (self.kernel.size - 1))) class Heuristic: def __init__(self, debug_printer): # type: (DebugPrinter) ->",
"np.unique(colors, axis=0) else: unique_colors = colors return unique_colors def get_new_dynamic_colors(self, image): # type:",
"channels \"\"\" new_matrix = np.zeros((input_matrix.size, 3)) new_matrix[:, 0] = np.array(input_matrix // 256 **",
"get_unique_colors(self, image): # type: (np.array) -> np.array \"\"\" Calculates unique color for an",
"their surrounding in masked image. :param np.array masked_image: masked image :return np.array: list",
"# Set Color- and FieldBoundaryDetector self.color_detector = color.DynamicPixelListColorDetector( self.debug_printer, self.package_path, vision_config) self.field_boundary_detector =",
"serialize(self, input_matrix): # type: (np.array) -> np.array \"\"\" Serializes the different color channels",
"a HTML color code) :param np.array input_matrix: list of colors values with 3",
"to queue and published. :param Image image_msg: Image-message :return: None \"\"\" # Converting",
"queue_size=1, tcp_nodelay=True) rospy.spin() def vision_config_callback(self, msg): # type: (Config) -> None \"\"\" This",
"color_set = color_set.intersection(whitelist) # Restructures the color channels return self.deserialize(np.array(list(color_set))) def recalculate(self, image,",
"= colors return unique_colors def get_new_dynamic_colors(self, image): # type: (np.array) -> np.array \"\"\"",
"Image-message if 'ROS_img_msg_topic' not in self.vision_config or \\ self.vision_config['ROS_img_msg_topic'] != vision_config['ROS_img_msg_topic']: if hasattr(self,",
"filtered by the heuristic. :param np.array image: image :return np.array: array of new",
"pixel :return: None \"\"\" # Init params self.debug_printer = debug_printer self.threshold = threshold",
"coordinates :return np.array: array of unique color values from image at pixel coordinates",
"'vision_config'-message. This node publishes ColorSpace-messages. Initiating 'bitbots_dynamic_color_space' node. :return: None \"\"\" # Init",
"number of occurrences of all colors in the image return (self.get_unique_colors(cv2.bitwise_and(image, image, mask=255",
"values with 3 channels :return: list of serialized colors \"\"\" return np.array( np.multiply(input_matrix[:,",
"pixel sum_array = cv2.filter2D(normalized_image, -1, self.kernel, borderType=0) # Returns all pixels with a",
"# type: (Image) -> None \"\"\" Publishes the current color space via ColorSpace-message.",
"np.array \"\"\" Calculates unique color for an input image. :param np.array image: image",
"from a given image at pixel coordinates from given list. :param np.array image:",
"self.pub_color_space.unregister() self.pub_color_space = rospy.Publisher( vision_config['ROS_dynamic_color_space_msg_topic'], ColorSpace, queue_size=1) # Set Color- and FieldBoundaryDetector self.color_detector",
"node subscribes to an Image-message (default: image_raw) and to the 'vision_config'-message. This node",
"files. This node subscribes to an Image-message (default: image_raw) and to the 'vision_config'-message.",
"kernel # Init kernel as M x M matrix of ONEs self.kernel =",
"# Converting the ROS image message to CV2-image image = self.bridge.imgmsg_to_cv2(image_msg, 'bgr8') #",
"self.bridge.imgmsg_to_cv2(image_msg, 'bgr8') # Get new dynamic colors from image colors = self.get_new_dynamic_colors(image) #",
"self.sub_image_msg = rospy.Subscriber( vision_config['ROS_img_msg_topic'], Image, self.image_callback, queue_size=vision_config['ROS_img_queue_size'], tcp_nodelay=True, buff_size=60000000) # https://github.com/ros/ros_comm/issues/536 self.vision_config =",
"image, mask=mask))) def get_unique_colors(self, image): # type: (np.array) -> np.array \"\"\" Calculates unique",
"get picked. :param DebugPrinter debug_printer: Debug-printer :return: None \"\"\" self.debug_printer = debug_printer def",
"self.serialize(color_list) # Making a set and removing duplicated colors color_set = set(color_list) #",
"params self.debug_printer = debug_printer self.threshold = threshold self.kernel_radius = kernel_radius self.kernel_edge_size = 2",
"Old Image-messages were dropped. Sometimes the queue gets to large, even when the",
"by merging the three color channels color_list = self.serialize(color_list) # Making a set",
"return np.array(np.where(sum_array > self.threshold * (self.kernel.size - 1))) class Heuristic: def __init__(self, debug_printer):",
"sum_array would be 0 self.kernel[int(np.size(self.kernel, 0) / 2), int(np.size(self.kernel, 1) / 2)] =",
"Initializes an empty color space color_space = np.array([]).reshape(0,3) # Stack every color space",
"amount of previously detected color in percentage :param int kernel_radius: radius surrounding the",
"colors from the queue return color_space def publish(self, image_msg): # type: (Image) ->",
"np.array((input_matrix - (new_matrix[:, 0] * 256 ** 2) - (new_matrix[:, 1] * 256)),",
"= kernel_radius self.kernel_edge_size = 2 * self.kernel_radius + 1 # Defines kernel #",
"np.array image: image :return np.array: array of new dynamic color values \"\"\" #",
"debug_classes=debug.DebugPrinter.generate_debug_class_list_from_string( vision_config['vision_debug_printer_classes'])) self.runtime_evaluator = evaluator.RuntimeEvaluator(None) # Print status of dynamic color space after",
"of array of color values :return np.array: color space \"\"\" # Initializes an",
"(Config) -> None \"\"\" This method is called by the 'vision_config'-message subscriber. Load",
"color space from queue color_space = self.queue_to_color_space(self.color_value_queue) # Create ColorSpace-message color_space_msg = ColorSpace()",
"the sum_array would be 0 self.kernel[int(np.size(self.kernel, 0) / 2), int(np.size(self.kernel, 1) / 2)]",
"the heuristic. :param np.array image: image :return np.array: array of new dynamic color",
":return: None \"\"\" # Converting the ROS image message to CV2-image image =",
"node. :return: None \"\"\" # Init package rospack = rospkg.RosPack() self.package_path = rospack.get_path('bitbots_vision')",
"dtype=np.uint8) new_matrix[:, 2] = np.array((input_matrix - (new_matrix[:, 0] * 256 ** 2) -",
"axis=0) else: unique_colors = colors return unique_colors def get_new_dynamic_colors(self, image): # type: (np.array)",
"'bitbots_dynamic_color_space' node. :return: None \"\"\" # Init package rospack = rospkg.RosPack() self.package_path =",
"np.array masked_image: masked image :return np.array: list of indices \"\"\" # Normalizes the",
"-> None \"\"\" Pointfinder is used to find false-color pixels with higher true-color",
"of allowed colors using the original image and the field-boundary-mask. :param np.array image:",
"image and the field-boundary-mask. :param np.array image: image :param np.array mask: field-boundary-mask :return",
"in both mask partitions. :param np.array image: image :param np.array mask: field-boundary-mask :return",
"'image') return self.handle_image(image_msg) def handle_image(self, image_msg): # type: (Image) -> None \"\"\" This",
"self.vision_config or \\ vision_config['dynamic_color_space_active'] != self.vision_config['dynamic_color_space_active']: if vision_config['dynamic_color_space_active']: rospy.loginfo('Dynamic color space turned ON.')",
"color space turned OFF.') # Set publisher of ColorSpace-messages if 'ROS_dynamic_color_space_msg_topic' not in",
"if hasattr(self, 'pub_color_space'): self.pub_color_space.unregister() self.pub_color_space = rospy.Publisher( vision_config['ROS_dynamic_color_space_msg_topic'], ColorSpace, queue_size=1) # Set Color-",
"list of colors values with 3 channels :return: list of serialized colors \"\"\"",
"coordinates colors = image[coordinate_list[0], coordinate_list[1]] # np.unique requires list with at least one",
":param np.array image: image :param np.array coordinate_list: list of pixel coordinates :return np.array:",
"\"\"\" # Converting the ROS image message to CV2-image image = self.bridge.imgmsg_to_cv2(image_msg, 'bgr8')",
"not in self.vision_config or \\ self.vision_config['ROS_dynamic_color_space_msg_topic'] != vision_config['ROS_dynamic_color_space_msg_topic']: if hasattr(self, 'pub_color_space'): self.pub_color_space.unregister() self.pub_color_space",
"to calculate dynamically changing color spaces to accommodate e.g. changing lighting conditions or",
"image :param np.array coordinate_list: list of pixel coordinates :return np.array: array of unique",
"colors to the queue self.color_value_queue.append(colors) # Publishes to 'ROS_dynamic_color_space_msg_topic' self.publish(image_msg) def get_unique_color_values(self, image,",
"type: (DebugPrinter) -> None \"\"\" Filters new color space colors according to their",
"to calculate the number of occurrences of all colors in the image return",
"of dynamic color space after toggeling 'dynamic_color_space_active' parameter if 'dynamic_color_space_active' not in self.vision_config",
"import cv2 import yaml import rospy import rospkg import numpy as np from",
"Sometimes the queue gets to large, even when the size is limeted to",
"heuristic. colors = np.array(self.heuristic.run(color_candidates, image, mask), dtype=np.int32) return colors return np.array([[]]) def queue_to_color_space(self,",
"(np.array, np.array) \"\"\" Masks picture and returns the unique colors that occurs in",
"a given list of colors using the original image and a field-boundary-mask. :param",
"Stack every color space in the queue for new_color_value_list in queue: color_space =",
"/ false-color ratio than the threshold return np.array(np.where(sum_array > self.threshold * (self.kernel.size -",
"at given coordinates colors = image[coordinate_list[0], coordinate_list[1]] # np.unique requires list with at",
"vision_config['ROS_dynamic_color_space_msg_topic'], ColorSpace, queue_size=1) # Set Color- and FieldBoundaryDetector self.color_detector = color.DynamicPixelListColorDetector( self.debug_printer, self.package_path,",
"the 'vision_config'-message subscriber. Load and update vision config. Handle config changes. This callback",
"colors using the heuristic. colors = np.array(self.heuristic.run(color_candidates, image, mask), dtype=np.int32) return colors return",
"2) - (new_matrix[:, 1] * 256)), dtype=np.uint8) return new_matrix if __name__ == '__main__':",
"the processing of an Image-message. New colors are calculated, appended to queue and",
"# type: (np.array) -> np.array \"\"\" Resolves the serialization of colors into different",
"by the vision node to better recognize the field color. DynamicColorSpace is able",
"image): # type: (np.array) -> np.array \"\"\" Returns array of new dynamically calculated",
"image_raw) and to the 'vision_config'-message. This node publishes ColorSpace-messages. Initiating 'bitbots_dynamic_color_space' node. :return:",
"= np.array(input_matrix // 256 ** 2, dtype=np.uint8) new_matrix[:, 1] = np.array((input_matrix - (new_matrix[:,",
"(DebugPrinter) -> None \"\"\" Filters new color space colors according to their position",
"callback is delayed (about 30 seconds) after changes through dynamic reconfigure :param Config",
"no occurrences over the field boundary get picked. :param DebugPrinter debug_printer: Debug-printer :return:",
"(np.array) -> np.array \"\"\" Resolves the serialization of colors into different channels. (Like",
"Dropped Image-message', 'image') return self.handle_image(image_msg) def handle_image(self, image_msg): # type: (Image) -> None",
"negative of the count of the matrix elements # In case the value",
"type: (np.array, np.array) -> (np.array, np.array) \"\"\" Masks picture and returns the unique",
"Add new colors to the queue self.color_value_queue.append(colors) # Publishes to 'ROS_dynamic_color_space_msg_topic' self.publish(image_msg) def",
"# Publishes to 'ROS_dynamic_color_space_msg_topic' self.publish(image_msg) def get_unique_color_values(self, image, coordinate_list): # type: (np.array, np.array)",
"rospy.init_node('bitbots_dynamic_color_space') rospy.loginfo('Initializing dynamic color-space...') self.bridge = CvBridge() # Init params self.vision_config = {}",
"color_space_msg.green = color_space[:,1].tolist() color_space_msg.red = color_space[:,2].tolist() # Publish ColorSpace-message self.pub_color_space.publish(color_space_msg) class Pointfinder(): def",
"rospy.Publisher( vision_config['ROS_dynamic_color_space_msg_topic'], ColorSpace, queue_size=1) # Set Color- and FieldBoundaryDetector self.color_detector = color.DynamicPixelListColorDetector( self.debug_printer,",
"to Image-message if 'ROS_img_msg_topic' not in self.vision_config or \\ self.vision_config['ROS_img_msg_topic'] != vision_config['ROS_img_msg_topic']: if",
"= Pointfinder( self.debug_printer, vision_config['dynamic_color_space_threshold'], vision_config['dynamic_color_space_kernel_radius']) self.heuristic = Heuristic(self.debug_printer) # Subscribe to Image-message if",
"CV2-image image = self.bridge.imgmsg_to_cv2(image_msg, 'bgr8') # Get new dynamic colors from image colors",
"case the value of this pixel is 1, it's value in the sum_array",
"Returns color space as array of all queue elements stacked, which contains all",
"np.array color_list: list of color values, that need to be filtered :param np.array",
"tcp_nodelay=True) rospy.spin() def vision_config_callback(self, msg): # type: (Config) -> None \"\"\" This method",
"the queue return color_space def publish(self, image_msg): # type: (Image) -> None \"\"\"",
"manually. :param Image image_msg: new Image-message from Image-message subscriber :return: None \"\"\" #",
"the config publisher in vision.py self.sub_vision_config_msg = rospy.Subscriber( 'vision_config', Config, self.vision_config_callback, queue_size=1, tcp_nodelay=True)",
"topic name MUST be the same as in the config publisher in vision.py",
"input_matrix: serialized colors :return: original colors with 3 channels \"\"\" new_matrix = np.zeros((input_matrix.size,",
"np.array) -> (np.array, np.array) \"\"\" Masks picture and returns the unique colors that",
"None \"\"\" This method is called by the Image-message subscriber. Old Image-messages were",
"Generates a whitelist of allowed colors using the original image and the field-boundary-mask.",
"handle_image(self, image_msg): # type: (Image) -> None \"\"\" This method handles the processing",
"self.get_unique_colors(cv2.bitwise_and(image, image, mask=mask))) def get_unique_colors(self, image): # type: (np.array) -> np.array \"\"\" Calculates",
"colors color_set = set(color_list) # Generates whitelist whitelist = self.recalculate(image, mask) # Takes",
"pixel coordinates of color candidates. Color candidates are false-color pixels with a higher",
"Set value of the center element of the matrix to the negative of",
"Color candidates are false-color pixels with a higher true-color/ false-color ratio as threshold",
"as array of all queue elements stacked, which contains all colors from the",
"'ROS_img_msg_topic' not in self.vision_config or \\ self.vision_config['ROS_img_msg_topic'] != vision_config['ROS_img_msg_topic']: if hasattr(self, 'sub_image_msg'): self.sub_image_msg.unregister()",
"2], dtype=np.int32) def deserialize(self, input_matrix): # type: (np.array) -> np.array \"\"\" Resolves the",
"serialization of colors into different channels. (Like a HTML color code) :param np.array",
"-> set \"\"\" Generates a whitelist of allowed colors using the original image",
"field_boundary detector self.field_boundary_detector.set_image(image) mask = self.field_boundary_detector.get_mask() if mask is not None: # Get",
"values color_set = color_set.intersection(whitelist) # Restructures the color channels return self.deserialize(np.array(list(color_set))) def recalculate(self,",
"\"\"\" # Initializes an empty color space color_space = np.array([]).reshape(0,3) # Stack every",
"dynamic reconfigure :param Config msg: new 'vision_config'-message subscriber :return: None \"\"\" # Load",
"in masked image. :param DebugPrinter: debug-printer :param float threshold: necessary amount of previously",
"the 'vision_config'-message. This node publishes ColorSpace-messages. Initiating 'bitbots_dynamic_color_space' node. :return: None \"\"\" #",
"np.array \"\"\" Resolves the serialization of colors into different channels. (Like a HTML",
"'vision_config'-message subscriber :return: None \"\"\" # Load dict from string in yaml-format in",
"def vision_config_callback(self, msg): # type: (Config) -> None \"\"\" This method is called",
"or \\ vision_config['dynamic_color_space_active'] != self.vision_config['dynamic_color_space_active']: if vision_config['dynamic_color_space_active']: rospy.loginfo('Dynamic color space turned ON.') else:",
"turned OFF.') # Set publisher of ColorSpace-messages if 'ROS_dynamic_color_space_msg_topic' not in self.vision_config or",
"-> np.array \"\"\" Returns color space as array of all queue elements stacked,",
"called by the 'vision_config'-message subscriber. Load and update vision config. Handle config changes.",
"field_boundary.FieldBoundaryDetector( self.color_detector, vision_config, self.debug_printer, used_by_dyn_color_detector=True) # Reset queue if hasattr(self, 'color_value_queue'): self.color_value_queue.clear() #",
"each pixel sum_array = cv2.filter2D(normalized_image, -1, self.kernel, borderType=0) # Returns all pixels with",
"# Get array of pixel coordinates of color candidates pixel_coordinates = self.pointfinder.get_coordinates_of_color_candidates(mask_image) #",
"= np.unique(colors, axis=0) else: unique_colors = colors return unique_colors def get_new_dynamic_colors(self, image): #",
"np.array(np.where(sum_array > self.threshold * (self.kernel.size - 1))) class Heuristic: def __init__(self, debug_printer): #",
"np.array \"\"\" Serializes the different color channels of a list of colors in",
"parameter if 'dynamic_color_space_active' not in self.vision_config or \\ vision_config['dynamic_color_space_active'] != self.vision_config['dynamic_color_space_active']: if vision_config['dynamic_color_space_active']:",
"with current color space mask_image = self.color_detector.mask_image(image) # Get mask from field_boundary detector",
"used to find false-color pixels with higher true-color / false-color ratio as threshold",
"changing lighting conditions or to compensate for not optimized base color space files.",
"M matrix of ONEs self.kernel = None self.kernel = np.ones((self.kernel_edge_size, self.kernel_edge_size)) # Set",
"input image. :param np.array image: image :return np.array: unique colors \"\"\" # Simplifies",
"pixels with a higher true-color/ false-color ratio as threshold in their surrounding in",
"of colors \"\"\" # Simplifies the handling by merging the three color channels",
"(Like a HTML color code) :param np.array input_matrix: list of colors values with",
"Image-messages were dropped. Sometimes the queue gets to large, even when the size",
"def __init__(self, debug_printer): # type: (DebugPrinter) -> None \"\"\" Filters new color space",
"the negative of the count of the matrix elements # In case the",
":param float threshold: necessary amount of previously detected color in percentage :param int",
"space files. This node subscribes to an Image-message (default: image_raw) and to the",
"package rospack = rospkg.RosPack() self.package_path = rospack.get_path('bitbots_vision') rospy.init_node('bitbots_dynamic_color_space') rospy.loginfo('Initializing dynamic color-space...') self.bridge =",
"# type: (Image) -> None \"\"\" This method is called by the Image-message",
"in percentage :param int kernel_radius: radius surrounding the center element of kernel matrix,",
"of config is false if 'dynamic_color_space_active' not in self.vision_config or \\ not self.vision_config['dynamic_color_space_active']:",
":return np.array: unique colors \"\"\" # Simplifies the handling by merging the 3",
"color_space_msg.red = color_space[:,2].tolist() # Publish ColorSpace-message self.pub_color_space.publish(color_space_msg) class Pointfinder(): def __init__(self, debug_printer, threshold,",
"to the field boundary. Only colors that occur under the field boundary and",
"candidates pixel_coordinates = self.pointfinder.get_coordinates_of_color_candidates(mask_image) # Get unique color values from the candidate pixels",
"None \"\"\" self.debug_printer = debug_printer def run(self, color_list, image, mask): # type: (np.array,",
"self.color_value_queue = deque(maxlen=self.queue_max_size) self.pointfinder = Pointfinder( self.debug_printer, vision_config['dynamic_color_space_threshold'], vision_config['dynamic_color_space_kernel_radius']) self.heuristic = Heuristic(self.debug_printer) #",
"Calculates the count of neighbors for each pixel sum_array = cv2.filter2D(normalized_image, -1, self.kernel,",
"self.pointfinder = Pointfinder( self.debug_printer, vision_config['dynamic_color_space_threshold'], vision_config['dynamic_color_space_kernel_radius']) self.heuristic = Heuristic(self.debug_printer) # Subscribe to Image-message",
"in msg.data vision_config = yaml.load(msg.data) self.debug_printer = debug.DebugPrinter( debug_classes=debug.DebugPrinter.generate_debug_class_list_from_string( vision_config['vision_debug_printer_classes'])) self.runtime_evaluator = evaluator.RuntimeEvaluator(None)",
"pixel is 1, it's value in the sum_array would be 0 self.kernel[int(np.size(self.kernel, 0)",
"from bitbots_msgs.msg import ColorSpace, Config from bitbots_vision.vision_modules import field_boundary, color, debug, evaluator class",
"Simplifies the handling by merging the 3 color channels serialized_img = self.serialize(np.reshape(image, (1,",
"image with current color space mask_image = self.color_detector.mask_image(image) # Get mask from field_boundary",
":return: None \"\"\" # Init package rospack = rospkg.RosPack() self.package_path = rospack.get_path('bitbots_vision') rospy.init_node('bitbots_dynamic_color_space')",
"their surrounding in masked image. :param DebugPrinter: debug-printer :param float threshold: necessary amount",
"30 seconds) after changes through dynamic reconfigure :param Config msg: new 'vision_config'-message subscriber",
"self.queue_to_color_space(self.color_value_queue) # Create ColorSpace-message color_space_msg = ColorSpace() color_space_msg.header.frame_id = image_msg.header.frame_id color_space_msg.header.stamp = image_msg.header.stamp",
"np.array image: image :return np.array: unique colors \"\"\" # Simplifies the handling by",
"in the sum_array would be 0 self.kernel[int(np.size(self.kernel, 0) / 2), int(np.size(self.kernel, 1) /",
"Init package rospack = rospkg.RosPack() self.package_path = rospack.get_path('bitbots_vision') rospy.init_node('bitbots_dynamic_color_space') rospy.loginfo('Initializing dynamic color-space...') self.bridge",
"unique colors values from a given image at pixel coordinates from given list.",
"- mask)), self.get_unique_colors(cv2.bitwise_and(image, image, mask=mask))) def get_unique_colors(self, image): # type: (np.array) -> np.array",
"unique colors that occurs in both mask partitions. :param np.array image: image :param",
"type: (Image) -> None \"\"\" Publishes the current color space via ColorSpace-message. :param",
"for each pixel sum_array = cv2.filter2D(normalized_image, -1, self.kernel, borderType=0) # Returns all pixels",
"with higher true-color / false-color ratio as threshold in their surrounding in masked",
"\"\"\" # Create list of color values from image at given coordinates colors",
"return color_space def publish(self, image_msg): # type: (Image) -> None \"\"\" Publishes the",
"/ 256, dtype=np.uint8) new_matrix[:, 2] = np.array((input_matrix - (new_matrix[:, 0] * 256 **",
"Returns all pixels with a higher true-color / false-color ratio than the threshold",
"def queue_to_color_space(self, queue): # type: (deque) -> np.array \"\"\" Returns color space as",
"DebugPrinter debug_printer: Debug-printer :return: None \"\"\" self.debug_printer = debug_printer def run(self, color_list, image,",
"publishes ColorSpace-messages. Initiating 'bitbots_dynamic_color_space' node. :return: None \"\"\" # Init package rospack =",
"-> np.array \"\"\" Calculates unique color for an input image. :param np.array image:",
"percentage :param int kernel_radius: radius surrounding the center element of kernel matrix, defines",
"or \\ self.vision_config['ROS_dynamic_color_space_msg_topic'] != vision_config['ROS_dynamic_color_space_msg_topic']: if hasattr(self, 'pub_color_space'): self.pub_color_space.unregister() self.pub_color_space = rospy.Publisher( vision_config['ROS_dynamic_color_space_msg_topic'],",
"boundary. Only colors that occur under the field boundary and have no occurrences",
"-> None \"\"\" This method is called by the Image-message subscriber. Old Image-messages",
"-> np.array \"\"\" Resolves the serialization of colors into different channels. (Like a",
"the vision node to better recognize the field color. DynamicColorSpace is able to",
"np.array([[]]) def queue_to_color_space(self, queue): # type: (deque) -> np.array \"\"\" Returns color space",
"/ 3), 3))[0]) # Returns unique colors in the image return np.unique(serialized_img, axis=0)",
"rospkg import numpy as np from cv_bridge import CvBridge from collections import deque",
"recalculate(self, image, mask): # type: (np.array, np.array) -> set \"\"\" Generates a whitelist",
"np.array) -> np.array \"\"\" Returns array of unique colors values from a given",
"of pixel coordinates of color candidates. Color candidates are false-color pixels with a",
"Load dict from string in yaml-format in msg.data vision_config = yaml.load(msg.data) self.debug_printer =",
"color channels serialized_img = self.serialize(np.reshape(image, (1, int(image.size / 3), 3))[0]) # Returns unique",
"np.array(self.heuristic.run(color_candidates, image, mask), dtype=np.int32) return colors return np.array([[]]) def queue_to_color_space(self, queue): # type:",
"Defines kernel # Init kernel as M x M matrix of ONEs self.kernel",
"config. Handle config changes. This callback is delayed (about 30 seconds) after changes",
"(np.array, np.array) -> set \"\"\" Generates a whitelist of allowed colors using the",
"ColorSpace-message. :param Image image_msg: 'image_raw'-message :return: None \"\"\" # Get color space from",
"# Returns unique colors in the image return np.unique(serialized_img, axis=0) def serialize(self, input_matrix):",
"# Simplifies the handling by merging the three color channels color_list = self.serialize(color_list)",
"new_matrix[:, 0] = np.array(input_matrix // 256 ** 2, dtype=np.uint8) new_matrix[:, 1] = np.array((input_matrix",
"from image colors = self.get_new_dynamic_colors(image) # Add new colors to the queue self.color_value_queue.append(colors)",
"status of dynamic color space after toggeling 'dynamic_color_space_active' parameter if 'dynamic_color_space_active' not in",
"= image_msg.header.frame_id color_space_msg.header.stamp = image_msg.header.stamp color_space_msg.blue = color_space[:,0].tolist() color_space_msg.green = color_space[:,1].tolist() color_space_msg.red =",
"queue and published. :param Image image_msg: Image-message :return: None \"\"\" # Converting the",
"field boundary get picked. :param DebugPrinter debug_printer: Debug-printer :return: None \"\"\" self.debug_printer =",
"self.debug_printer = debug.DebugPrinter( debug_classes=debug.DebugPrinter.generate_debug_class_list_from_string( vision_config['vision_debug_printer_classes'])) self.runtime_evaluator = evaluator.RuntimeEvaluator(None) # Print status of dynamic",
"unique_colors = np.unique(colors, axis=0) else: unique_colors = colors return unique_colors def get_new_dynamic_colors(self, image):",
"# Calls a function to calculate the number of occurrences of all colors",
"color channels return self.deserialize(np.array(list(color_set))) def recalculate(self, image, mask): # type: (np.array, np.array) ->",
":param np.array mask: field-boundary-mask :return set: whitelist \"\"\" # Generates whitelist colors_over_field_boundary, colors_under_field_boundary",
"'ROS_dynamic_color_space_msg_topic' self.publish(image_msg) def get_unique_color_values(self, image, coordinate_list): # type: (np.array, np.array) -> np.array \"\"\"",
"256 ** 2) \\ + np.multiply(input_matrix[:, 1], 256) \\ + input_matrix[:, 2], dtype=np.int32)",
"DebugPrinter: debug-printer :param float threshold: necessary amount of previously detected color in percentage",
"# Turn off dynamic color space, if parameter of config is false if",
"__init__(self, debug_printer, threshold, kernel_radius): # type: (DebugPrinter, float, int) -> None \"\"\" Pointfinder",
"after toggeling 'dynamic_color_space_active' parameter if 'dynamic_color_space_active' not in self.vision_config or \\ vision_config['dynamic_color_space_active'] !=",
"count of the matrix elements # In case the value of this pixel",
"if 'ROS_dynamic_color_space_msg_topic' not in self.vision_config or \\ self.vision_config['ROS_dynamic_color_space_msg_topic'] != vision_config['ROS_dynamic_color_space_msg_topic']: if hasattr(self, 'pub_color_space'):",
"after changes through dynamic reconfigure :param Config msg: new 'vision_config'-message subscriber :return: None",
"= cv2.filter2D(normalized_image, -1, self.kernel, borderType=0) # Returns all pixels with a higher true-color",
"image, coordinate_list): # type: (np.array, np.array) -> np.array \"\"\" Returns array of unique",
"colors using the original image and the field-boundary-mask. :param np.array image: image :param",
"of previously detected color in percentage :param int kernel_radius: radius surrounding the center",
"np.array image: raw vision image :param np.array mask: binary field-boundary-mask :return np.array: filtered",
"mask = self.field_boundary_detector.get_mask() if mask is not None: # Get array of pixel",
"\"\"\" # Simplifies the handling by merging the 3 color channels serialized_img =",
"colors.size > 0: unique_colors = np.unique(colors, axis=0) else: unique_colors = colors return unique_colors",
"DynamicColorSpace is a ROS node, that is used by the vision node to",
"that is used by the vision node to better recognize the field color.",
"color values. Those values were filtered by the heuristic. :param np.array image: image",
"np from cv_bridge import CvBridge from collections import deque from sensor_msgs.msg import Image",
"0] * 256 ** 2)) / 256, dtype=np.uint8) new_matrix[:, 2] = np.array((input_matrix -",
"# type: (Config) -> None \"\"\" This method is called by the 'vision_config'-message",
"list of serialized colors \"\"\" return np.array( np.multiply(input_matrix[:, 0], 256 ** 2) \\",
"of unique color values from image at pixel coordinates \"\"\" # Create list",
"matrix to the negative of the count of the matrix elements # In",
"to 'vision_config'-message # The message topic name MUST be the same as in",
"None self.kernel = np.ones((self.kernel_edge_size, self.kernel_edge_size)) # Set value of the center element of",
"3), 3))[0]) # Returns unique colors in the image return np.unique(serialized_img, axis=0) def",
"called by the Image-message subscriber. Old Image-messages were dropped. Sometimes the queue gets",
"unique color values from the candidate pixels color_candidates = self.get_unique_color_values(image, pixel_coordinates) # Filters",
"# Generates whitelist whitelist = self.recalculate(image, mask) # Takes only whitelisted values color_set",
"\"\"\" This method is called by the Image-message subscriber. Old Image-messages were dropped.",
"ColorSpace, Config from bitbots_vision.vision_modules import field_boundary, color, debug, evaluator class DynamicColorSpace: def __init__(self):",
"# Making a set and removing duplicated colors color_set = set(color_list) # Generates",
"values from a given image at pixel coordinates from given list. :param np.array",
"image_msg.header.frame_id color_space_msg.header.stamp = image_msg.header.stamp color_space_msg.blue = color_space[:,0].tolist() color_space_msg.green = color_space[:,1].tolist() color_space_msg.red = color_space[:,2].tolist()",
"the same as in the config publisher in vision.py self.sub_vision_config_msg = rospy.Subscriber( 'vision_config',",
"-> np.array \"\"\" Returns array of new dynamically calculated color values. Those values",
"values. Those values were filtered by the heuristic. :param np.array image: image :return",
"field-boundary-mask :return set: whitelist \"\"\" # Generates whitelist colors_over_field_boundary, colors_under_field_boundary = self.unique_colors_for_partitions(image, mask)",
"return self.handle_image(image_msg) def handle_image(self, image_msg): # type: (Image) -> None \"\"\" This method",
"# type: (deque) -> np.array \"\"\" Returns color space as array of all",
"optimized base color space files. This node subscribes to an Image-message (default: image_raw)",
"np.array \"\"\" This method filters a given list of colors using the original",
"by the heuristic. :param np.array image: image :return np.array: array of new dynamic",
"channels return self.deserialize(np.array(list(color_set))) def recalculate(self, image, mask): # type: (np.array, np.array) -> set",
"the field boundary. Only colors that occur under the field boundary and have",
"seconds) after changes through dynamic reconfigure :param Config msg: new 'vision_config'-message subscriber :return:",
"higher true-color / false-color ratio than the threshold return np.array(np.where(sum_array > self.threshold *",
"image :return np.array: list of indices \"\"\" # Normalizes the masked image to",
"Config, self.vision_config_callback, queue_size=1, tcp_nodelay=True) rospy.spin() def vision_config_callback(self, msg): # type: (Config) -> None",
"old images image_age = rospy.get_rostime() - image_msg.header.stamp if image_age.to_sec() > 0.1: self.debug_printer.info('Dynamic color",
"None \"\"\" Filters new color space colors according to their position relative to",
"or to compensate for not optimized base color space files. This node subscribes",
"colors in an single channel. (Like a HTML color code) :param np.array input_matrix:",
"# type (np.array) -> np.array \"\"\" Returns array of pixel coordinates of color",
"serialized colors \"\"\" return np.array( np.multiply(input_matrix[:, 0], 256 ** 2) \\ + np.multiply(input_matrix[:,",
"whitelist of allowed colors using the original image and the field-boundary-mask. :param np.array",
"= rospy.get_rostime() - image_msg.header.stamp if image_age.to_sec() > 0.1: self.debug_printer.info('Dynamic color space: Dropped Image-message',",
"new image with current color space mask_image = self.color_detector.mask_image(image) # Get mask from",
"the candidate pixels color_candidates = self.get_unique_color_values(image, pixel_coordinates) # Filters the colors using the",
"!= self.vision_config['dynamic_color_space_active']: if vision_config['dynamic_color_space_active']: rospy.loginfo('Dynamic color space turned ON.') else: rospy.logwarn('Dynamic color space",
"Returns array of new dynamically calculated color values. Those values were filtered by",
"# type: (np.array, np.array, np.array) -> np.array \"\"\" This method filters a given",
"field-boundary-mask :return np.array: colors over the field boundary :return np.array: colors under the",
"boundary \"\"\" # Calls a function to calculate the number of occurrences of",
"name MUST be the same as in the config publisher in vision.py self.sub_vision_config_msg",
"only whitelisted values color_set = color_set.intersection(whitelist) # Restructures the color channels return self.deserialize(np.array(list(color_set)))",
"color space: Dropped Image-message', 'image') return self.handle_image(image_msg) def handle_image(self, image_msg): # type: (Image)",
"np.array, np.array) -> np.array \"\"\" This method filters a given list of colors",
"new dynamically calculated color values. Those values were filtered by the heuristic. :param",
"numpy as np from cv_bridge import CvBridge from collections import deque from sensor_msgs.msg",
"def get_unique_colors(self, image): # type: (np.array) -> np.array \"\"\" Calculates unique color for",
"mask=mask))) def get_unique_colors(self, image): # type: (np.array) -> np.array \"\"\" Calculates unique color",
"type (np.array) -> np.array \"\"\" Returns array of pixel coordinates of color candidates.",
":return: None \"\"\" self.debug_printer = debug_printer def run(self, color_list, image, mask): # type:",
"def recalculate(self, image, mask): # type: (np.array, np.array) -> set \"\"\" Generates a",
"Get array of pixel coordinates of color candidates pixel_coordinates = self.pointfinder.get_coordinates_of_color_candidates(mask_image) # Get",
"<filename>bitbots_vision/src/bitbots_vision/dynamic_color_space.py #! /usr/bin/env python3 import cv2 import yaml import rospy import rospkg import",
"queue self.color_value_queue.append(colors) # Publishes to 'ROS_dynamic_color_space_msg_topic' self.publish(image_msg) def get_unique_color_values(self, image, coordinate_list): # type:",
"mask: field-boundary-mask :return set: whitelist \"\"\" # Generates whitelist colors_over_field_boundary, colors_under_field_boundary = self.unique_colors_for_partitions(image,",
"= self.get_unique_color_values(image, pixel_coordinates) # Filters the colors using the heuristic. colors = np.array(self.heuristic.run(color_candidates,",
"color in percentage :param int kernel_radius: radius surrounding the center element of kernel",
"array of unique colors values from a given image at pixel coordinates from",
"return self.deserialize(np.array(list(color_set))) def recalculate(self, image, mask): # type: (np.array, np.array) -> set \"\"\"",
"= ColorSpace() color_space_msg.header.frame_id = image_msg.header.frame_id color_space_msg.header.stamp = image_msg.header.stamp color_space_msg.blue = color_space[:,0].tolist() color_space_msg.green =",
"Set publisher of ColorSpace-messages if 'ROS_dynamic_color_space_msg_topic' not in self.vision_config or \\ self.vision_config['ROS_dynamic_color_space_msg_topic'] !=",
"neighbors for each pixel sum_array = cv2.filter2D(normalized_image, -1, self.kernel, borderType=0) # Returns all",
"-> (np.array, np.array) \"\"\" Masks picture and returns the unique colors that occurs",
"publish(self, image_msg): # type: (Image) -> None \"\"\" Publishes the current color space",
"elements stacked, which contains all colors from the queue. :param dequeue queue: queue",
"list of color values, that need to be filtered :param np.array image: raw",
"values \"\"\" # Masks new image with current color space mask_image = self.color_detector.mask_image(image)",
"self.vision_config['dynamic_color_space_active']: return # Drops old images image_age = rospy.get_rostime() - image_msg.header.stamp if image_age.to_sec()",
"mask_image = self.color_detector.mask_image(image) # Get mask from field_boundary detector self.field_boundary_detector.set_image(image) mask = self.field_boundary_detector.get_mask()",
"matrix, defines relevant surrounding of pixel :return: None \"\"\" # Init params self.debug_printer",
"the masked image to values of 1 or 0 normalized_image = np.floor_divide(masked_image, 255,",
"given image at pixel coordinates from given list. :param np.array image: image :param",
"the 3 color channels serialized_img = self.serialize(np.reshape(image, (1, int(image.size / 3), 3))[0]) #",
"drop old images manually. :param Image image_msg: new Image-message from Image-message subscriber :return:",
"rospy.Subscriber( vision_config['ROS_img_msg_topic'], Image, self.image_callback, queue_size=vision_config['ROS_img_queue_size'], tcp_nodelay=True, buff_size=60000000) # https://github.com/ros/ros_comm/issues/536 self.vision_config = vision_config def",
"element of the matrix to the negative of the count of the matrix",
"self.publish(image_msg) def get_unique_color_values(self, image, coordinate_list): # type: (np.array, np.array) -> np.array \"\"\" Returns",
"\"\"\" new_matrix = np.zeros((input_matrix.size, 3)) new_matrix[:, 0] = np.array(input_matrix // 256 ** 2,",
"if 'ROS_img_msg_topic' not in self.vision_config or \\ self.vision_config['ROS_img_msg_topic'] != vision_config['ROS_img_msg_topic']: if hasattr(self, 'sub_image_msg'):",
":param np.array image: image :param np.array mask: field-boundary-mask :return np.array: colors over the",
"calculate dynamically changing color spaces to accommodate e.g. changing lighting conditions or to",
"self.vision_config or \\ not self.vision_config['dynamic_color_space_active']: return # Drops old images image_age = rospy.get_rostime()",
"queue of array of color values :return np.array: color space \"\"\" # Initializes",
"in self.vision_config or \\ not self.vision_config['dynamic_color_space_active']: return # Drops old images image_age =",
"if parameter of config is false if 'dynamic_color_space_active' not in self.vision_config or \\",
"of unique colors values from a given image at pixel coordinates from given",
"from sensor_msgs.msg import Image from bitbots_msgs.msg import ColorSpace, Config from bitbots_vision.vision_modules import field_boundary,",
"occurs in both mask partitions. :param np.array image: image :param np.array mask: field-boundary-mask",
"publisher in vision.py self.sub_vision_config_msg = rospy.Subscriber( 'vision_config', Config, self.vision_config_callback, queue_size=1, tcp_nodelay=True) rospy.spin() def",
"dynamic color space after toggeling 'dynamic_color_space_active' parameter if 'dynamic_color_space_active' not in self.vision_config or",
"# https://github.com/ros/ros_comm/issues/536 self.vision_config = vision_config def image_callback(self, image_msg): # type: (Image) -> None",
"coordinate_list: list of pixel coordinates :return np.array: array of unique color values from",
"is called by the Image-message subscriber. Old Image-messages were dropped. Sometimes the queue",
"for not optimized base color space files. This node subscribes to an Image-message",
"Return a color space, which contains all colors from the queue return color_space",
"for new_color_value_list in queue: color_space = np.append(color_space, new_color_value_list[:,:], axis=0) # Return a color",
"The message topic name MUST be the same as in the config publisher",
"params self.queue_max_size = vision_config['dynamic_color_space_queue_max_size'] self.color_value_queue = deque(maxlen=self.queue_max_size) self.pointfinder = Pointfinder( self.debug_printer, vision_config['dynamic_color_space_threshold'], vision_config['dynamic_color_space_kernel_radius'])",
"queue gets to large, even when the size is limeted to 1. That's,",
"2, dtype=np.uint8) new_matrix[:, 1] = np.array((input_matrix - (new_matrix[:, 0] * 256 ** 2))",
"whitelist = self.recalculate(image, mask) # Takes only whitelisted values color_set = color_set.intersection(whitelist) #",
"one element if colors.size > 0: unique_colors = np.unique(colors, axis=0) else: unique_colors =",
"= yaml.load(msg.data) self.debug_printer = debug.DebugPrinter( debug_classes=debug.DebugPrinter.generate_debug_class_list_from_string( vision_config['vision_debug_printer_classes'])) self.runtime_evaluator = evaluator.RuntimeEvaluator(None) # Print status",
"deque(maxlen=self.queue_max_size) self.pointfinder = Pointfinder( self.debug_printer, vision_config['dynamic_color_space_threshold'], vision_config['dynamic_color_space_kernel_radius']) self.heuristic = Heuristic(self.debug_printer) # Subscribe to",
"image): # type: (np.array) -> np.array \"\"\" Calculates unique color for an input",
"and returns the unique colors that occurs in both mask partitions. :param np.array",
"as threshold in their surrounding in masked image. :param DebugPrinter: debug-printer :param float",
"np.array: list of indices \"\"\" # Normalizes the masked image to values of",
"- (new_matrix[:, 0] * 256 ** 2) - (new_matrix[:, 1] * 256)), dtype=np.uint8)",
"image_msg: 'image_raw'-message :return: None \"\"\" # Get color space from queue color_space =",
"mask): # type: (np.array, np.array, np.array) -> np.array \"\"\" This method filters a",
"values from image at pixel coordinates \"\"\" # Create list of color values",
"np.array image: image :param np.array mask: field-boundary-mask :return np.array: colors over the field",
"# Load dict from string in yaml-format in msg.data vision_config = yaml.load(msg.data) self.debug_printer",
"channels :return: list of serialized colors \"\"\" return np.array( np.multiply(input_matrix[:, 0], 256 **",
":return set: whitelist \"\"\" # Generates whitelist colors_over_field_boundary, colors_under_field_boundary = self.unique_colors_for_partitions(image, mask) return",
"even when the size is limeted to 1. That's, why we drop old",
"from the queue. :param dequeue queue: queue of array of color values :return",
"colors with 3 channels \"\"\" new_matrix = np.zeros((input_matrix.size, 3)) new_matrix[:, 0] = np.array(input_matrix",
"if 'dynamic_color_space_active' not in self.vision_config or \\ vision_config['dynamic_color_space_active'] != self.vision_config['dynamic_color_space_active']: if vision_config['dynamic_color_space_active']: rospy.loginfo('Dynamic",
"color-space...') self.bridge = CvBridge() # Init params self.vision_config = {} # Subscribe to",
"gets to large, even when the size is limeted to 1. That's, why",
"-> np.array \"\"\" Returns array of pixel coordinates of color candidates. Color candidates",
"= np.array([]).reshape(0,3) # Stack every color space in the queue for new_color_value_list in",
"(self.kernel.size - 1))) class Heuristic: def __init__(self, debug_printer): # type: (DebugPrinter) -> None",
"+ input_matrix[:, 2], dtype=np.int32) def deserialize(self, input_matrix): # type: (np.array) -> np.array \"\"\"",
"message to CV2-image image = self.bridge.imgmsg_to_cv2(image_msg, 'bgr8') # Get new dynamic colors from",
":param np.array coordinate_list: list of pixel coordinates :return np.array: array of unique color",
"float, int) -> None \"\"\" Pointfinder is used to find false-color pixels with",
"np.array coordinate_list: list of pixel coordinates :return np.array: array of unique color values",
"- (new_matrix[:, 0] * 256 ** 2)) / 256, dtype=np.uint8) new_matrix[:, 2] =",
"color. DynamicColorSpace is able to calculate dynamically changing color spaces to accommodate e.g.",
"This method is called by the 'vision_config'-message subscriber. Load and update vision config.",
"= self.get_new_dynamic_colors(image) # Add new colors to the queue self.color_value_queue.append(colors) # Publishes to",
"\"\"\" Returns array of pixel coordinates of color candidates. Color candidates are false-color",
"# In case the value of this pixel is 1, it's value in",
"self.vision_config_callback, queue_size=1, tcp_nodelay=True) rospy.spin() def vision_config_callback(self, msg): # type: (Config) -> None \"\"\"",
"of pixel coordinates :return np.array: array of unique color values from image at",
"2), int(np.size(self.kernel, 1) / 2)] = - self.kernel.size def get_coordinates_of_color_candidates(self, masked_image): # type",
"np.multiply(input_matrix[:, 0], 256 ** 2) \\ + np.multiply(input_matrix[:, 1], 256) \\ + input_matrix[:,",
"in vision.py self.sub_vision_config_msg = rospy.Subscriber( 'vision_config', Config, self.vision_config_callback, queue_size=1, tcp_nodelay=True) rospy.spin() def vision_config_callback(self,",
"image and a field-boundary-mask. :param np.array color_list: list of color values, that need",
"element of kernel matrix, defines relevant surrounding of pixel :return: None \"\"\" #",
"to better recognize the field color. DynamicColorSpace is able to calculate dynamically changing",
"the handling by merging the three color channels color_list = self.serialize(color_list) # Making",
"toggeling 'dynamic_color_space_active' parameter if 'dynamic_color_space_active' not in self.vision_config or \\ vision_config['dynamic_color_space_active'] != self.vision_config['dynamic_color_space_active']:",
"and removing duplicated colors color_set = set(color_list) # Generates whitelist whitelist = self.recalculate(image,",
"= self.unique_colors_for_partitions(image, mask) return set(colors_under_field_boundary) - set(colors_over_field_boundary) def unique_colors_for_partitions(self, image, mask): # type:",
"2] = np.array((input_matrix - (new_matrix[:, 0] * 256 ** 2) - (new_matrix[:, 1]",
"# Subscribe to 'vision_config'-message # The message topic name MUST be the same",
"from the queue return color_space def publish(self, image_msg): # type: (Image) -> None",
"color_space[:,0].tolist() color_space_msg.green = color_space[:,1].tolist() color_space_msg.red = color_space[:,2].tolist() # Publish ColorSpace-message self.pub_color_space.publish(color_space_msg) class Pointfinder():",
"masked_image): # type (np.array) -> np.array \"\"\" Returns array of pixel coordinates of",
"np.array) -> set \"\"\" Generates a whitelist of allowed colors using the original",
"accommodate e.g. changing lighting conditions or to compensate for not optimized base color",
"def get_coordinates_of_color_candidates(self, masked_image): # type (np.array) -> np.array \"\"\" Returns array of pixel",
"= deque(maxlen=self.queue_max_size) self.pointfinder = Pointfinder( self.debug_printer, vision_config['dynamic_color_space_threshold'], vision_config['dynamic_color_space_kernel_radius']) self.heuristic = Heuristic(self.debug_printer) # Subscribe",
"Image image_msg: new Image-message from Image-message subscriber :return: None \"\"\" # Turn off",
"Calls a function to calculate the number of occurrences of all colors in",
"in an single channel. (Like a HTML color code) :param np.array input_matrix: list",
"from queue color_space = self.queue_to_color_space(self.color_value_queue) # Create ColorSpace-message color_space_msg = ColorSpace() color_space_msg.header.frame_id =",
"rospy.loginfo('Initializing dynamic color-space...') self.bridge = CvBridge() # Init params self.vision_config = {} #",
"\"\"\" return np.array( np.multiply(input_matrix[:, 0], 256 ** 2) \\ + np.multiply(input_matrix[:, 1], 256)",
"colors return np.array([[]]) def queue_to_color_space(self, queue): # type: (deque) -> np.array \"\"\" Returns",
"get_unique_color_values(self, image, coordinate_list): # type: (np.array, np.array) -> np.array \"\"\" Returns array of",
"coordinates from given list. :param np.array image: image :param np.array coordinate_list: list of",
"vision image :param np.array mask: binary field-boundary-mask :return np.array: filtered list of colors",
"dynamic color-space...') self.bridge = CvBridge() # Init params self.vision_config = {} # Subscribe",
"vision_config['dynamic_color_space_active'] != self.vision_config['dynamic_color_space_active']: if vision_config['dynamic_color_space_active']: rospy.loginfo('Dynamic color space turned ON.') else: rospy.logwarn('Dynamic color",
"= self.serialize(np.reshape(image, (1, int(image.size / 3), 3))[0]) # Returns unique colors in the",
"detector self.field_boundary_detector.set_image(image) mask = self.field_boundary_detector.get_mask() if mask is not None: # Get array",
"borderType=0) # Returns all pixels with a higher true-color / false-color ratio than",
"= evaluator.RuntimeEvaluator(None) # Print status of dynamic color space after toggeling 'dynamic_color_space_active' parameter",
"masked image. :param np.array masked_image: masked image :return np.array: list of indices \"\"\"",
"+ np.multiply(input_matrix[:, 1], 256) \\ + input_matrix[:, 2], dtype=np.int32) def deserialize(self, input_matrix): #",
"the handling by merging the 3 color channels serialized_img = self.serialize(np.reshape(image, (1, int(image.size",
"handling by merging the 3 color channels serialized_img = self.serialize(np.reshape(image, (1, int(image.size /",
"= threshold self.kernel_radius = kernel_radius self.kernel_edge_size = 2 * self.kernel_radius + 1 #",
"is a ROS node, that is used by the vision node to better",
"Image-message :return: None \"\"\" # Converting the ROS image message to CV2-image image",
"in their surrounding in masked image. :param DebugPrinter: debug-printer :param float threshold: necessary",
"which contains all colors from the queue return color_space def publish(self, image_msg): #",
"through dynamic reconfigure :param Config msg: new 'vision_config'-message subscriber :return: None \"\"\" #",
"# Calculates the count of neighbors for each pixel sum_array = cv2.filter2D(normalized_image, -1,",
"the heuristic. colors = np.array(self.heuristic.run(color_candidates, image, mask), dtype=np.int32) return colors return np.array([[]]) def",
"self.debug_printer = debug_printer def run(self, color_list, image, mask): # type: (np.array, np.array, np.array)",
"unique_colors = colors return unique_colors def get_new_dynamic_colors(self, image): # type: (np.array) -> np.array",
"def get_new_dynamic_colors(self, image): # type: (np.array) -> np.array \"\"\" Returns array of new",
"\\ self.vision_config['ROS_dynamic_color_space_msg_topic'] != vision_config['ROS_dynamic_color_space_msg_topic']: if hasattr(self, 'pub_color_space'): self.pub_color_space.unregister() self.pub_color_space = rospy.Publisher( vision_config['ROS_dynamic_color_space_msg_topic'], ColorSpace,",
"values of 1 or 0 normalized_image = np.floor_divide(masked_image, 255, dtype=np.int16) # Calculates the",
"'dynamic_color_space_active' not in self.vision_config or \\ vision_config['dynamic_color_space_active'] != self.vision_config['dynamic_color_space_active']: if vision_config['dynamic_color_space_active']: rospy.loginfo('Dynamic color",
"the original image and a field-boundary-mask. :param np.array color_list: list of color values,",
"image: raw vision image :param np.array mask: binary field-boundary-mask :return np.array: filtered list",
"the original image and the field-boundary-mask. :param np.array image: image :param np.array mask:",
"= rospkg.RosPack() self.package_path = rospack.get_path('bitbots_vision') rospy.init_node('bitbots_dynamic_color_space') rospy.loginfo('Initializing dynamic color-space...') self.bridge = CvBridge() #",
"e.g. changing lighting conditions or to compensate for not optimized base color space",
"vision_config['dynamic_color_space_active']: rospy.loginfo('Dynamic color space turned ON.') else: rospy.logwarn('Dynamic color space turned OFF.') #",
"are calculated, appended to queue and published. :param Image image_msg: Image-message :return: None",
"> 0.1: self.debug_printer.info('Dynamic color space: Dropped Image-message', 'image') return self.handle_image(image_msg) def handle_image(self, image_msg):",
"that occurs in both mask partitions. :param np.array image: image :param np.array mask:",
"rospy.Subscriber( 'vision_config', Config, self.vision_config_callback, queue_size=1, tcp_nodelay=True) rospy.spin() def vision_config_callback(self, msg): # type: (Config)",
"= np.array(self.heuristic.run(color_candidates, image, mask), dtype=np.int32) return colors return np.array([[]]) def queue_to_color_space(self, queue): #",
"picked. :param DebugPrinter debug_printer: Debug-printer :return: None \"\"\" self.debug_printer = debug_printer def run(self,",
"color_list, image, mask): # type: (np.array, np.array, np.array) -> np.array \"\"\" This method",
"all colors from the queue return color_space def publish(self, image_msg): # type: (Image)",
"an Image-message (default: image_raw) and to the 'vision_config'-message. This node publishes ColorSpace-messages. Initiating",
"# Simplifies the handling by merging the 3 color channels serialized_img = self.serialize(np.reshape(image,",
"image, mask): # type: (np.array, np.array) -> (np.array, np.array) \"\"\" Masks picture and",
"color_space[:,1].tolist() color_space_msg.red = color_space[:,2].tolist() # Publish ColorSpace-message self.pub_color_space.publish(color_space_msg) class Pointfinder(): def __init__(self, debug_printer,",
"of colors in an single channel. (Like a HTML color code) :param np.array",
"Heuristic(self.debug_printer) # Subscribe to Image-message if 'ROS_img_msg_topic' not in self.vision_config or \\ self.vision_config['ROS_img_msg_topic']",
"debug, evaluator class DynamicColorSpace: def __init__(self): # type: () -> None \"\"\" DynamicColorSpace",
"is not None: # Get array of pixel coordinates of color candidates pixel_coordinates",
"color values \"\"\" # Masks new image with current color space mask_image =",
"the color channels return self.deserialize(np.array(list(color_set))) def recalculate(self, image, mask): # type: (np.array, np.array)",
"find false-color pixels with higher true-color / false-color ratio as threshold in their",
"colors = np.array(self.heuristic.run(color_candidates, image, mask), dtype=np.int32) return colors return np.array([[]]) def queue_to_color_space(self, queue):",
"unique color for an input image. :param np.array image: image :return np.array: unique",
"array of unique color values from image at pixel coordinates \"\"\" # Create",
"by the Image-message subscriber. Old Image-messages were dropped. Sometimes the queue gets to",
"ratio as threshold in their surrounding in masked image. :param np.array masked_image: masked",
"in queue: color_space = np.append(color_space, new_color_value_list[:,:], axis=0) # Return a color space, which",
"to the queue self.color_value_queue.append(colors) # Publishes to 'ROS_dynamic_color_space_msg_topic' self.publish(image_msg) def get_unique_color_values(self, image, coordinate_list):",
"changing color spaces to accommodate e.g. changing lighting conditions or to compensate for",
"conditions or to compensate for not optimized base color space files. This node",
"Config msg: new 'vision_config'-message subscriber :return: None \"\"\" # Load dict from string",
"rospack = rospkg.RosPack() self.package_path = rospack.get_path('bitbots_vision') rospy.init_node('bitbots_dynamic_color_space') rospy.loginfo('Initializing dynamic color-space...') self.bridge = CvBridge()",
":return np.array: colors under the field boundary \"\"\" # Calls a function to",
"= color.DynamicPixelListColorDetector( self.debug_printer, self.package_path, vision_config) self.field_boundary_detector = field_boundary.FieldBoundaryDetector( self.color_detector, vision_config, self.debug_printer, used_by_dyn_color_detector=True) #",
"ratio as threshold in their surrounding in masked image. :param DebugPrinter: debug-printer :param",
"and a field-boundary-mask. :param np.array color_list: list of color values, that need to",
"queue return color_space def publish(self, image_msg): # type: (Image) -> None \"\"\" Publishes",
"# Reset queue if hasattr(self, 'color_value_queue'): self.color_value_queue.clear() # Set params self.queue_max_size = vision_config['dynamic_color_space_queue_max_size']",
"image_msg: new Image-message from Image-message subscriber :return: None \"\"\" # Turn off dynamic",
"were dropped. Sometimes the queue gets to large, even when the size is",
"np.unique requires list with at least one element if colors.size > 0: unique_colors",
"previously detected color in percentage :param int kernel_radius: radius surrounding the center element",
"the ROS image message to CV2-image image = self.bridge.imgmsg_to_cv2(image_msg, 'bgr8') # Get new",
"np.array([]).reshape(0,3) # Stack every color space in the queue for new_color_value_list in queue:",
"over the field boundary get picked. :param DebugPrinter debug_printer: Debug-printer :return: None \"\"\"",
"by merging the 3 color channels serialized_img = self.serialize(np.reshape(image, (1, int(image.size / 3),",
"image message to CV2-image image = self.bridge.imgmsg_to_cv2(image_msg, 'bgr8') # Get new dynamic colors",
"stacked, which contains all colors from the queue. :param dequeue queue: queue of",
"removing duplicated colors color_set = set(color_list) # Generates whitelist whitelist = self.recalculate(image, mask)",
"given list of colors using the original image and a field-boundary-mask. :param np.array",
"None: # Get array of pixel coordinates of color candidates pixel_coordinates = self.pointfinder.get_coordinates_of_color_candidates(mask_image)",
"Image-message (default: image_raw) and to the 'vision_config'-message. This node publishes ColorSpace-messages. Initiating 'bitbots_dynamic_color_space'",
":return: None \"\"\" # Load dict from string in yaml-format in msg.data vision_config",
"contains all colors from the queue. :param dequeue queue: queue of array of",
"\"\"\" # Masks new image with current color space mask_image = self.color_detector.mask_image(image) #",
"self.kernel_radius + 1 # Defines kernel # Init kernel as M x M",
"self.debug_printer.info('Dynamic color space: Dropped Image-message', 'image') return self.handle_image(image_msg) def handle_image(self, image_msg): # type:",
"the image return (self.get_unique_colors(cv2.bitwise_and(image, image, mask=255 - mask)), self.get_unique_colors(cv2.bitwise_and(image, image, mask=mask))) def get_unique_colors(self,",
"dynamically changing color spaces to accommodate e.g. changing lighting conditions or to compensate",
"self.kernel = None self.kernel = np.ones((self.kernel_edge_size, self.kernel_edge_size)) # Set value of the center",
"mask)), self.get_unique_colors(cv2.bitwise_and(image, image, mask=mask))) def get_unique_colors(self, image): # type: (np.array) -> np.array \"\"\"",
"center element of kernel matrix, defines relevant surrounding of pixel :return: None \"\"\"",
"Pointfinder( self.debug_printer, vision_config['dynamic_color_space_threshold'], vision_config['dynamic_color_space_kernel_radius']) self.heuristic = Heuristic(self.debug_printer) # Subscribe to Image-message if 'ROS_img_msg_topic'",
"colors = self.get_new_dynamic_colors(image) # Add new colors to the queue self.color_value_queue.append(colors) # Publishes",
"# Get new dynamic colors from image colors = self.get_new_dynamic_colors(image) # Add new",
"from collections import deque from sensor_msgs.msg import Image from bitbots_msgs.msg import ColorSpace, Config",
"color_space_msg = ColorSpace() color_space_msg.header.frame_id = image_msg.header.frame_id color_space_msg.header.stamp = image_msg.header.stamp color_space_msg.blue = color_space[:,0].tolist() color_space_msg.green",
"256 ** 2)) / 256, dtype=np.uint8) new_matrix[:, 2] = np.array((input_matrix - (new_matrix[:, 0]",
"= np.array((input_matrix - (new_matrix[:, 0] * 256 ** 2) - (new_matrix[:, 1] *",
"Returns unique colors in the image return np.unique(serialized_img, axis=0) def serialize(self, input_matrix): #",
"not self.vision_config['dynamic_color_space_active']: return # Drops old images image_age = rospy.get_rostime() - image_msg.header.stamp if",
"picture and returns the unique colors that occurs in both mask partitions. :param",
"# Publish ColorSpace-message self.pub_color_space.publish(color_space_msg) class Pointfinder(): def __init__(self, debug_printer, threshold, kernel_radius): # type:",
"recognize the field color. DynamicColorSpace is able to calculate dynamically changing color spaces",
"\"\"\" # Load dict from string in yaml-format in msg.data vision_config = yaml.load(msg.data)",
"of indices \"\"\" # Normalizes the masked image to values of 1 or",
"new Image-message from Image-message subscriber :return: None \"\"\" # Turn off dynamic color",
"https://github.com/ros/ros_comm/issues/536 self.vision_config = vision_config def image_callback(self, image_msg): # type: (Image) -> None \"\"\"",
"CvBridge from collections import deque from sensor_msgs.msg import Image from bitbots_msgs.msg import ColorSpace,",
"# Initializes an empty color space color_space = np.array([]).reshape(0,3) # Stack every color",
"= self.color_detector.mask_image(image) # Get mask from field_boundary detector self.field_boundary_detector.set_image(image) mask = self.field_boundary_detector.get_mask() if",
"with at least one element if colors.size > 0: unique_colors = np.unique(colors, axis=0)",
"queue for new_color_value_list in queue: color_space = np.append(color_space, new_color_value_list[:,:], axis=0) # Return a",
"both mask partitions. :param np.array image: image :param np.array mask: field-boundary-mask :return np.array:",
"values, that need to be filtered :param np.array image: raw vision image :param",
"np.array((input_matrix - (new_matrix[:, 0] * 256 ** 2)) / 256, dtype=np.uint8) new_matrix[:, 2]",
"# type: (np.array) -> np.array \"\"\" Calculates unique color for an input image.",
"we drop old images manually. :param Image image_msg: new Image-message from Image-message subscriber",
"3 channels \"\"\" new_matrix = np.zeros((input_matrix.size, 3)) new_matrix[:, 0] = np.array(input_matrix // 256",
"is used by the vision node to better recognize the field color. DynamicColorSpace",
"self.field_boundary_detector.set_image(image) mask = self.field_boundary_detector.get_mask() if mask is not None: # Get array of",
"colors in the image return (self.get_unique_colors(cv2.bitwise_and(image, image, mask=255 - mask)), self.get_unique_colors(cv2.bitwise_and(image, image, mask=mask)))",
"colors into different channels. (Like a HTML color code) :param np.array input_matrix: serialized",
"Image image_msg: Image-message :return: None \"\"\" # Converting the ROS image message to",
"(deque) -> np.array \"\"\" Returns color space as array of all queue elements",
"colors \"\"\" # Simplifies the handling by merging the three color channels color_list",
"# Get mask from field_boundary detector self.field_boundary_detector.set_image(image) mask = self.field_boundary_detector.get_mask() if mask is",
"is delayed (about 30 seconds) after changes through dynamic reconfigure :param Config msg:",
"boundary and have no occurrences over the field boundary get picked. :param DebugPrinter",
"yaml import rospy import rospkg import numpy as np from cv_bridge import CvBridge",
"an single channel. (Like a HTML color code) :param np.array input_matrix: list of",
"color space turned ON.') else: rospy.logwarn('Dynamic color space turned OFF.') # Set publisher",
"vision_config) self.field_boundary_detector = field_boundary.FieldBoundaryDetector( self.color_detector, vision_config, self.debug_printer, used_by_dyn_color_detector=True) # Reset queue if hasattr(self,",
"class Pointfinder(): def __init__(self, debug_printer, threshold, kernel_radius): # type: (DebugPrinter, float, int) ->",
"2 * self.kernel_radius + 1 # Defines kernel # Init kernel as M",
"using the original image and the field-boundary-mask. :param np.array image: image :param np.array",
"bitbots_vision.vision_modules import field_boundary, color, debug, evaluator class DynamicColorSpace: def __init__(self): # type: ()",
"ROS image message to CV2-image image = self.bridge.imgmsg_to_cv2(image_msg, 'bgr8') # Get new dynamic",
"array of pixel coordinates of color candidates. Color candidates are false-color pixels with",
"self.kernel_radius = kernel_radius self.kernel_edge_size = 2 * self.kernel_radius + 1 # Defines kernel",
"rospack.get_path('bitbots_vision') rospy.init_node('bitbots_dynamic_color_space') rospy.loginfo('Initializing dynamic color-space...') self.bridge = CvBridge() # Init params self.vision_config =",
"calculated color values. Those values were filtered by the heuristic. :param np.array image:",
"merging the 3 color channels serialized_img = self.serialize(np.reshape(image, (1, int(image.size / 3), 3))[0])",
"-> None \"\"\" DynamicColorSpace is a ROS node, that is used by the",
"np.append(color_space, new_color_value_list[:,:], axis=0) # Return a color space, which contains all colors from",
"# type: (np.array, np.array) -> (np.array, np.array) \"\"\" Masks picture and returns the",
"rospy.logwarn('Dynamic color space turned OFF.') # Set publisher of ColorSpace-messages if 'ROS_dynamic_color_space_msg_topic' not",
"field boundary and have no occurrences over the field boundary get picked. :param",
"duplicated colors color_set = set(color_list) # Generates whitelist whitelist = self.recalculate(image, mask) #",
"Image from bitbots_msgs.msg import ColorSpace, Config from bitbots_vision.vision_modules import field_boundary, color, debug, evaluator",
"image :return np.array: unique colors \"\"\" # Simplifies the handling by merging the",
"parameter of config is false if 'dynamic_color_space_active' not in self.vision_config or \\ not",
"Publishes the current color space via ColorSpace-message. :param Image image_msg: 'image_raw'-message :return: None",
"Get color space from queue color_space = self.queue_to_color_space(self.color_value_queue) # Create ColorSpace-message color_space_msg =",
"# type: (np.array, np.array) -> set \"\"\" Generates a whitelist of allowed colors",
"= vision_config['dynamic_color_space_queue_max_size'] self.color_value_queue = deque(maxlen=self.queue_max_size) self.pointfinder = Pointfinder( self.debug_printer, vision_config['dynamic_color_space_threshold'], vision_config['dynamic_color_space_kernel_radius']) self.heuristic =",
"queue color_space = self.queue_to_color_space(self.color_value_queue) # Create ColorSpace-message color_space_msg = ColorSpace() color_space_msg.header.frame_id = image_msg.header.frame_id",
"code) :param np.array input_matrix: serialized colors :return: original colors with 3 channels \"\"\"",
"__init__(self): # type: () -> None \"\"\" DynamicColorSpace is a ROS node, that",
"This node subscribes to an Image-message (default: image_raw) and to the 'vision_config'-message. This",
"= image_msg.header.stamp color_space_msg.blue = color_space[:,0].tolist() color_space_msg.green = color_space[:,1].tolist() color_space_msg.red = color_space[:,2].tolist() # Publish",
"type: (Config) -> None \"\"\" This method is called by the 'vision_config'-message subscriber.",
"image_age = rospy.get_rostime() - image_msg.header.stamp if image_age.to_sec() > 0.1: self.debug_printer.info('Dynamic color space: Dropped",
"None \"\"\" # Load dict from string in yaml-format in msg.data vision_config =",
"an input image. :param np.array image: image :return np.array: unique colors \"\"\" #",
"color_set.intersection(whitelist) # Restructures the color channels return self.deserialize(np.array(list(color_set))) def recalculate(self, image, mask): #",
"image_msg.header.stamp color_space_msg.blue = color_space[:,0].tolist() color_space_msg.green = color_space[:,1].tolist() color_space_msg.red = color_space[:,2].tolist() # Publish ColorSpace-message",
"the serialization of colors into different channels. (Like a HTML color code) :param",
"dict from string in yaml-format in msg.data vision_config = yaml.load(msg.data) self.debug_printer = debug.DebugPrinter(",
"Initiating 'bitbots_dynamic_color_space' node. :return: None \"\"\" # Init package rospack = rospkg.RosPack() self.package_path",
"Print status of dynamic color space after toggeling 'dynamic_color_space_active' parameter if 'dynamic_color_space_active' not",
"it's value in the sum_array would be 0 self.kernel[int(np.size(self.kernel, 0) / 2), int(np.size(self.kernel,",
"not in self.vision_config or \\ vision_config['dynamic_color_space_active'] != self.vision_config['dynamic_color_space_active']: if vision_config['dynamic_color_space_active']: rospy.loginfo('Dynamic color space",
"3 color channels serialized_img = self.serialize(np.reshape(image, (1, int(image.size / 3), 3))[0]) # Returns",
"of the center element of the matrix to the negative of the count",
"over the field boundary :return np.array: colors under the field boundary \"\"\" #",
"# type: () -> None \"\"\" DynamicColorSpace is a ROS node, that is",
"M x M matrix of ONEs self.kernel = None self.kernel = np.ones((self.kernel_edge_size, self.kernel_edge_size))",
"self.kernel.size def get_coordinates_of_color_candidates(self, masked_image): # type (np.array) -> np.array \"\"\" Returns array of",
"set and removing duplicated colors color_set = set(color_list) # Generates whitelist whitelist =",
"colors that occurs in both mask partitions. :param np.array image: image :param np.array",
"np.array) \"\"\" Masks picture and returns the unique colors that occurs in both",
"(about 30 seconds) after changes through dynamic reconfigure :param Config msg: new 'vision_config'-message",
"self.deserialize(np.array(list(color_set))) def recalculate(self, image, mask): # type: (np.array, np.array) -> set \"\"\" Generates",
"color_space = np.array([]).reshape(0,3) # Stack every color space in the queue for new_color_value_list",
"Image-message from Image-message subscriber :return: None \"\"\" # Turn off dynamic color space,",
"self.color_detector = color.DynamicPixelListColorDetector( self.debug_printer, self.package_path, vision_config) self.field_boundary_detector = field_boundary.FieldBoundaryDetector( self.color_detector, vision_config, self.debug_printer, used_by_dyn_color_detector=True)",
"of ColorSpace-messages if 'ROS_dynamic_color_space_msg_topic' not in self.vision_config or \\ self.vision_config['ROS_dynamic_color_space_msg_topic'] != vision_config['ROS_dynamic_color_space_msg_topic']: if",
"vision_config['ROS_dynamic_color_space_msg_topic']: if hasattr(self, 'pub_color_space'): self.pub_color_space.unregister() self.pub_color_space = rospy.Publisher( vision_config['ROS_dynamic_color_space_msg_topic'], ColorSpace, queue_size=1) # Set",
"Converting the ROS image message to CV2-image image = self.bridge.imgmsg_to_cv2(image_msg, 'bgr8') # Get",
"# Create ColorSpace-message color_space_msg = ColorSpace() color_space_msg.header.frame_id = image_msg.header.frame_id color_space_msg.header.stamp = image_msg.header.stamp color_space_msg.blue",
"(np.array) -> np.array \"\"\" Serializes the different color channels of a list of",
"not in self.vision_config or \\ not self.vision_config['dynamic_color_space_active']: return # Drops old images image_age",
"type: (np.array) -> np.array \"\"\" Serializes the different color channels of a list",
"def serialize(self, input_matrix): # type: (np.array) -> np.array \"\"\" Serializes the different color",
"queue: color_space = np.append(color_space, new_color_value_list[:,:], axis=0) # Return a color space, which contains",
"or \\ self.vision_config['ROS_img_msg_topic'] != vision_config['ROS_img_msg_topic']: if hasattr(self, 'sub_image_msg'): self.sub_image_msg.unregister() self.sub_image_msg = rospy.Subscriber( vision_config['ROS_img_msg_topic'],",
"mask=255 - mask)), self.get_unique_colors(cv2.bitwise_and(image, image, mask=mask))) def get_unique_colors(self, image): # type: (np.array) ->",
"(new_matrix[:, 0] * 256 ** 2) - (new_matrix[:, 1] * 256)), dtype=np.uint8) return",
"all pixels with a higher true-color / false-color ratio than the threshold return",
"(np.array) -> np.array \"\"\" Calculates unique color for an input image. :param np.array",
"as np from cv_bridge import CvBridge from collections import deque from sensor_msgs.msg import",
"# Return a color space, which contains all colors from the queue return",
"field boundary :return np.array: colors under the field boundary \"\"\" # Calls a",
"the field boundary \"\"\" # Calls a function to calculate the number of",
"at pixel coordinates from given list. :param np.array image: image :param np.array coordinate_list:",
"published. :param Image image_msg: Image-message :return: None \"\"\" # Converting the ROS image",
"# Get unique color values from the candidate pixels color_candidates = self.get_unique_color_values(image, pixel_coordinates)",
"field-boundary-mask. :param np.array color_list: list of color values, that need to be filtered",
"the matrix to the negative of the count of the matrix elements #",
"element if colors.size > 0: unique_colors = np.unique(colors, axis=0) else: unique_colors = colors",
"This method handles the processing of an Image-message. New colors are calculated, appended",
"ColorSpace() color_space_msg.header.frame_id = image_msg.header.frame_id color_space_msg.header.stamp = image_msg.header.stamp color_space_msg.blue = color_space[:,0].tolist() color_space_msg.green = color_space[:,1].tolist()",
"Restructures the color channels return self.deserialize(np.array(list(color_set))) def recalculate(self, image, mask): # type: (np.array,",
"to an Image-message (default: image_raw) and to the 'vision_config'-message. This node publishes ColorSpace-messages.",
"# type: (Image) -> None \"\"\" This method handles the processing of an",
"int) -> None \"\"\" Pointfinder is used to find false-color pixels with higher",
"hasattr(self, 'color_value_queue'): self.color_value_queue.clear() # Set params self.queue_max_size = vision_config['dynamic_color_space_queue_max_size'] self.color_value_queue = deque(maxlen=self.queue_max_size) self.pointfinder",
"np.array input_matrix: list of colors values with 3 channels :return: list of serialized",
"colors \"\"\" # Simplifies the handling by merging the 3 color channels serialized_img",
"1] = np.array((input_matrix - (new_matrix[:, 0] * 256 ** 2)) / 256, dtype=np.uint8)",
"else: unique_colors = colors return unique_colors def get_new_dynamic_colors(self, image): # type: (np.array) ->",
"* 256 ** 2)) / 256, dtype=np.uint8) new_matrix[:, 2] = np.array((input_matrix - (new_matrix[:,",
"false-color pixels with higher true-color / false-color ratio as threshold in their surrounding",
"def run(self, color_list, image, mask): # type: (np.array, np.array, np.array) -> np.array \"\"\"",
"elements # In case the value of this pixel is 1, it's value",
"self.pub_color_space.publish(color_space_msg) class Pointfinder(): def __init__(self, debug_printer, threshold, kernel_radius): # type: (DebugPrinter, float, int)",
"from bitbots_vision.vision_modules import field_boundary, color, debug, evaluator class DynamicColorSpace: def __init__(self): # type:",
"surrounding in masked image. :param np.array masked_image: masked image :return np.array: list of",
"a given image at pixel coordinates from given list. :param np.array image: image",
"0] = np.array(input_matrix // 256 ** 2, dtype=np.uint8) new_matrix[:, 1] = np.array((input_matrix -",
"self.handle_image(image_msg) def handle_image(self, image_msg): # type: (Image) -> None \"\"\" This method handles",
"np.array: colors under the field boundary \"\"\" # Calls a function to calculate",
"occur under the field boundary and have no occurrences over the field boundary",
"and have no occurrences over the field boundary get picked. :param DebugPrinter debug_printer:",
"# Takes only whitelisted values color_set = color_set.intersection(whitelist) # Restructures the color channels",
"\"\"\" # Simplifies the handling by merging the three color channels color_list =",
"the center element of the matrix to the negative of the count of",
"channels serialized_img = self.serialize(np.reshape(image, (1, int(image.size / 3), 3))[0]) # Returns unique colors",
"Masks new image with current color space mask_image = self.color_detector.mask_image(image) # Get mask",
"0.1: self.debug_printer.info('Dynamic color space: Dropped Image-message', 'image') return self.handle_image(image_msg) def handle_image(self, image_msg): #",
"a color space, which contains all colors from the queue return color_space def",
"np.array image: image :param np.array mask: field-boundary-mask :return set: whitelist \"\"\" # Generates",
"different channels. (Like a HTML color code) :param np.array input_matrix: serialized colors :return:",
"-> None \"\"\" This method handles the processing of an Image-message. New colors",
"* self.kernel_radius + 1 # Defines kernel # Init kernel as M x",
"requires list with at least one element if colors.size > 0: unique_colors =",
"have no occurrences over the field boundary get picked. :param DebugPrinter debug_printer: Debug-printer",
"** 2)) / 256, dtype=np.uint8) new_matrix[:, 2] = np.array((input_matrix - (new_matrix[:, 0] *",
"x M matrix of ONEs self.kernel = None self.kernel = np.ones((self.kernel_edge_size, self.kernel_edge_size)) #",
"\"\"\" Returns array of unique colors values from a given image at pixel",
"# The message topic name MUST be the same as in the config",
"/usr/bin/env python3 import cv2 import yaml import rospy import rospkg import numpy as",
"from image at given coordinates colors = image[coordinate_list[0], coordinate_list[1]] # np.unique requires list",
"relative to the field boundary. Only colors that occur under the field boundary",
"type: (Image) -> None \"\"\" This method handles the processing of an Image-message.",
"original colors with 3 channels \"\"\" new_matrix = np.zeros((input_matrix.size, 3)) new_matrix[:, 0] =",
"cv_bridge import CvBridge from collections import deque from sensor_msgs.msg import Image from bitbots_msgs.msg",
"true-color / false-color ratio than the threshold return np.array(np.where(sum_array > self.threshold * (self.kernel.size",
"type: (deque) -> np.array \"\"\" Returns color space as array of all queue",
":param np.array image: image :return np.array: array of new dynamic color values \"\"\"",
"vision_config def image_callback(self, image_msg): # type: (Image) -> None \"\"\" This method is",
"1 # Defines kernel # Init kernel as M x M matrix of",
"DynamicColorSpace: def __init__(self): # type: () -> None \"\"\" DynamicColorSpace is a ROS",
"import field_boundary, color, debug, evaluator class DynamicColorSpace: def __init__(self): # type: () ->",
"color_list: list of color values, that need to be filtered :param np.array image:",
"Create list of color values from image at given coordinates colors = image[coordinate_list[0],",
"= np.append(color_space, new_color_value_list[:,:], axis=0) # Return a color space, which contains all colors",
"images image_age = rospy.get_rostime() - image_msg.header.stamp if image_age.to_sec() > 0.1: self.debug_printer.info('Dynamic color space:",
"** 2) - (new_matrix[:, 1] * 256)), dtype=np.uint8) return new_matrix if __name__ ==",
"surrounding the center element of kernel matrix, defines relevant surrounding of pixel :return:",
"Filters new color space colors according to their position relative to the field",
"# Returns all pixels with a higher true-color / false-color ratio than the",
"unique_colors def get_new_dynamic_colors(self, image): # type: (np.array) -> np.array \"\"\" Returns array of",
"image, mask): # type: (np.array, np.array) -> set \"\"\" Generates a whitelist of",
"Only colors that occur under the field boundary and have no occurrences over",
"space after toggeling 'dynamic_color_space_active' parameter if 'dynamic_color_space_active' not in self.vision_config or \\ vision_config['dynamic_color_space_active']",
"debug_printer, threshold, kernel_radius): # type: (DebugPrinter, float, int) -> None \"\"\" Pointfinder is",
"image, mask=255 - mask)), self.get_unique_colors(cv2.bitwise_and(image, image, mask=mask))) def get_unique_colors(self, image): # type: (np.array)",
"if hasattr(self, 'sub_image_msg'): self.sub_image_msg.unregister() self.sub_image_msg = rospy.Subscriber( vision_config['ROS_img_msg_topic'], Image, self.image_callback, queue_size=vision_config['ROS_img_queue_size'], tcp_nodelay=True, buff_size=60000000)",
"ROS node, that is used by the vision node to better recognize the",
":return np.array: array of new dynamic color values \"\"\" # Masks new image",
":return: list of serialized colors \"\"\" return np.array( np.multiply(input_matrix[:, 0], 256 ** 2)",
"'vision_config', Config, self.vision_config_callback, queue_size=1, tcp_nodelay=True) rospy.spin() def vision_config_callback(self, msg): # type: (Config) ->",
"colors \"\"\" return np.array( np.multiply(input_matrix[:, 0], 256 ** 2) \\ + np.multiply(input_matrix[:, 1],",
"dynamic color values \"\"\" # Masks new image with current color space mask_image",
":param DebugPrinter debug_printer: Debug-printer :return: None \"\"\" self.debug_printer = debug_printer def run(self, color_list,",
"vision_config, self.debug_printer, used_by_dyn_color_detector=True) # Reset queue if hasattr(self, 'color_value_queue'): self.color_value_queue.clear() # Set params",
"(Image) -> None \"\"\" Publishes the current color space via ColorSpace-message. :param Image",
"of this pixel is 1, it's value in the sum_array would be 0",
"self.vision_config['ROS_dynamic_color_space_msg_topic'] != vision_config['ROS_dynamic_color_space_msg_topic']: if hasattr(self, 'pub_color_space'): self.pub_color_space.unregister() self.pub_color_space = rospy.Publisher( vision_config['ROS_dynamic_color_space_msg_topic'], ColorSpace, queue_size=1)",
"color_space[:,2].tolist() # Publish ColorSpace-message self.pub_color_space.publish(color_space_msg) class Pointfinder(): def __init__(self, debug_printer, threshold, kernel_radius): #",
"color space color_space = np.array([]).reshape(0,3) # Stack every color space in the queue",
"values :return np.array: color space \"\"\" # Initializes an empty color space color_space",
"# type: (np.array, np.array) -> np.array \"\"\" Returns array of unique colors values",
"(np.array) -> np.array \"\"\" Returns array of pixel coordinates of color candidates. Color",
"self.debug_printer, self.package_path, vision_config) self.field_boundary_detector = field_boundary.FieldBoundaryDetector( self.color_detector, vision_config, self.debug_printer, used_by_dyn_color_detector=True) # Reset queue",
"type: (np.array, np.array) -> set \"\"\" Generates a whitelist of allowed colors using",
"base color space files. This node subscribes to an Image-message (default: image_raw) and",
"be 0 self.kernel[int(np.size(self.kernel, 0) / 2), int(np.size(self.kernel, 1) / 2)] = - self.kernel.size",
"int(np.size(self.kernel, 1) / 2)] = - self.kernel.size def get_coordinates_of_color_candidates(self, masked_image): # type (np.array)",
"# Generates whitelist colors_over_field_boundary, colors_under_field_boundary = self.unique_colors_for_partitions(image, mask) return set(colors_under_field_boundary) - set(colors_over_field_boundary) def",
"def deserialize(self, input_matrix): # type: (np.array) -> np.array \"\"\" Resolves the serialization of",
"color space \"\"\" # Initializes an empty color space color_space = np.array([]).reshape(0,3) #",
"vision_config['vision_debug_printer_classes'])) self.runtime_evaluator = evaluator.RuntimeEvaluator(None) # Print status of dynamic color space after toggeling",
"vision node to better recognize the field color. DynamicColorSpace is able to calculate",
"image at given coordinates colors = image[coordinate_list[0], coordinate_list[1]] # np.unique requires list with",
"large, even when the size is limeted to 1. That's, why we drop",
"-> None \"\"\" This method is called by the 'vision_config'-message subscriber. Load and",
"not None: # Get array of pixel coordinates of color candidates pixel_coordinates =",
"pixel_coordinates) # Filters the colors using the heuristic. colors = np.array(self.heuristic.run(color_candidates, image, mask),",
"new_color_value_list in queue: color_space = np.append(color_space, new_color_value_list[:,:], axis=0) # Return a color space,",
"\\ + input_matrix[:, 2], dtype=np.int32) def deserialize(self, input_matrix): # type: (np.array) -> np.array",
"colors are calculated, appended to queue and published. :param Image image_msg: Image-message :return:",
"0: unique_colors = np.unique(colors, axis=0) else: unique_colors = colors return unique_colors def get_new_dynamic_colors(self,",
"collections import deque from sensor_msgs.msg import Image from bitbots_msgs.msg import ColorSpace, Config from",
"dtype=np.uint8) new_matrix[:, 1] = np.array((input_matrix - (new_matrix[:, 0] * 256 ** 2)) /",
"debug.DebugPrinter( debug_classes=debug.DebugPrinter.generate_debug_class_list_from_string( vision_config['vision_debug_printer_classes'])) self.runtime_evaluator = evaluator.RuntimeEvaluator(None) # Print status of dynamic color space",
"least one element if colors.size > 0: unique_colors = np.unique(colors, axis=0) else: unique_colors",
"the unique colors that occurs in both mask partitions. :param np.array image: image",
"def unique_colors_for_partitions(self, image, mask): # type: (np.array, np.array) -> (np.array, np.array) \"\"\" Masks",
"self.color_detector.mask_image(image) # Get mask from field_boundary detector self.field_boundary_detector.set_image(image) mask = self.field_boundary_detector.get_mask() if mask",
"Generates whitelist whitelist = self.recalculate(image, mask) # Takes only whitelisted values color_set =",
"\\ not self.vision_config['dynamic_color_space_active']: return # Drops old images image_age = rospy.get_rostime() - image_msg.header.stamp",
"(Image) -> None \"\"\" This method is called by the Image-message subscriber. Old",
"\"\"\" This method filters a given list of colors using the original image",
"CvBridge() # Init params self.vision_config = {} # Subscribe to 'vision_config'-message # The",
"is 1, it's value in the sum_array would be 0 self.kernel[int(np.size(self.kernel, 0) /",
"self.pointfinder.get_coordinates_of_color_candidates(mask_image) # Get unique color values from the candidate pixels color_candidates = self.get_unique_color_values(image,",
"\"\"\" # Calls a function to calculate the number of occurrences of all",
"is able to calculate dynamically changing color spaces to accommodate e.g. changing lighting",
"evaluator class DynamicColorSpace: def __init__(self): # type: () -> None \"\"\" DynamicColorSpace is",
"color code) :param np.array input_matrix: list of colors values with 3 channels :return:",
"self.bridge = CvBridge() # Init params self.vision_config = {} # Subscribe to 'vision_config'-message",
"set(colors_over_field_boundary) def unique_colors_for_partitions(self, image, mask): # type: (np.array, np.array) -> (np.array, np.array) \"\"\"",
"> self.threshold * (self.kernel.size - 1))) class Heuristic: def __init__(self, debug_printer): # type:",
"# Init kernel as M x M matrix of ONEs self.kernel = None",
"the threshold return np.array(np.where(sum_array > self.threshold * (self.kernel.size - 1))) class Heuristic: def",
"boundary get picked. :param DebugPrinter debug_printer: Debug-printer :return: None \"\"\" self.debug_printer = debug_printer",
"image_msg): # type: (Image) -> None \"\"\" Publishes the current color space via",
"in the queue for new_color_value_list in queue: color_space = np.append(color_space, new_color_value_list[:,:], axis=0) #",
"axis=0) def serialize(self, input_matrix): # type: (np.array) -> np.array \"\"\" Serializes the different",
"\\ vision_config['dynamic_color_space_active'] != self.vision_config['dynamic_color_space_active']: if vision_config['dynamic_color_space_active']: rospy.loginfo('Dynamic color space turned ON.') else: rospy.logwarn('Dynamic",
":param Image image_msg: 'image_raw'-message :return: None \"\"\" # Get color space from queue",
"ColorSpace-message self.pub_color_space.publish(color_space_msg) class Pointfinder(): def __init__(self, debug_printer, threshold, kernel_radius): # type: (DebugPrinter, float,",
"This callback is delayed (about 30 seconds) after changes through dynamic reconfigure :param",
"colors_under_field_boundary = self.unique_colors_for_partitions(image, mask) return set(colors_under_field_boundary) - set(colors_over_field_boundary) def unique_colors_for_partitions(self, image, mask): #",
"given list. :param np.array image: image :param np.array coordinate_list: list of pixel coordinates",
"changes. This callback is delayed (about 30 seconds) after changes through dynamic reconfigure",
"higher true-color / false-color ratio as threshold in their surrounding in masked image.",
"image :param np.array mask: binary field-boundary-mask :return np.array: filtered list of colors \"\"\"",
"color.DynamicPixelListColorDetector( self.debug_printer, self.package_path, vision_config) self.field_boundary_detector = field_boundary.FieldBoundaryDetector( self.color_detector, vision_config, self.debug_printer, used_by_dyn_color_detector=True) # Reset",
"color_space def publish(self, image_msg): # type: (Image) -> None \"\"\" Publishes the current",
"field-boundary-mask :return np.array: filtered list of colors \"\"\" # Simplifies the handling by",
"colors from image colors = self.get_new_dynamic_colors(image) # Add new colors to the queue",
"when the size is limeted to 1. That's, why we drop old images",
"None \"\"\" # Init package rospack = rospkg.RosPack() self.package_path = rospack.get_path('bitbots_vision') rospy.init_node('bitbots_dynamic_color_space') rospy.loginfo('Initializing",
"values were filtered by the heuristic. :param np.array image: image :return np.array: array",
"threshold self.kernel_radius = kernel_radius self.kernel_edge_size = 2 * self.kernel_radius + 1 # Defines",
"'bgr8') # Get new dynamic colors from image colors = self.get_new_dynamic_colors(image) # Add",
"a HTML color code) :param np.array input_matrix: serialized colors :return: original colors with",
"spaces to accommodate e.g. changing lighting conditions or to compensate for not optimized",
"# Init package rospack = rospkg.RosPack() self.package_path = rospack.get_path('bitbots_vision') rospy.init_node('bitbots_dynamic_color_space') rospy.loginfo('Initializing dynamic color-space...')",
"colors values with 3 channels :return: list of serialized colors \"\"\" return np.array(",
"self.package_path, vision_config) self.field_boundary_detector = field_boundary.FieldBoundaryDetector( self.color_detector, vision_config, self.debug_printer, used_by_dyn_color_detector=True) # Reset queue if",
"mask) # Takes only whitelisted values color_set = color_set.intersection(whitelist) # Restructures the color",
"\\ self.vision_config['ROS_img_msg_topic'] != vision_config['ROS_img_msg_topic']: if hasattr(self, 'sub_image_msg'): self.sub_image_msg.unregister() self.sub_image_msg = rospy.Subscriber( vision_config['ROS_img_msg_topic'], Image,",
"method is called by the 'vision_config'-message subscriber. Load and update vision config. Handle",
"color_space = self.queue_to_color_space(self.color_value_queue) # Create ColorSpace-message color_space_msg = ColorSpace() color_space_msg.header.frame_id = image_msg.header.frame_id color_space_msg.header.stamp",
"the current color space via ColorSpace-message. :param Image image_msg: 'image_raw'-message :return: None \"\"\"",
"import rospkg import numpy as np from cv_bridge import CvBridge from collections import",
"able to calculate dynamically changing color spaces to accommodate e.g. changing lighting conditions",
"# Init params self.debug_printer = debug_printer self.threshold = threshold self.kernel_radius = kernel_radius self.kernel_edge_size",
"evaluator.RuntimeEvaluator(None) # Print status of dynamic color space after toggeling 'dynamic_color_space_active' parameter if",
"same as in the config publisher in vision.py self.sub_vision_config_msg = rospy.Subscriber( 'vision_config', Config,",
"would be 0 self.kernel[int(np.size(self.kernel, 0) / 2), int(np.size(self.kernel, 1) / 2)] = -",
"Returns array of pixel coordinates of color candidates. Color candidates are false-color pixels",
"config publisher in vision.py self.sub_vision_config_msg = rospy.Subscriber( 'vision_config', Config, self.vision_config_callback, queue_size=1, tcp_nodelay=True) rospy.spin()",
"self.recalculate(image, mask) # Takes only whitelisted values color_set = color_set.intersection(whitelist) # Restructures the",
"= CvBridge() # Init params self.vision_config = {} # Subscribe to 'vision_config'-message #",
"of new dynamic color values \"\"\" # Masks new image with current color",
"self.heuristic = Heuristic(self.debug_printer) # Subscribe to Image-message if 'ROS_img_msg_topic' not in self.vision_config or",
"new dynamic colors from image colors = self.get_new_dynamic_colors(image) # Add new colors to",
"rospy.get_rostime() - image_msg.header.stamp if image_age.to_sec() > 0.1: self.debug_printer.info('Dynamic color space: Dropped Image-message', 'image')",
"of pixel coordinates of color candidates pixel_coordinates = self.pointfinder.get_coordinates_of_color_candidates(mask_image) # Get unique color",
"Color- and FieldBoundaryDetector self.color_detector = color.DynamicPixelListColorDetector( self.debug_printer, self.package_path, vision_config) self.field_boundary_detector = field_boundary.FieldBoundaryDetector( self.color_detector,",
"# Normalizes the masked image to values of 1 or 0 normalized_image =",
"np.array input_matrix: serialized colors :return: original colors with 3 channels \"\"\" new_matrix =",
"Turn off dynamic color space, if parameter of config is false if 'dynamic_color_space_active'",
":param Config msg: new 'vision_config'-message subscriber :return: None \"\"\" # Load dict from",
"1) / 2)] = - self.kernel.size def get_coordinates_of_color_candidates(self, masked_image): # type (np.array) ->",
"HTML color code) :param np.array input_matrix: serialized colors :return: original colors with 3",
"sum_array = cv2.filter2D(normalized_image, -1, self.kernel, borderType=0) # Returns all pixels with a higher",
"= color_set.intersection(whitelist) # Restructures the color channels return self.deserialize(np.array(list(color_set))) def recalculate(self, image, mask):",
"color candidates pixel_coordinates = self.pointfinder.get_coordinates_of_color_candidates(mask_image) # Get unique color values from the candidate",
"kernel_radius): # type: (DebugPrinter, float, int) -> None \"\"\" Pointfinder is used to",
"- image_msg.header.stamp if image_age.to_sec() > 0.1: self.debug_printer.info('Dynamic color space: Dropped Image-message', 'image') return",
"self.kernel_edge_size = 2 * self.kernel_radius + 1 # Defines kernel # Init kernel",
"color_space = np.append(color_space, new_color_value_list[:,:], axis=0) # Return a color space, which contains all",
"np.array: array of new dynamic color values \"\"\" # Masks new image with",
"import yaml import rospy import rospkg import numpy as np from cv_bridge import",
"None \"\"\" # Get color space from queue color_space = self.queue_to_color_space(self.color_value_queue) # Create",
"threshold in their surrounding in masked image. :param DebugPrinter: debug-printer :param float threshold:",
"self.color_detector, vision_config, self.debug_printer, used_by_dyn_color_detector=True) # Reset queue if hasattr(self, 'color_value_queue'): self.color_value_queue.clear() # Set",
"channels color_list = self.serialize(color_list) # Making a set and removing duplicated colors color_set",
"the colors using the heuristic. colors = np.array(self.heuristic.run(color_candidates, image, mask), dtype=np.int32) return colors",
"list of colors in an single channel. (Like a HTML color code) :param",
"value of this pixel is 1, it's value in the sum_array would be",
"is false if 'dynamic_color_space_active' not in self.vision_config or \\ not self.vision_config['dynamic_color_space_active']: return #",
"coordinates of color candidates. Color candidates are false-color pixels with a higher true-color/",
"threshold return np.array(np.where(sum_array > self.threshold * (self.kernel.size - 1))) class Heuristic: def __init__(self,",
"def get_unique_color_values(self, image, coordinate_list): # type: (np.array, np.array) -> np.array \"\"\" Returns array",
"color values from image at pixel coordinates \"\"\" # Create list of color",
"color space, which contains all colors from the queue return color_space def publish(self,",
"() -> None \"\"\" DynamicColorSpace is a ROS node, that is used by",
"space: Dropped Image-message', 'image') return self.handle_image(image_msg) def handle_image(self, image_msg): # type: (Image) ->",
"self.pub_color_space = rospy.Publisher( vision_config['ROS_dynamic_color_space_msg_topic'], ColorSpace, queue_size=1) # Set Color- and FieldBoundaryDetector self.color_detector =",
"msg: new 'vision_config'-message subscriber :return: None \"\"\" # Load dict from string in",
"\"\"\" Pointfinder is used to find false-color pixels with higher true-color / false-color",
"images manually. :param Image image_msg: new Image-message from Image-message subscriber :return: None \"\"\"",
"(new_matrix[:, 0] * 256 ** 2)) / 256, dtype=np.uint8) new_matrix[:, 2] = np.array((input_matrix",
"# Create list of color values from image at given coordinates colors =",
"# Drops old images image_age = rospy.get_rostime() - image_msg.header.stamp if image_age.to_sec() > 0.1:",
"color space files. This node subscribes to an Image-message (default: image_raw) and to",
"old images manually. :param Image image_msg: new Image-message from Image-message subscriber :return: None",
"np.array: colors over the field boundary :return np.array: colors under the field boundary",
"color candidates. Color candidates are false-color pixels with a higher true-color/ false-color ratio",
"raw vision image :param np.array mask: binary field-boundary-mask :return np.array: filtered list of",
"def image_callback(self, image_msg): # type: (Image) -> None \"\"\" This method is called",
"# Subscribe to Image-message if 'ROS_img_msg_topic' not in self.vision_config or \\ self.vision_config['ROS_img_msg_topic'] !=",
"image return np.unique(serialized_img, axis=0) def serialize(self, input_matrix): # type: (np.array) -> np.array \"\"\"",
"surrounding in masked image. :param DebugPrinter: debug-printer :param float threshold: necessary amount of",
"vision_config['ROS_img_msg_topic']: if hasattr(self, 'sub_image_msg'): self.sub_image_msg.unregister() self.sub_image_msg = rospy.Subscriber( vision_config['ROS_img_msg_topic'], Image, self.image_callback, queue_size=vision_config['ROS_img_queue_size'], tcp_nodelay=True,",
"calculated, appended to queue and published. :param Image image_msg: Image-message :return: None \"\"\"",
"1, it's value in the sum_array would be 0 self.kernel[int(np.size(self.kernel, 0) / 2),",
"3)) new_matrix[:, 0] = np.array(input_matrix // 256 ** 2, dtype=np.uint8) new_matrix[:, 1] =",
"color space in the queue for new_color_value_list in queue: color_space = np.append(color_space, new_color_value_list[:,:],",
"\"\"\" Generates a whitelist of allowed colors using the original image and the",
"why we drop old images manually. :param Image image_msg: new Image-message from Image-message",
"list of pixel coordinates :return np.array: array of unique color values from image",
"import ColorSpace, Config from bitbots_vision.vision_modules import field_boundary, color, debug, evaluator class DynamicColorSpace: def",
"np.array: filtered list of colors \"\"\" # Simplifies the handling by merging the",
"cv2 import yaml import rospy import rospkg import numpy as np from cv_bridge",
"!= vision_config['ROS_dynamic_color_space_msg_topic']: if hasattr(self, 'pub_color_space'): self.pub_color_space.unregister() self.pub_color_space = rospy.Publisher( vision_config['ROS_dynamic_color_space_msg_topic'], ColorSpace, queue_size=1) #",
"np.array \"\"\" Returns array of pixel coordinates of color candidates. Color candidates are",
"color values from the candidate pixels color_candidates = self.get_unique_color_values(image, pixel_coordinates) # Filters the",
"np.array(input_matrix // 256 ** 2, dtype=np.uint8) new_matrix[:, 1] = np.array((input_matrix - (new_matrix[:, 0]",
"array of pixel coordinates of color candidates pixel_coordinates = self.pointfinder.get_coordinates_of_color_candidates(mask_image) # Get unique",
"self.kernel, borderType=0) # Returns all pixels with a higher true-color / false-color ratio",
"colors in the image return np.unique(serialized_img, axis=0) def serialize(self, input_matrix): # type: (np.array)",
"np.unique(serialized_img, axis=0) def serialize(self, input_matrix): # type: (np.array) -> np.array \"\"\" Serializes the",
"to compensate for not optimized base color space files. This node subscribes to",
"** 2, dtype=np.uint8) new_matrix[:, 1] = np.array((input_matrix - (new_matrix[:, 0] * 256 **",
"\"\"\" Returns color space as array of all queue elements stacked, which contains",
"than the threshold return np.array(np.where(sum_array > self.threshold * (self.kernel.size - 1))) class Heuristic:",
"self.vision_config['dynamic_color_space_active']: if vision_config['dynamic_color_space_active']: rospy.loginfo('Dynamic color space turned ON.') else: rospy.logwarn('Dynamic color space turned",
"not in self.vision_config or \\ self.vision_config['ROS_img_msg_topic'] != vision_config['ROS_img_msg_topic']: if hasattr(self, 'sub_image_msg'): self.sub_image_msg.unregister() self.sub_image_msg",
"from Image-message subscriber :return: None \"\"\" # Turn off dynamic color space, if",
"input_matrix[:, 2], dtype=np.int32) def deserialize(self, input_matrix): # type: (np.array) -> np.array \"\"\" Resolves",
"unique_colors_for_partitions(self, image, mask): # type: (np.array, np.array) -> (np.array, np.array) \"\"\" Masks picture",
"np.array \"\"\" Returns array of unique colors values from a given image at",
"image_age.to_sec() > 0.1: self.debug_printer.info('Dynamic color space: Dropped Image-message', 'image') return self.handle_image(image_msg) def handle_image(self,",
"as in the config publisher in vision.py self.sub_vision_config_msg = rospy.Subscriber( 'vision_config', Config, self.vision_config_callback,",
"a field-boundary-mask. :param np.array color_list: list of color values, that need to be",
"int kernel_radius: radius surrounding the center element of kernel matrix, defines relevant surrounding",
"color space after toggeling 'dynamic_color_space_active' parameter if 'dynamic_color_space_active' not in self.vision_config or \\",
"space \"\"\" # Initializes an empty color space color_space = np.array([]).reshape(0,3) # Stack",
"import CvBridge from collections import deque from sensor_msgs.msg import Image from bitbots_msgs.msg import",
"image_callback(self, image_msg): # type: (Image) -> None \"\"\" This method is called by",
"threshold in their surrounding in masked image. :param np.array masked_image: masked image :return",
"false if 'dynamic_color_space_active' not in self.vision_config or \\ not self.vision_config['dynamic_color_space_active']: return # Drops",
"def __init__(self, debug_printer, threshold, kernel_radius): # type: (DebugPrinter, float, int) -> None \"\"\"",
"image_msg: Image-message :return: None \"\"\" # Converting the ROS image message to CV2-image",
"of the matrix elements # In case the value of this pixel is",
"returns the unique colors that occurs in both mask partitions. :param np.array image:",
"python3 import cv2 import yaml import rospy import rospkg import numpy as np",
"field boundary \"\"\" # Calls a function to calculate the number of occurrences",
"coordinate_list[1]] # np.unique requires list with at least one element if colors.size >",
"/ false-color ratio as threshold in their surrounding in masked image. :param DebugPrinter:",
"255, dtype=np.int16) # Calculates the count of neighbors for each pixel sum_array =",
"in the config publisher in vision.py self.sub_vision_config_msg = rospy.Subscriber( 'vision_config', Config, self.vision_config_callback, queue_size=1,",
"be the same as in the config publisher in vision.py self.sub_vision_config_msg = rospy.Subscriber(",
"of kernel matrix, defines relevant surrounding of pixel :return: None \"\"\" # Init",
"queue elements stacked, which contains all colors from the queue. :param dequeue queue:",
"np.array \"\"\" Returns color space as array of all queue elements stacked, which",
"array of new dynamically calculated color values. Those values were filtered by the",
"at least one element if colors.size > 0: unique_colors = np.unique(colors, axis=0) else:",
"using the original image and a field-boundary-mask. :param np.array color_list: list of color",
"compensate for not optimized base color space files. This node subscribes to an",
"Simplifies the handling by merging the three color channels color_list = self.serialize(color_list) #",
"cv2.filter2D(normalized_image, -1, self.kernel, borderType=0) # Returns all pixels with a higher true-color /",
"np.array: array of unique color values from image at pixel coordinates \"\"\" #",
"image at pixel coordinates from given list. :param np.array image: image :param np.array",
"serialized_img = self.serialize(np.reshape(image, (1, int(image.size / 3), 3))[0]) # Returns unique colors in",
"publisher of ColorSpace-messages if 'ROS_dynamic_color_space_msg_topic' not in self.vision_config or \\ self.vision_config['ROS_dynamic_color_space_msg_topic'] != vision_config['ROS_dynamic_color_space_msg_topic']:",
"image. :param np.array image: image :return np.array: unique colors \"\"\" # Simplifies the",
"which contains all colors from the queue. :param dequeue queue: queue of array",
"mask is not None: # Get array of pixel coordinates of color candidates",
"false-color ratio as threshold in their surrounding in masked image. :param np.array masked_image:",
"and published. :param Image image_msg: Image-message :return: None \"\"\" # Converting the ROS",
"That's, why we drop old images manually. :param Image image_msg: new Image-message from",
"method is called by the Image-message subscriber. Old Image-messages were dropped. Sometimes the",
"= self.serialize(color_list) # Making a set and removing duplicated colors color_set = set(color_list)",
"pixels with higher true-color / false-color ratio as threshold in their surrounding in",
"'dynamic_color_space_active' not in self.vision_config or \\ not self.vision_config['dynamic_color_space_active']: return # Drops old images",
"Init kernel as M x M matrix of ONEs self.kernel = None self.kernel",
"processing of an Image-message. New colors are calculated, appended to queue and published.",
"- self.kernel.size def get_coordinates_of_color_candidates(self, masked_image): # type (np.array) -> np.array \"\"\" Returns array",
"(Image) -> None \"\"\" This method handles the processing of an Image-message. New",
"candidate pixels color_candidates = self.get_unique_color_values(image, pixel_coordinates) # Filters the colors using the heuristic.",
"Returns array of unique colors values from a given image at pixel coordinates",
"// 256 ** 2, dtype=np.uint8) new_matrix[:, 1] = np.array((input_matrix - (new_matrix[:, 0] *",
"np.multiply(input_matrix[:, 1], 256) \\ + input_matrix[:, 2], dtype=np.int32) def deserialize(self, input_matrix): # type:",
"candidates are false-color pixels with a higher true-color/ false-color ratio as threshold in",
"the field boundary get picked. :param DebugPrinter debug_printer: Debug-printer :return: None \"\"\" self.debug_printer",
"Image image_msg: 'image_raw'-message :return: None \"\"\" # Get color space from queue color_space",
"the number of occurrences of all colors in the image return (self.get_unique_colors(cv2.bitwise_and(image, image,",
"color spaces to accommodate e.g. changing lighting conditions or to compensate for not",
"= np.floor_divide(masked_image, 255, dtype=np.int16) # Calculates the count of neighbors for each pixel",
"Pointfinder is used to find false-color pixels with higher true-color / false-color ratio",
"single channel. (Like a HTML color code) :param np.array input_matrix: list of colors",
"/ 2)] = - self.kernel.size def get_coordinates_of_color_candidates(self, masked_image): # type (np.array) -> np.array",
"\"\"\" Masks picture and returns the unique colors that occurs in both mask",
"list of indices \"\"\" # Normalizes the masked image to values of 1",
"matrix elements # In case the value of this pixel is 1, it's",
"buff_size=60000000) # https://github.com/ros/ros_comm/issues/536 self.vision_config = vision_config def image_callback(self, image_msg): # type: (Image) ->",
"a higher true-color / false-color ratio than the threshold return np.array(np.where(sum_array > self.threshold",
"- 1))) class Heuristic: def __init__(self, debug_printer): # type: (DebugPrinter) -> None \"\"\"",
"'ROS_dynamic_color_space_msg_topic' not in self.vision_config or \\ self.vision_config['ROS_dynamic_color_space_msg_topic'] != vision_config['ROS_dynamic_color_space_msg_topic']: if hasattr(self, 'pub_color_space'): self.pub_color_space.unregister()",
"image, mask), dtype=np.int32) return colors return np.array([[]]) def queue_to_color_space(self, queue): # type: (deque)",
"np.array mask: field-boundary-mask :return np.array: colors over the field boundary :return np.array: colors",
"false-color ratio than the threshold return np.array(np.where(sum_array > self.threshold * (self.kernel.size - 1)))",
"-> np.array \"\"\" Returns array of unique colors values from a given image",
"coordinates of color candidates pixel_coordinates = self.pointfinder.get_coordinates_of_color_candidates(mask_image) # Get unique color values from",
"colors according to their position relative to the field boundary. Only colors that",
"= field_boundary.FieldBoundaryDetector( self.color_detector, vision_config, self.debug_printer, used_by_dyn_color_detector=True) # Reset queue if hasattr(self, 'color_value_queue'): self.color_value_queue.clear()",
"to 'ROS_dynamic_color_space_msg_topic' self.publish(image_msg) def get_unique_color_values(self, image, coordinate_list): # type: (np.array, np.array) -> np.array",
"value of the center element of the matrix to the negative of the",
"rospy.loginfo('Dynamic color space turned ON.') else: rospy.logwarn('Dynamic color space turned OFF.') # Set",
"config is false if 'dynamic_color_space_active' not in self.vision_config or \\ not self.vision_config['dynamic_color_space_active']: return",
"1. That's, why we drop old images manually. :param Image image_msg: new Image-message",
"the field boundary and have no occurrences over the field boundary get picked.",
"of color values :return np.array: color space \"\"\" # Initializes an empty color",
"None \"\"\" # Turn off dynamic color space, if parameter of config is",
"original image and a field-boundary-mask. :param np.array color_list: list of color values, that",
"= set(color_list) # Generates whitelist whitelist = self.recalculate(image, mask) # Takes only whitelisted",
"space as array of all queue elements stacked, which contains all colors from",
"- set(colors_over_field_boundary) def unique_colors_for_partitions(self, image, mask): # type: (np.array, np.array) -> (np.array, np.array)",
"'image_raw'-message :return: None \"\"\" # Get color space from queue color_space = self.queue_to_color_space(self.color_value_queue)",
"an Image-message. New colors are calculated, appended to queue and published. :param Image",
"not optimized base color space files. This node subscribes to an Image-message (default:",
"channels. (Like a HTML color code) :param np.array input_matrix: serialized colors :return: original",
"by the 'vision_config'-message subscriber. Load and update vision config. Handle config changes. This",
"pixel coordinates from given list. :param np.array image: image :param np.array coordinate_list: list",
":return np.array: color space \"\"\" # Initializes an empty color space color_space =",
"tcp_nodelay=True, buff_size=60000000) # https://github.com/ros/ros_comm/issues/536 self.vision_config = vision_config def image_callback(self, image_msg): # type: (Image)",
"of new dynamically calculated color values. Those values were filtered by the heuristic.",
"deserialize(self, input_matrix): # type: (np.array) -> np.array \"\"\" Resolves the serialization of colors",
"New colors are calculated, appended to queue and published. :param Image image_msg: Image-message",
"in self.vision_config or \\ self.vision_config['ROS_dynamic_color_space_msg_topic'] != vision_config['ROS_dynamic_color_space_msg_topic']: if hasattr(self, 'pub_color_space'): self.pub_color_space.unregister() self.pub_color_space =",
"= - self.kernel.size def get_coordinates_of_color_candidates(self, masked_image): # type (np.array) -> np.array \"\"\" Returns",
"indices \"\"\" # Normalizes the masked image to values of 1 or 0",
"self.serialize(np.reshape(image, (1, int(image.size / 3), 3))[0]) # Returns unique colors in the image",
"of colors values with 3 channels :return: list of serialized colors \"\"\" return",
":return np.array: array of unique color values from image at pixel coordinates \"\"\"",
"image: image :param np.array mask: field-boundary-mask :return np.array: colors over the field boundary",
"* 256 ** 2) - (new_matrix[:, 1] * 256)), dtype=np.uint8) return new_matrix if",
"= debug.DebugPrinter( debug_classes=debug.DebugPrinter.generate_debug_class_list_from_string( vision_config['vision_debug_printer_classes'])) self.runtime_evaluator = evaluator.RuntimeEvaluator(None) # Print status of dynamic color",
"Filters the colors using the heuristic. colors = np.array(self.heuristic.run(color_candidates, image, mask), dtype=np.int32) return",
"list of color values from image at given coordinates colors = image[coordinate_list[0], coordinate_list[1]]",
"self.debug_printer = debug_printer self.threshold = threshold self.kernel_radius = kernel_radius self.kernel_edge_size = 2 *",
"color for an input image. :param np.array image: image :return np.array: unique colors",
"as M x M matrix of ONEs self.kernel = None self.kernel = np.ones((self.kernel_edge_size,",
"kernel matrix, defines relevant surrounding of pixel :return: None \"\"\" # Init params",
"coordinate_list): # type: (np.array, np.array) -> np.array \"\"\" Returns array of unique colors",
"filtered list of colors \"\"\" # Simplifies the handling by merging the three",
"to 1. That's, why we drop old images manually. :param Image image_msg: new",
"color space via ColorSpace-message. :param Image image_msg: 'image_raw'-message :return: None \"\"\" # Get",
"debug_printer self.threshold = threshold self.kernel_radius = kernel_radius self.kernel_edge_size = 2 * self.kernel_radius +",
"in their surrounding in masked image. :param np.array masked_image: masked image :return np.array:",
"new_matrix = np.zeros((input_matrix.size, 3)) new_matrix[:, 0] = np.array(input_matrix // 256 ** 2, dtype=np.uint8)",
"method filters a given list of colors using the original image and a",
"color_list = self.serialize(color_list) # Making a set and removing duplicated colors color_set =",
"dropped. Sometimes the queue gets to large, even when the size is limeted",
"input_matrix): # type: (np.array) -> np.array \"\"\" Resolves the serialization of colors into",
"Image-message', 'image') return self.handle_image(image_msg) def handle_image(self, image_msg): # type: (Image) -> None \"\"\"",
"if colors.size > 0: unique_colors = np.unique(colors, axis=0) else: unique_colors = colors return",
"to large, even when the size is limeted to 1. That's, why we",
"= 2 * self.kernel_radius + 1 # Defines kernel # Init kernel as",
"0] * 256 ** 2) - (new_matrix[:, 1] * 256)), dtype=np.uint8) return new_matrix",
":param np.array masked_image: masked image :return np.array: list of indices \"\"\" # Normalizes",
"are false-color pixels with a higher true-color/ false-color ratio as threshold in their",
"node, that is used by the vision node to better recognize the field",
"values from the candidate pixels color_candidates = self.get_unique_color_values(image, pixel_coordinates) # Filters the colors",
"(DebugPrinter, float, int) -> None \"\"\" Pointfinder is used to find false-color pixels",
"queue_to_color_space(self, queue): # type: (deque) -> np.array \"\"\" Returns color space as array",
"and the field-boundary-mask. :param np.array image: image :param np.array mask: field-boundary-mask :return set:",
"with 3 channels \"\"\" new_matrix = np.zeros((input_matrix.size, 3)) new_matrix[:, 0] = np.array(input_matrix //",
"Create ColorSpace-message color_space_msg = ColorSpace() color_space_msg.header.frame_id = image_msg.header.frame_id color_space_msg.header.stamp = image_msg.header.stamp color_space_msg.blue =",
"candidates. Color candidates are false-color pixels with a higher true-color/ false-color ratio as",
"mask: field-boundary-mask :return np.array: colors over the field boundary :return np.array: colors under",
"according to their position relative to the field boundary. Only colors that occur",
"from field_boundary detector self.field_boundary_detector.set_image(image) mask = self.field_boundary_detector.get_mask() if mask is not None: #",
"threshold: necessary amount of previously detected color in percentage :param int kernel_radius: radius",
"a function to calculate the number of occurrences of all colors in the",
"return (self.get_unique_colors(cv2.bitwise_and(image, image, mask=255 - mask)), self.get_unique_colors(cv2.bitwise_and(image, image, mask=mask))) def get_unique_colors(self, image): #",
"** 2) \\ + np.multiply(input_matrix[:, 1], 256) \\ + input_matrix[:, 2], dtype=np.int32) def",
"a higher true-color/ false-color ratio as threshold in their surrounding in masked image.",
"dtype=np.int32) def deserialize(self, input_matrix): # type: (np.array) -> np.array \"\"\" Resolves the serialization",
"delayed (about 30 seconds) after changes through dynamic reconfigure :param Config msg: new",
"mask): # type: (np.array, np.array) -> set \"\"\" Generates a whitelist of allowed",
"of the matrix to the negative of the count of the matrix elements",
"np.ones((self.kernel_edge_size, self.kernel_edge_size)) # Set value of the center element of the matrix to",
"colors :return: original colors with 3 channels \"\"\" new_matrix = np.zeros((input_matrix.size, 3)) new_matrix[:,",
"the queue. :param dequeue queue: queue of array of color values :return np.array:",
"for an input image. :param np.array image: image :return np.array: unique colors \"\"\"",
"Image-message subscriber :return: None \"\"\" # Turn off dynamic color space, if parameter",
"1))) class Heuristic: def __init__(self, debug_printer): # type: (DebugPrinter) -> None \"\"\" Filters",
"mask: binary field-boundary-mask :return np.array: filtered list of colors \"\"\" # Simplifies the",
"new_matrix[:, 2] = np.array((input_matrix - (new_matrix[:, 0] * 256 ** 2) - (new_matrix[:,",
"channel. (Like a HTML color code) :param np.array input_matrix: list of colors values",
"subscribes to an Image-message (default: image_raw) and to the 'vision_config'-message. This node publishes",
"masked image :return np.array: list of indices \"\"\" # Normalizes the masked image",
"-> np.array \"\"\" This method filters a given list of colors using the",
"new dynamic color values \"\"\" # Masks new image with current color space",
"1 or 0 normalized_image = np.floor_divide(masked_image, 255, dtype=np.int16) # Calculates the count of",
"set(colors_under_field_boundary) - set(colors_over_field_boundary) def unique_colors_for_partitions(self, image, mask): # type: (np.array, np.array) -> (np.array,",
"'sub_image_msg'): self.sub_image_msg.unregister() self.sub_image_msg = rospy.Subscriber( vision_config['ROS_img_msg_topic'], Image, self.image_callback, queue_size=vision_config['ROS_img_queue_size'], tcp_nodelay=True, buff_size=60000000) # https://github.com/ros/ros_comm/issues/536",
"changes through dynamic reconfigure :param Config msg: new 'vision_config'-message subscriber :return: None \"\"\"",
"__init__(self, debug_printer): # type: (DebugPrinter) -> None \"\"\" Filters new color space colors",
"new 'vision_config'-message subscriber :return: None \"\"\" # Load dict from string in yaml-format",
"the three color channels color_list = self.serialize(color_list) # Making a set and removing",
"\"\"\" # Init package rospack = rospkg.RosPack() self.package_path = rospack.get_path('bitbots_vision') rospy.init_node('bitbots_dynamic_color_space') rospy.loginfo('Initializing dynamic",
"heuristic. :param np.array image: image :return np.array: array of new dynamic color values",
"Get unique color values from the candidate pixels color_candidates = self.get_unique_color_values(image, pixel_coordinates) #",
"= image[coordinate_list[0], coordinate_list[1]] # np.unique requires list with at least one element if",
"kernel as M x M matrix of ONEs self.kernel = None self.kernel =",
"be filtered :param np.array image: raw vision image :param np.array mask: binary field-boundary-mask",
"into different channels. (Like a HTML color code) :param np.array input_matrix: serialized colors",
"# Init params self.vision_config = {} # Subscribe to 'vision_config'-message # The message",
"of colors into different channels. (Like a HTML color code) :param np.array input_matrix:",
"dynamic colors from image colors = self.get_new_dynamic_colors(image) # Add new colors to the",
"\"\"\" # Generates whitelist colors_over_field_boundary, colors_under_field_boundary = self.unique_colors_for_partitions(image, mask) return set(colors_under_field_boundary) - set(colors_over_field_boundary)",
"np.array: unique colors \"\"\" # Simplifies the handling by merging the 3 color",
"np.array \"\"\" Returns array of new dynamically calculated color values. Those values were",
"return # Drops old images image_age = rospy.get_rostime() - image_msg.header.stamp if image_age.to_sec() >",
"string in yaml-format in msg.data vision_config = yaml.load(msg.data) self.debug_printer = debug.DebugPrinter( debug_classes=debug.DebugPrinter.generate_debug_class_list_from_string( vision_config['vision_debug_printer_classes']))",
"color_space_msg.blue = color_space[:,0].tolist() color_space_msg.green = color_space[:,1].tolist() color_space_msg.red = color_space[:,2].tolist() # Publish ColorSpace-message self.pub_color_space.publish(color_space_msg)",
"self.sub_vision_config_msg = rospy.Subscriber( 'vision_config', Config, self.vision_config_callback, queue_size=1, tcp_nodelay=True) rospy.spin() def vision_config_callback(self, msg): #",
"np.array: color space \"\"\" # Initializes an empty color space color_space = np.array([]).reshape(0,3)",
"3 channels :return: list of serialized colors \"\"\" return np.array( np.multiply(input_matrix[:, 0], 256",
"value in the sum_array would be 0 self.kernel[int(np.size(self.kernel, 0) / 2), int(np.size(self.kernel, 1)",
"of color values from image at given coordinates colors = image[coordinate_list[0], coordinate_list[1]] #",
"Those values were filtered by the heuristic. :param np.array image: image :return np.array:",
"pixels with a higher true-color / false-color ratio than the threshold return np.array(np.where(sum_array",
"Reset queue if hasattr(self, 'color_value_queue'): self.color_value_queue.clear() # Set params self.queue_max_size = vision_config['dynamic_color_space_queue_max_size'] self.color_value_queue",
"\"\"\" # Get color space from queue color_space = self.queue_to_color_space(self.color_value_queue) # Create ColorSpace-message",
"color, debug, evaluator class DynamicColorSpace: def __init__(self): # type: () -> None \"\"\"",
"array of new dynamic color values \"\"\" # Masks new image with current",
"!= vision_config['ROS_img_msg_topic']: if hasattr(self, 'sub_image_msg'): self.sub_image_msg.unregister() self.sub_image_msg = rospy.Subscriber( vision_config['ROS_img_msg_topic'], Image, self.image_callback, queue_size=vision_config['ROS_img_queue_size'],",
"ratio than the threshold return np.array(np.where(sum_array > self.threshold * (self.kernel.size - 1))) class",
"true-color/ false-color ratio as threshold in their surrounding in masked image. :param np.array",
"image[coordinate_list[0], coordinate_list[1]] # np.unique requires list with at least one element if colors.size",
"hasattr(self, 'pub_color_space'): self.pub_color_space.unregister() self.pub_color_space = rospy.Publisher( vision_config['ROS_dynamic_color_space_msg_topic'], ColorSpace, queue_size=1) # Set Color- and",
"Generates whitelist colors_over_field_boundary, colors_under_field_boundary = self.unique_colors_for_partitions(image, mask) return set(colors_under_field_boundary) - set(colors_over_field_boundary) def unique_colors_for_partitions(self,",
"#! /usr/bin/env python3 import cv2 import yaml import rospy import rospkg import numpy",
"is used to find false-color pixels with higher true-color / false-color ratio as",
"space, if parameter of config is false if 'dynamic_color_space_active' not in self.vision_config or",
"three color channels color_list = self.serialize(color_list) # Making a set and removing duplicated",
"space turned ON.') else: rospy.logwarn('Dynamic color space turned OFF.') # Set publisher of",
"values from image at given coordinates colors = image[coordinate_list[0], coordinate_list[1]] # np.unique requires",
"if vision_config['dynamic_color_space_active']: rospy.loginfo('Dynamic color space turned ON.') else: rospy.logwarn('Dynamic color space turned OFF.')",
"current color space via ColorSpace-message. :param Image image_msg: 'image_raw'-message :return: None \"\"\" #",
"run(self, color_list, image, mask): # type: (np.array, np.array, np.array) -> np.array \"\"\" This",
"= self.recalculate(image, mask) # Takes only whitelisted values color_set = color_set.intersection(whitelist) # Restructures",
"3))[0]) # Returns unique colors in the image return np.unique(serialized_img, axis=0) def serialize(self,",
"space, which contains all colors from the queue return color_space def publish(self, image_msg):",
"return np.array( np.multiply(input_matrix[:, 0], 256 ** 2) \\ + np.multiply(input_matrix[:, 1], 256) \\",
"in the image return (self.get_unique_colors(cv2.bitwise_and(image, image, mask=255 - mask)), self.get_unique_colors(cv2.bitwise_and(image, image, mask=mask))) def",
"new colors to the queue self.color_value_queue.append(colors) # Publishes to 'ROS_dynamic_color_space_msg_topic' self.publish(image_msg) def get_unique_color_values(self,",
"if image_age.to_sec() > 0.1: self.debug_printer.info('Dynamic color space: Dropped Image-message', 'image') return self.handle_image(image_msg) def",
"or 0 normalized_image = np.floor_divide(masked_image, 255, dtype=np.int16) # Calculates the count of neighbors",
"Load and update vision config. Handle config changes. This callback is delayed (about",
"import numpy as np from cv_bridge import CvBridge from collections import deque from",
"get_coordinates_of_color_candidates(self, masked_image): # type (np.array) -> np.array \"\"\" Returns array of pixel coordinates",
"pixel coordinates \"\"\" # Create list of color values from image at given",
"# type: (np.array) -> np.array \"\"\" Returns array of new dynamically calculated color",
"None \"\"\" DynamicColorSpace is a ROS node, that is used by the vision",
"from string in yaml-format in msg.data vision_config = yaml.load(msg.data) self.debug_printer = debug.DebugPrinter( debug_classes=debug.DebugPrinter.generate_debug_class_list_from_string(",
"256, dtype=np.uint8) new_matrix[:, 2] = np.array((input_matrix - (new_matrix[:, 0] * 256 ** 2)",
"= self.queue_to_color_space(self.color_value_queue) # Create ColorSpace-message color_space_msg = ColorSpace() color_space_msg.header.frame_id = image_msg.header.frame_id color_space_msg.header.stamp =",
"to find false-color pixels with higher true-color / false-color ratio as threshold in",
"mask): # type: (np.array, np.array) -> (np.array, np.array) \"\"\" Masks picture and returns",
"false-color pixels with a higher true-color/ false-color ratio as threshold in their surrounding",
"def handle_image(self, image_msg): # type: (Image) -> None \"\"\" This method handles the",
"np.array) -> np.array \"\"\" This method filters a given list of colors using",
"and to the 'vision_config'-message. This node publishes ColorSpace-messages. Initiating 'bitbots_dynamic_color_space' node. :return: None",
"self.runtime_evaluator = evaluator.RuntimeEvaluator(None) # Print status of dynamic color space after toggeling 'dynamic_color_space_active'",
"-> None \"\"\" Publishes the current color space via ColorSpace-message. :param Image image_msg:",
"ColorSpace-messages. Initiating 'bitbots_dynamic_color_space' node. :return: None \"\"\" # Init package rospack = rospkg.RosPack()",
"type: () -> None \"\"\" DynamicColorSpace is a ROS node, that is used",
"0) / 2), int(np.size(self.kernel, 1) / 2)] = - self.kernel.size def get_coordinates_of_color_candidates(self, masked_image):",
"function to calculate the number of occurrences of all colors in the image",
"float threshold: necessary amount of previously detected color in percentage :param int kernel_radius:",
"Masks picture and returns the unique colors that occurs in both mask partitions.",
"np.array mask: field-boundary-mask :return set: whitelist \"\"\" # Generates whitelist colors_over_field_boundary, colors_under_field_boundary =",
"yaml.load(msg.data) self.debug_printer = debug.DebugPrinter( debug_classes=debug.DebugPrinter.generate_debug_class_list_from_string( vision_config['vision_debug_printer_classes'])) self.runtime_evaluator = evaluator.RuntimeEvaluator(None) # Print status of",
"field-boundary-mask. :param np.array image: image :param np.array mask: field-boundary-mask :return set: whitelist \"\"\"",
"Serializes the different color channels of a list of colors in an single",
"'color_value_queue'): self.color_value_queue.clear() # Set params self.queue_max_size = vision_config['dynamic_color_space_queue_max_size'] self.color_value_queue = deque(maxlen=self.queue_max_size) self.pointfinder =",
"Config from bitbots_vision.vision_modules import field_boundary, color, debug, evaluator class DynamicColorSpace: def __init__(self): #",
"import Image from bitbots_msgs.msg import ColorSpace, Config from bitbots_vision.vision_modules import field_boundary, color, debug,",
"normalized_image = np.floor_divide(masked_image, 255, dtype=np.int16) # Calculates the count of neighbors for each",
"Calculates unique color for an input image. :param np.array image: image :return np.array:",
"filtered :param np.array image: raw vision image :param np.array mask: binary field-boundary-mask :return",
"handles the processing of an Image-message. New colors are calculated, appended to queue",
"given coordinates colors = image[coordinate_list[0], coordinate_list[1]] # np.unique requires list with at least",
"vision_config['ROS_img_msg_topic'], Image, self.image_callback, queue_size=vision_config['ROS_img_queue_size'], tcp_nodelay=True, buff_size=60000000) # https://github.com/ros/ros_comm/issues/536 self.vision_config = vision_config def image_callback(self,",
"true-color / false-color ratio as threshold in their surrounding in masked image. :param",
":return np.array: filtered list of colors \"\"\" # Simplifies the handling by merging",
"the count of the matrix elements # In case the value of this",
"matrix of ONEs self.kernel = None self.kernel = np.ones((self.kernel_edge_size, self.kernel_edge_size)) # Set value",
"self.field_boundary_detector = field_boundary.FieldBoundaryDetector( self.color_detector, vision_config, self.debug_printer, used_by_dyn_color_detector=True) # Reset queue if hasattr(self, 'color_value_queue'):",
"turned ON.') else: rospy.logwarn('Dynamic color space turned OFF.') # Set publisher of ColorSpace-messages",
"# type: (np.array) -> np.array \"\"\" Serializes the different color channels of a",
"all queue elements stacked, which contains all colors from the queue. :param dequeue",
"color space mask_image = self.color_detector.mask_image(image) # Get mask from field_boundary detector self.field_boundary_detector.set_image(image) mask",
"import rospy import rospkg import numpy as np from cv_bridge import CvBridge from",
"return set(colors_under_field_boundary) - set(colors_over_field_boundary) def unique_colors_for_partitions(self, image, mask): # type: (np.array, np.array) ->",
"Subscribe to Image-message if 'ROS_img_msg_topic' not in self.vision_config or \\ self.vision_config['ROS_img_msg_topic'] != vision_config['ROS_img_msg_topic']:",
"under the field boundary and have no occurrences over the field boundary get",
"dtype=np.int16) # Calculates the count of neighbors for each pixel sum_array = cv2.filter2D(normalized_image,",
"need to be filtered :param np.array image: raw vision image :param np.array mask:",
"= Heuristic(self.debug_printer) # Subscribe to Image-message if 'ROS_img_msg_topic' not in self.vision_config or \\",
"{} # Subscribe to 'vision_config'-message # The message topic name MUST be the",
"> 0: unique_colors = np.unique(colors, axis=0) else: unique_colors = colors return unique_colors def",
"256 ** 2, dtype=np.uint8) new_matrix[:, 1] = np.array((input_matrix - (new_matrix[:, 0] * 256",
"rospy.spin() def vision_config_callback(self, msg): # type: (Config) -> None \"\"\" This method is",
"ON.') else: rospy.logwarn('Dynamic color space turned OFF.') # Set publisher of ColorSpace-messages if",
":return: original colors with 3 channels \"\"\" new_matrix = np.zeros((input_matrix.size, 3)) new_matrix[:, 0]",
"'vision_config'-message subscriber. Load and update vision config. Handle config changes. This callback is",
"vision_config['dynamic_color_space_queue_max_size'] self.color_value_queue = deque(maxlen=self.queue_max_size) self.pointfinder = Pointfinder( self.debug_printer, vision_config['dynamic_color_space_threshold'], vision_config['dynamic_color_space_kernel_radius']) self.heuristic = Heuristic(self.debug_printer)",
":param dequeue queue: queue of array of color values :return np.array: color space",
"\"\"\" Publishes the current color space via ColorSpace-message. :param Image image_msg: 'image_raw'-message :return:",
"space color_space = np.array([]).reshape(0,3) # Stack every color space in the queue for",
"masked_image: masked image :return np.array: list of indices \"\"\" # Normalizes the masked",
"= None self.kernel = np.ones((self.kernel_edge_size, self.kernel_edge_size)) # Set value of the center element",
"- (new_matrix[:, 1] * 256)), dtype=np.uint8) return new_matrix if __name__ == '__main__': DynamicColorSpace()",
"self.vision_config['ROS_img_msg_topic'] != vision_config['ROS_img_msg_topic']: if hasattr(self, 'sub_image_msg'): self.sub_image_msg.unregister() self.sub_image_msg = rospy.Subscriber( vision_config['ROS_img_msg_topic'], Image, self.image_callback,",
"kernel_radius: radius surrounding the center element of kernel matrix, defines relevant surrounding of",
"of color values, that need to be filtered :param np.array image: raw vision",
"list. :param np.array image: image :param np.array coordinate_list: list of pixel coordinates :return",
":param np.array mask: binary field-boundary-mask :return np.array: filtered list of colors \"\"\" #",
"Drops old images image_age = rospy.get_rostime() - image_msg.header.stamp if image_age.to_sec() > 0.1: self.debug_printer.info('Dynamic",
"None \"\"\" This method handles the processing of an Image-message. New colors are",
"list of colors \"\"\" # Simplifies the handling by merging the three color",
"self.debug_printer, used_by_dyn_color_detector=True) # Reset queue if hasattr(self, 'color_value_queue'): self.color_value_queue.clear() # Set params self.queue_max_size",
"queue_size=1) # Set Color- and FieldBoundaryDetector self.color_detector = color.DynamicPixelListColorDetector( self.debug_printer, self.package_path, vision_config) self.field_boundary_detector",
"axis=0) # Return a color space, which contains all colors from the queue",
"limeted to 1. That's, why we drop old images manually. :param Image image_msg:",
"image = self.bridge.imgmsg_to_cv2(image_msg, 'bgr8') # Get new dynamic colors from image colors =",
"vision_config['dynamic_color_space_kernel_radius']) self.heuristic = Heuristic(self.debug_printer) # Subscribe to Image-message if 'ROS_img_msg_topic' not in self.vision_config",
"\"\"\" Returns array of new dynamically calculated color values. Those values were filtered",
"image return (self.get_unique_colors(cv2.bitwise_and(image, image, mask=255 - mask)), self.get_unique_colors(cv2.bitwise_and(image, image, mask=mask))) def get_unique_colors(self, image):",
":param DebugPrinter: debug-printer :param float threshold: necessary amount of previously detected color in",
"colors = image[coordinate_list[0], coordinate_list[1]] # np.unique requires list with at least one element",
"self.color_value_queue.append(colors) # Publishes to 'ROS_dynamic_color_space_msg_topic' self.publish(image_msg) def get_unique_color_values(self, image, coordinate_list): # type: (np.array,",
"off dynamic color space, if parameter of config is false if 'dynamic_color_space_active' not",
"None \"\"\" Pointfinder is used to find false-color pixels with higher true-color /",
"= rospy.Publisher( vision_config['ROS_dynamic_color_space_msg_topic'], ColorSpace, queue_size=1) # Set Color- and FieldBoundaryDetector self.color_detector = color.DynamicPixelListColorDetector(",
"count of neighbors for each pixel sum_array = cv2.filter2D(normalized_image, -1, self.kernel, borderType=0) #",
"in masked image. :param np.array masked_image: masked image :return np.array: list of indices",
"set: whitelist \"\"\" # Generates whitelist colors_over_field_boundary, colors_under_field_boundary = self.unique_colors_for_partitions(image, mask) return set(colors_under_field_boundary)",
"# Restructures the color channels return self.deserialize(np.array(list(color_set))) def recalculate(self, image, mask): # type:",
"# Set params self.queue_max_size = vision_config['dynamic_color_space_queue_max_size'] self.color_value_queue = deque(maxlen=self.queue_max_size) self.pointfinder = Pointfinder( self.debug_printer,",
"original image and the field-boundary-mask. :param np.array image: image :param np.array mask: field-boundary-mask",
"in self.vision_config or \\ self.vision_config['ROS_img_msg_topic'] != vision_config['ROS_img_msg_topic']: if hasattr(self, 'sub_image_msg'): self.sub_image_msg.unregister() self.sub_image_msg =",
"\"\"\" This method is called by the 'vision_config'-message subscriber. Load and update vision",
"type: (DebugPrinter, float, int) -> None \"\"\" Pointfinder is used to find false-color",
"whitelist whitelist = self.recalculate(image, mask) # Takes only whitelisted values color_set = color_set.intersection(whitelist)",
"every color space in the queue for new_color_value_list in queue: color_space = np.append(color_space,",
"Get new dynamic colors from image colors = self.get_new_dynamic_colors(image) # Add new colors",
"whitelist colors_over_field_boundary, colors_under_field_boundary = self.unique_colors_for_partitions(image, mask) return set(colors_under_field_boundary) - set(colors_over_field_boundary) def unique_colors_for_partitions(self, image,",
"(np.array) -> np.array \"\"\" Returns array of new dynamically calculated color values. Those",
"get_new_dynamic_colors(self, image): # type: (np.array) -> np.array \"\"\" Returns array of new dynamically",
"Takes only whitelisted values color_set = color_set.intersection(whitelist) # Restructures the color channels return",
"masked image to values of 1 or 0 normalized_image = np.floor_divide(masked_image, 255, dtype=np.int16)",
"with a higher true-color / false-color ratio than the threshold return np.array(np.where(sum_array >",
"This method is called by the Image-message subscriber. Old Image-messages were dropped. Sometimes",
"= np.zeros((input_matrix.size, 3)) new_matrix[:, 0] = np.array(input_matrix // 256 ** 2, dtype=np.uint8) new_matrix[:,",
"of all queue elements stacked, which contains all colors from the queue. :param",
":return: None \"\"\" # Get color space from queue color_space = self.queue_to_color_space(self.color_value_queue) #",
"image :param np.array mask: field-boundary-mask :return np.array: colors over the field boundary :return",
"to accommodate e.g. changing lighting conditions or to compensate for not optimized base",
"code) :param np.array input_matrix: list of colors values with 3 channels :return: list",
"np.zeros((input_matrix.size, 3)) new_matrix[:, 0] = np.array(input_matrix // 256 ** 2, dtype=np.uint8) new_matrix[:, 1]",
"type: (np.array) -> np.array \"\"\" Resolves the serialization of colors into different channels.",
":param np.array input_matrix: serialized colors :return: original colors with 3 channels \"\"\" new_matrix",
"that occur under the field boundary and have no occurrences over the field",
"as threshold in their surrounding in masked image. :param np.array masked_image: masked image",
"their position relative to the field boundary. Only colors that occur under the",
"from cv_bridge import CvBridge from collections import deque from sensor_msgs.msg import Image from",
"whitelist \"\"\" # Generates whitelist colors_over_field_boundary, colors_under_field_boundary = self.unique_colors_for_partitions(image, mask) return set(colors_under_field_boundary) -",
"import deque from sensor_msgs.msg import Image from bitbots_msgs.msg import ColorSpace, Config from bitbots_vision.vision_modules",
"mask), dtype=np.int32) return colors return np.array([[]]) def queue_to_color_space(self, queue): # type: (deque) ->",
"were filtered by the heuristic. :param np.array image: image :return np.array: array of",
"to be filtered :param np.array image: raw vision image :param np.array mask: binary",
"None \"\"\" Publishes the current color space via ColorSpace-message. :param Image image_msg: 'image_raw'-message",
"type: (np.array) -> np.array \"\"\" Calculates unique color for an input image. :param",
"of an Image-message. New colors are calculated, appended to queue and published. :param",
"-> None \"\"\" Filters new color space colors according to their position relative",
"= vision_config def image_callback(self, image_msg): # type: (Image) -> None \"\"\" This method",
"array of color values :return np.array: color space \"\"\" # Initializes an empty",
"type: (Image) -> None \"\"\" This method is called by the Image-message subscriber.",
"queue): # type: (deque) -> np.array \"\"\" Returns color space as array of",
":param np.array image: raw vision image :param np.array mask: binary field-boundary-mask :return np.array:",
"params self.vision_config = {} # Subscribe to 'vision_config'-message # The message topic name",
"color channels color_list = self.serialize(color_list) # Making a set and removing duplicated colors",
"Image-message subscriber. Old Image-messages were dropped. Sometimes the queue gets to large, even",
"ColorSpace, queue_size=1) # Set Color- and FieldBoundaryDetector self.color_detector = color.DynamicPixelListColorDetector( self.debug_printer, self.package_path, vision_config)",
"2) \\ + np.multiply(input_matrix[:, 1], 256) \\ + input_matrix[:, 2], dtype=np.int32) def deserialize(self,",
"ONEs self.kernel = None self.kernel = np.ones((self.kernel_edge_size, self.kernel_edge_size)) # Set value of the",
":return np.array: list of indices \"\"\" # Normalizes the masked image to values",
"with 3 channels :return: list of serialized colors \"\"\" return np.array( np.multiply(input_matrix[:, 0],",
"unique color values from image at pixel coordinates \"\"\" # Create list of",
"image: image :param np.array mask: field-boundary-mask :return set: whitelist \"\"\" # Generates whitelist",
"list with at least one element if colors.size > 0: unique_colors = np.unique(colors,",
"# Print status of dynamic color space after toggeling 'dynamic_color_space_active' parameter if 'dynamic_color_space_active'",
"image_msg.header.stamp if image_age.to_sec() > 0.1: self.debug_printer.info('Dynamic color space: Dropped Image-message', 'image') return self.handle_image(image_msg)",
"kernel_radius self.kernel_edge_size = 2 * self.kernel_radius + 1 # Defines kernel # Init",
"boundary :return np.array: colors under the field boundary \"\"\" # Calls a function",
"set(color_list) # Generates whitelist whitelist = self.recalculate(image, mask) # Takes only whitelisted values",
"this pixel is 1, it's value in the sum_array would be 0 self.kernel[int(np.size(self.kernel,",
"self.vision_config or \\ self.vision_config['ROS_img_msg_topic'] != vision_config['ROS_img_msg_topic']: if hasattr(self, 'sub_image_msg'): self.sub_image_msg.unregister() self.sub_image_msg = rospy.Subscriber(",
"color space as array of all queue elements stacked, which contains all colors",
"defines relevant surrounding of pixel :return: None \"\"\" # Init params self.debug_printer =",
"'vision_config'-message # The message topic name MUST be the same as in the",
"colors from the queue. :param dequeue queue: queue of array of color values",
"the queue self.color_value_queue.append(colors) # Publishes to 'ROS_dynamic_color_space_msg_topic' self.publish(image_msg) def get_unique_color_values(self, image, coordinate_list): #",
"subscriber :return: None \"\"\" # Turn off dynamic color space, if parameter of",
"queue. :param dequeue queue: queue of array of color values :return np.array: color",
"is limeted to 1. That's, why we drop old images manually. :param Image",
"self.vision_config or \\ self.vision_config['ROS_dynamic_color_space_msg_topic'] != vision_config['ROS_dynamic_color_space_msg_topic']: if hasattr(self, 'pub_color_space'): self.pub_color_space.unregister() self.pub_color_space = rospy.Publisher(",
"= np.array((input_matrix - (new_matrix[:, 0] * 256 ** 2)) / 256, dtype=np.uint8) new_matrix[:,",
"image. :param DebugPrinter: debug-printer :param float threshold: necessary amount of previously detected color",
"via ColorSpace-message. :param Image image_msg: 'image_raw'-message :return: None \"\"\" # Get color space",
"return np.array([[]]) def queue_to_color_space(self, queue): # type: (deque) -> np.array \"\"\" Returns color",
":return np.array: colors over the field boundary :return np.array: colors under the field",
"(1, int(image.size / 3), 3))[0]) # Returns unique colors in the image return",
"Publish ColorSpace-message self.pub_color_space.publish(color_space_msg) class Pointfinder(): def __init__(self, debug_printer, threshold, kernel_radius): # type: (DebugPrinter,",
"\"\"\" Filters new color space colors according to their position relative to the",
"0], 256 ** 2) \\ + np.multiply(input_matrix[:, 1], 256) \\ + input_matrix[:, 2],",
"= {} # Subscribe to 'vision_config'-message # The message topic name MUST be",
"ColorSpace-messages if 'ROS_dynamic_color_space_msg_topic' not in self.vision_config or \\ self.vision_config['ROS_dynamic_color_space_msg_topic'] != vision_config['ROS_dynamic_color_space_msg_topic']: if hasattr(self,",
"2)] = - self.kernel.size def get_coordinates_of_color_candidates(self, masked_image): # type (np.array) -> np.array \"\"\"",
"\"\"\" Serializes the different color channels of a list of colors in an",
"def __init__(self): # type: () -> None \"\"\" DynamicColorSpace is a ROS node,",
"image colors = self.get_new_dynamic_colors(image) # Add new colors to the queue self.color_value_queue.append(colors) #",
"# Get color space from queue color_space = self.queue_to_color_space(self.color_value_queue) # Create ColorSpace-message color_space_msg",
"if 'dynamic_color_space_active' not in self.vision_config or \\ not self.vision_config['dynamic_color_space_active']: return # Drops old",
"color_space_msg.header.frame_id = image_msg.header.frame_id color_space_msg.header.stamp = image_msg.header.stamp color_space_msg.blue = color_space[:,0].tolist() color_space_msg.green = color_space[:,1].tolist() color_space_msg.red",
"-1, self.kernel, borderType=0) # Returns all pixels with a higher true-color / false-color",
"image to values of 1 or 0 normalized_image = np.floor_divide(masked_image, 255, dtype=np.int16) #",
"return colors return np.array([[]]) def queue_to_color_space(self, queue): # type: (deque) -> np.array \"\"\"",
"class DynamicColorSpace: def __init__(self): # type: () -> None \"\"\" DynamicColorSpace is a",
"list of colors using the original image and a field-boundary-mask. :param np.array color_list:",
"vision_config_callback(self, msg): # type: (Config) -> None \"\"\" This method is called by",
":param np.array color_list: list of color values, that need to be filtered :param",
"filters a given list of colors using the original image and a field-boundary-mask.",
"+ 1 # Defines kernel # Init kernel as M x M matrix",
"colors that occur under the field boundary and have no occurrences over the",
"the different color channels of a list of colors in an single channel.",
"occurrences of all colors in the image return (self.get_unique_colors(cv2.bitwise_and(image, image, mask=255 - mask)),",
"merging the three color channels color_list = self.serialize(color_list) # Making a set and",
"colors return unique_colors def get_new_dynamic_colors(self, image): # type: (np.array) -> np.array \"\"\" Returns",
"self.kernel = np.ones((self.kernel_edge_size, self.kernel_edge_size)) # Set value of the center element of the",
"the Image-message subscriber. Old Image-messages were dropped. Sometimes the queue gets to large,",
"at pixel coordinates \"\"\" # Create list of color values from image at",
"\"\"\" # Init params self.debug_printer = debug_printer self.threshold = threshold self.kernel_radius = kernel_radius",
"of color candidates. Color candidates are false-color pixels with a higher true-color/ false-color",
"field boundary. Only colors that occur under the field boundary and have no",
"color channels of a list of colors in an single channel. (Like a",
"np.array image: image :param np.array coordinate_list: list of pixel coordinates :return np.array: array",
"self.package_path = rospack.get_path('bitbots_vision') rospy.init_node('bitbots_dynamic_color_space') rospy.loginfo('Initializing dynamic color-space...') self.bridge = CvBridge() # Init params",
"2)) / 256, dtype=np.uint8) new_matrix[:, 2] = np.array((input_matrix - (new_matrix[:, 0] * 256",
":param int kernel_radius: radius surrounding the center element of kernel matrix, defines relevant",
"size is limeted to 1. That's, why we drop old images manually. :param",
":param np.array mask: field-boundary-mask :return np.array: colors over the field boundary :return np.array:",
"np.floor_divide(masked_image, 255, dtype=np.int16) # Calculates the count of neighbors for each pixel sum_array",
"field_boundary, color, debug, evaluator class DynamicColorSpace: def __init__(self): # type: () -> None",
"yaml-format in msg.data vision_config = yaml.load(msg.data) self.debug_printer = debug.DebugPrinter( debug_classes=debug.DebugPrinter.generate_debug_class_list_from_string( vision_config['vision_debug_printer_classes'])) self.runtime_evaluator =",
"the center element of kernel matrix, defines relevant surrounding of pixel :return: None",
"allowed colors using the original image and the field-boundary-mask. :param np.array image: image",
"and FieldBoundaryDetector self.color_detector = color.DynamicPixelListColorDetector( self.debug_printer, self.package_path, vision_config) self.field_boundary_detector = field_boundary.FieldBoundaryDetector( self.color_detector, vision_config,",
"DynamicColorSpace is able to calculate dynamically changing color spaces to accommodate e.g. changing",
"detected color in percentage :param int kernel_radius: radius surrounding the center element of",
"of colors using the original image and a field-boundary-mask. :param np.array color_list: list",
"the field boundary :return np.array: colors under the field boundary \"\"\" # Calls",
"\"\"\" # Turn off dynamic color space, if parameter of config is false",
":param Image image_msg: Image-message :return: None \"\"\" # Converting the ROS image message",
"if hasattr(self, 'color_value_queue'): self.color_value_queue.clear() # Set params self.queue_max_size = vision_config['dynamic_color_space_queue_max_size'] self.color_value_queue = deque(maxlen=self.queue_max_size)",
"lighting conditions or to compensate for not optimized base color space files. This",
"(Like a HTML color code) :param np.array input_matrix: serialized colors :return: original colors",
"(np.array, np.array) -> (np.array, np.array) \"\"\" Masks picture and returns the unique colors"
] |
[
"as f: long_description = f.read() setup( name='pituo', packages=['pituo'], version='0.0.2', license='MIT', description='Go-styled errors in",
"License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 2',",
"Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language ::",
"long_description = f.read() setup( name='pituo', packages=['pituo'], version='0.0.2', license='MIT', description='Go-styled errors in Python.', long_description=long_description,",
"= f.read() setup( name='pituo', packages=['pituo'], version='0.0.2', license='MIT', description='Go-styled errors in Python.', long_description=long_description, long_description_content_type=\"text/markdown\",",
"Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language ::",
"long_description=long_description, long_description_content_type=\"text/markdown\", author='<NAME>', author_email='<EMAIL>', url='https://github.com/RuyiLi/pituo', keywords=['go', 'error', 'exception'], classifiers=[ 'Intended Audience :: Developers',",
"3', 'Programming Language :: Python :: 2', 'Operating System :: OS Independent', ],",
"classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming",
":: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python",
"MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python ::",
":: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming",
"name='pituo', packages=['pituo'], version='0.0.2', license='MIT', description='Go-styled errors in Python.', long_description=long_description, long_description_content_type=\"text/markdown\", author='<NAME>', author_email='<EMAIL>', url='https://github.com/RuyiLi/pituo',",
"import setup with open('README.md') as f: long_description = f.read() setup( name='pituo', packages=['pituo'], version='0.0.2',",
"OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language",
"'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language",
"setup with open('README.md') as f: long_description = f.read() setup( name='pituo', packages=['pituo'], version='0.0.2', license='MIT',",
"from setuptools import setup with open('README.md') as f: long_description = f.read() setup( name='pituo',",
"packages=['pituo'], version='0.0.2', license='MIT', description='Go-styled errors in Python.', long_description=long_description, long_description_content_type=\"text/markdown\", author='<NAME>', author_email='<EMAIL>', url='https://github.com/RuyiLi/pituo', keywords=['go',",
"keywords=['go', 'error', 'exception'], classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved ::",
"<reponame>RuyiLi/pituo from setuptools import setup with open('README.md') as f: long_description = f.read() setup(",
"author='<NAME>', author_email='<EMAIL>', url='https://github.com/RuyiLi/pituo', keywords=['go', 'error', 'exception'], classifiers=[ 'Intended Audience :: Developers', 'License ::",
"'Programming Language :: Python :: 2', 'Operating System :: OS Independent', ], )",
"setup( name='pituo', packages=['pituo'], version='0.0.2', license='MIT', description='Go-styled errors in Python.', long_description=long_description, long_description_content_type=\"text/markdown\", author='<NAME>', author_email='<EMAIL>',",
"license='MIT', description='Go-styled errors in Python.', long_description=long_description, long_description_content_type=\"text/markdown\", author='<NAME>', author_email='<EMAIL>', url='https://github.com/RuyiLi/pituo', keywords=['go', 'error', 'exception'],",
"open('README.md') as f: long_description = f.read() setup( name='pituo', packages=['pituo'], version='0.0.2', license='MIT', description='Go-styled errors",
"'error', 'exception'], classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT",
":: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python",
"f: long_description = f.read() setup( name='pituo', packages=['pituo'], version='0.0.2', license='MIT', description='Go-styled errors in Python.',",
"'Programming Language :: Python :: 3', 'Programming Language :: Python :: 2', 'Operating",
"Language :: Python :: 3', 'Programming Language :: Python :: 2', 'Operating System",
"in Python.', long_description=long_description, long_description_content_type=\"text/markdown\", author='<NAME>', author_email='<EMAIL>', url='https://github.com/RuyiLi/pituo', keywords=['go', 'error', 'exception'], classifiers=[ 'Intended Audience",
"Python :: 3', 'Programming Language :: Python :: 2', 'Operating System :: OS",
"Python.', long_description=long_description, long_description_content_type=\"text/markdown\", author='<NAME>', author_email='<EMAIL>', url='https://github.com/RuyiLi/pituo', keywords=['go', 'error', 'exception'], classifiers=[ 'Intended Audience ::",
":: Python :: 3', 'Programming Language :: Python :: 2', 'Operating System ::",
"f.read() setup( name='pituo', packages=['pituo'], version='0.0.2', license='MIT', description='Go-styled errors in Python.', long_description=long_description, long_description_content_type=\"text/markdown\", author='<NAME>',",
"with open('README.md') as f: long_description = f.read() setup( name='pituo', packages=['pituo'], version='0.0.2', license='MIT', description='Go-styled",
"long_description_content_type=\"text/markdown\", author='<NAME>', author_email='<EMAIL>', url='https://github.com/RuyiLi/pituo', keywords=['go', 'error', 'exception'], classifiers=[ 'Intended Audience :: Developers', 'License",
"setuptools import setup with open('README.md') as f: long_description = f.read() setup( name='pituo', packages=['pituo'],",
":: 3', 'Programming Language :: Python :: 2', 'Operating System :: OS Independent',",
"version='0.0.2', license='MIT', description='Go-styled errors in Python.', long_description=long_description, long_description_content_type=\"text/markdown\", author='<NAME>', author_email='<EMAIL>', url='https://github.com/RuyiLi/pituo', keywords=['go', 'error',",
"'exception'], classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License',",
"description='Go-styled errors in Python.', long_description=long_description, long_description_content_type=\"text/markdown\", author='<NAME>', author_email='<EMAIL>', url='https://github.com/RuyiLi/pituo', keywords=['go', 'error', 'exception'], classifiers=[",
"errors in Python.', long_description=long_description, long_description_content_type=\"text/markdown\", author='<NAME>', author_email='<EMAIL>', url='https://github.com/RuyiLi/pituo', keywords=['go', 'error', 'exception'], classifiers=[ 'Intended",
"author_email='<EMAIL>', url='https://github.com/RuyiLi/pituo', keywords=['go', 'error', 'exception'], classifiers=[ 'Intended Audience :: Developers', 'License :: OSI",
"Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python ::",
"'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3',",
"url='https://github.com/RuyiLi/pituo', keywords=['go', 'error', 'exception'], classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved"
] |
[
"IN THE # SOFTWARE. \"\"\" Basic classes to read/write a binary Kaldi ark",
"writer = KaldiIntVectorArkWriter() reader.open(args.input_ark) writer.open(args.output_ark) for uttid2data in reader: print(('uttid: %s' %list(uttid2data.keys())[0])) if",
"args.type == 'f': reader = KaldiFeatArkReader() writer = KaldiFeatArkWriter() elif args.type == 'w':",
"information; see http://soundfile.sapp.org/doc/WaveFormat/ for details \"\"\" bytesPerSample = struct.unpack( '<h', riff_header[34:36] )[0] //",
"close(self): \"\"\" Close the file pointer if it is opened \"\"\" if self.arkfp",
"self.curr_arkfile = None if store_image == True:# store all the utterance data into",
"WAV_SYM: raise ValueError('ERROR: %s: could not find %s but %s' %(self.curr_arkfile, WAV_SYM, endSym))",
"into the wav ark file \"\"\" outData = b'' for c in uttid",
"self.arkfp.write(outData) self.arkfp.flush() def correct_chunk_size(numSamples, riff_header): \"\"\" Correct the data length in header information;",
"* bytesPerSample totalChunkSize = 36 + dataLength return (riff_header[0:4] + struct.pack('<L', totalChunkSize) +",
"c class KaldiArkWriter: \"\"\" Base class for writing a Kaldi ark file \"\"\"",
"ID and feature matrix where each row vector correpsonds to a feature vector",
"if store_image == True:# store all the utterance data into image self.arkdata =",
"\"\"\" Read a Kaldi .wav.ark file per utterance iteratively \"\"\" def __init__(self, store_image=False):",
"A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR",
"this is constructed with store_image = True. \"\"\" if self.arkdata is None: self.arkdata",
"ark file') c = struct.unpack('<s', arkdata)[0] if c == b' ': # read",
"struct.pack('<I', featD) self.arkfp.write(outData) outData = b'' for frameX in range(frameN): for coeff in",
"included in all # copies or substantial portions of the Software. # #",
"from the ark file and return it :returns : Python dictionary that contains",
"one byte data '\\x04' arkdata = self.arkfp.read(4) # read the dimension featD =",
"uttid += c class KaldiIntVectorArkReader(KaldiArkReader): \"\"\" Read a Kaldi integer-vector file per utterance",
"data header frameN = len(intVec) outData = b'' for c in uttid +",
"return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() def open(self, arkfile): if self.arkfp",
"+ riff_header[44:]) class KaldiWavArkWriter(KaldiArkWriter): \"\"\" Write utterance data as a Kaldi .wav.ark file",
"be kept in RAM if True \"\"\" self.arkfp = None self.curr_arkfile = None",
":returns : Python dictionary that contains the utterance ID as a key and",
"end symbol 'BFM ' endSym = struct.unpack('<4s', arkdata)[0] if endSym != BFM_SYM: raise",
"to permit persons to whom the Software is # furnished to do so,",
"= {uttid:intVec} uttid = b'' yield uttid2data else: uttid += c class KaldiWavArkReader(KaldiArkReader):",
"NULLC) for c in BIV_SYM.decode(): outData +=struct.pack('<c', c.encode()) outData += struct.pack('<c', FEAT_BYTE_SIZE) outData",
"SOFTWARE. \"\"\" Basic classes to read/write a binary Kaldi ark file \"\"\" import",
"+= struct.pack('<c', FEAT_BYTE_SIZE) outData += struct.pack('<I', frameN) self.arkfp.write(outData) # write actual vector data",
"%(self.curr_arkfile, endSym)) arkdata = self.arkfp.read(1) # skip one byte data '\\x04' arkdata =",
"vals.append(struct.unpack('<i', arkdata)[0]) intVec = numpy.array(vals) uttid = uttid.decode() if self.arkdata is not None:",
"self.arkfp.flush() def correct_chunk_size(numSamples, riff_header): \"\"\" Correct the data length in header information; see",
"LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION",
"= riff_header uttid = uttid.decode() if self.arkdata is not None: self.accumulate(uttid, samples) uttid2data",
"36 + dataLength return (riff_header[0:4] + struct.pack('<L', totalChunkSize) + riff_header[8:40] + struct.pack('<L', dataLength)",
"the ark file will be kept in RAM if True \"\"\" self.arkfp =",
"= self.arkfp.read(4) vals.append(struct.unpack('<i', arkdata)[0]) intVec = numpy.array(vals) uttid = uttid.decode() if self.arkdata is",
"self.uttids = [] def seek(self, position_in_bytes): \"\"\" Skip the file pointer. You can",
"endSym, BIV_SYM)) arkdata = self.arkfp.read(1) # skip one byte data '\\x04' arkdata =",
"self.uttids = [] self.arkdata[uttid] = dataelem self.uttids.append(uttid) def open(self, arkfile): \"\"\" Set the",
"reader.open(args.input_ark) writer.open(args.output_ark) for uttid2data in reader: print(('uttid: %s' %list(uttid2data.keys())[0])) if args.type == 'w':",
"KaldiArkReader.__init__(self, store_image) def __iter__(self): \"\"\" Return a tuple of an utterance ID and",
"if uttids is None: uttids = list(uttid2feats.keys()) for uttid in uttids: outData =",
"\"\"\" if self.arkfp is not None: self.arkfp.seek(position_in_bytes, 0) class KaldiFeatArkReader(KaldiArkReader): \"\"\" Read a",
"OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. \"\"\" Basic classes",
"'\\0' arkdata = self.arkfp.read(1) # read the end symbol 'B' endSym = struct.unpack('<s',",
"arkfile def close(self): \"\"\" Close the file pointer if it is opened \"\"\"",
"iteratively \"\"\" def __init__(self, store_image=False): KaldiArkReader.__init__(self, store_image) def __iter__(self): \"\"\" Return a tuple",
"is None: self.arkdata = {} self.uttids = [] self.arkdata[uttid] = dataelem self.uttids.append(uttid) def",
"struct.unpack('<s', arkdata)[0] if endSym != BIV_SYM: raise ValueError('ERROR: %s: Unmatched symbol %s!=%s' %(self.curr_arkfile,",
"int-vector ark file \"\"\" def __init__(self): KaldiArkWriter.__init__(self) def write(self, uttid2feats, uttids=None): if uttids",
"if self.arkdata is None: self.arkdata = {} self.uttids = [] self.arkdata[uttid] = dataelem",
"#!/usr/bin/env python # -*- coding: utf-8 -*- # # MIT License # #",
"+ riff_header[8:40] + struct.pack('<L', dataLength) + riff_header[44:]) class KaldiWavArkWriter(KaldiArkWriter): \"\"\" Write utterance data",
"# read the end symbol 'BFM ' endSym = struct.unpack('<4s', arkdata)[0] if endSym",
"help='Ark file type (i/f/w)') parser.add_argument('input_ark', help='input ark path') parser.add_argument('output_ark', help='output ark path') return",
"BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN",
"each utterance from the ark file and return it :returns : Python dictionary",
"def write(self, uttid2feats, uttid2headers, uttids=None): if uttids is None: uttids = list(uttid2feats.keys()) for",
"CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT",
"== b' ': arkdata = self.arkfp.read(1) # skip '\\0' arkdata = self.arkfp.read(4) #",
"%s' %(self.curr_arkfile, endSym)) arkdata = self.arkfp.read(1) # skip one byte data '\\x04' arkdata",
"numpy.reshape(struct.unpack('<%df' %(coeffN), arkdata), (frameN,featD)) uttid = uttid.decode() if self.arkdata is not None: self.accumulate(uttid,",
"arkdata = self.arkfp.read(1) # skip '\\0' arkdata = self.arkfp.read(4) # read the end",
"self.close() def accumulate(self, uttid, dataelem): \"\"\" Store all the utterance data into the",
"uttid = uttid.decode() if self.arkdata is not None: self.accumulate(uttid, samples) uttid2data = {uttid:samples}",
"= self.arkfp.read(4) # read the dimension featD = struct.unpack( '<I', arkdata )[0] coeffN",
"self.arkdata is not None: self.arkdata = {} self.uttids = [] def seek(self, position_in_bytes):",
"= None self.samplerate = None self.num_channels = None def get_riff_header(self): return self.riff_header def",
"\"\"\" def __init__(self, store_image=False): KaldiArkReader.__init__(self, store_image) self.riff_header = None self.samplerate = None self.num_channels",
"# write the corrected header information uttid2header = correct_chunk_size(len(samples), uttid2headers[uttid]) self.arkfp.write(uttid2header) outData =",
"def __exit__(self, exc_type, exc_val, exc_tb): self.close() def open(self, arkfile): if self.arkfp is not",
"\"\"\" if self.arkfp is not None: self.arkfp.close() self.arkfp = None self.curr_arkfile = None",
"DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR",
"USE OR OTHER DEALINGS IN THE # SOFTWARE. \"\"\" Basic classes to read/write",
"= None self.curr_arkfile = None if store_image == True:# store all the utterance",
"is opened \"\"\" if self.arkfp is not None: self.arkfp.close() self.arkfp = None self.curr_arkfile",
"\"\"\" Skip the file pointer. You can pick up the file position from",
"frameN) self.arkfp.write(outData) # write actual vector data outData = b'' for coeff in",
"self.arkfp.flush() class KaldiIntVectorArkWriter(KaldiArkWriter): \"\"\" Write utterance data as a Kaldi int-vector ark file",
"!= 16: raise ValueError('ERROR: %s: expecting utterance with int16 format but %d bits",
"with int16 format but %d bits per sample.' % (self.curr_arkfile, bitsPerSample)) uttBinary =",
"None: self.accumulate(uttid, samples) uttid2data = {uttid:samples} uttid = b'' yield uttid2data else: uttid",
"ark file to be read later \"\"\" if self.arkfp is not None: raise",
"# write actual vector data outData = b'' for coeff in intVec: outData",
".wav.ark file per utterance iteratively \"\"\" def __init__(self, store_image=False): KaldiArkReader.__init__(self, store_image) self.riff_header =",
"not None: self.accumulate(uttid, samples) uttid2data = {uttid:samples} uttid = b'' yield uttid2data else:",
"NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE",
"the file position from .scp file \"\"\" if self.arkfp is not None: self.arkfp.seek(position_in_bytes,",
"software and associated documentation files (the \"Software\"), to deal # in the Software",
"c.encode()) outData += struct.pack('<c', NULLC) for c in BIV_SYM.decode(): outData +=struct.pack('<c', c.encode()) outData",
"frameN = struct.unpack('<i', arkdata)[0] # read the coefficients vals = [] for i",
"True: arkdata = self.arkfp.read(1) if arkdata == b'': raise StopIteration('End of feat ark",
"and to permit persons to whom the Software is # furnished to do",
"# furnished to do so, subject to the following conditions: # # The",
"b' ': arkdata = self.arkfp.read(1) # skip '\\0' arkdata = self.arkfp.read(1) # read",
"the Software, and to permit persons to whom the Software is # furnished",
"== b'': raise StopIteration('End of wav ark file') c = struct.unpack('<s', arkdata)[0] if",
"Kaldi int-vector ark file \"\"\" def __init__(self): KaldiArkWriter.__init__(self) def write(self, uttid2feats, uttids=None): if",
"yield uttid2data else: uttid += c class KaldiWavArkReader(KaldiArkReader): \"\"\" Read a Kaldi .wav.ark",
"+= c class KaldiArkWriter: \"\"\" Base class for writing a Kaldi ark file",
"struct.unpack('<L', riff_header[24:28])[0] self.num_channels = struct.unpack('<h', riff_header[22:24])[0] if endSym != WAV_SYM: raise ValueError('ERROR: %s:",
"vector :returns: (string, numpy.vector) \"\"\" uttid = b'' while True: arkdata = self.arkfp.read(1)",
"'rb') self.curr_arkfile = arkfile def close(self): \"\"\" Close the file pointer if it",
"ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE",
"file') parser.add_argument('-t', '--type', default='f', help='Ark file type (i/f/w)') parser.add_argument('input_ark', help='input ark path') parser.add_argument('output_ark',",
"tuple of an utterance ID and vector :returns: (string, numpy.vector) \"\"\" uttid =",
"# skip one byte data '\\x04' arkdata = self.arkfp.read(4) # read no. frames",
"+= struct.pack('<h', samp) self.arkfp.write(outData) self.arkfp.flush() def dump_riff_file(self, riff_file, uttid): \"\"\" Dump the data",
"License # # Copyright (c) 2018 <NAME> # # Permission is hereby granted,",
"%s but %s' %(self.curr_arkfile, WAV_SYM, endSym)) if bitsPerSample != 16: raise ValueError('ERROR: %s:",
"in range(frameN): for coeff in feMat[frameX]: outData += struct.pack('<f', coeff) self.arkfp.write(outData) self.arkfp.flush() class",
"CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH",
"self.samplerate = struct.unpack('<L', riff_header[24:28])[0] self.num_channels = struct.unpack('<h', riff_header[22:24])[0] if endSym != WAV_SYM: raise",
"arkdata = self.arkfp.read(4) vals.append(struct.unpack('<i', arkdata)[0]) intVec = numpy.array(vals) uttid = uttid.decode() if self.arkdata",
"coeff) self.arkfp.write(outData) self.arkfp.flush() def correct_chunk_size(numSamples, riff_header): \"\"\" Correct the data length in header",
"uttids is None: uttids = list(uttid2feats.keys()) for uttid in uttids: feMat = uttid2feats[uttid]",
"uttids=None): if uttids is None: uttids = list(uttid2feats.keys()) for uttid in uttids: feMat",
"PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT",
"self.num_channels = None def get_riff_header(self): return self.riff_header def get_samplerate(self): return self.samplerate def get_num_channel(self):",
"could not find %s but %s' %(self.curr_arkfile, WAV_SYM, endSym)) if bitsPerSample != 16:",
"self.arkdata is not None: self.accumulate(uttid, samples) uttid2data = {uttid:samples} uttid = b'' yield",
"': outData += struct.pack('<c', c.encode()) self.arkfp.write(outData) samples = uttid2feats[uttid] # write the corrected",
"KaldiArkWriter.__init__(self) def write(self, uttid2feats, uttid2headers, uttids=None): if uttids is None: uttids = list(uttid2feats.keys())",
"Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY",
"store_image) def __iter__(self): \"\"\" Return a tuple of an utterance ID and feature",
"self.arkfp.read(1) # skip one byte data '\\x04' arkdata = self.arkfp.read(4) # read the",
"vector per frame :returns: (string, numpy.matrix) \"\"\" uttid = b'' while True: arkdata",
"to deal # in the Software without restriction, including without limitation the rights",
"to any person obtaining a copy # of this software and associated documentation",
"RAM if this is constructed with store_image = True. \"\"\" if self.arkdata is",
"and vector :returns: (string, numpy.vector) \"\"\" uttid = b'' while True: arkdata =",
"endSym != WAV_SYM: raise ValueError('ERROR: %s: could not find %s but %s' %(self.curr_arkfile,",
"= self.arkfp.read(44) # skip '\\0' endSym = struct.unpack('<4s',riff_header[0:4])[0] dataLength = struct.unpack('<L', riff_header[40:44])[0] bitsPerSample",
"in the ark file will be kept in RAM if True \"\"\" self.arkfp",
"OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #",
"reader = KaldiFeatArkReader() writer = KaldiFeatArkWriter() elif args.type == 'w': reader = KaldiWavArkReader()",
"raise NotImplemented('Implement this') def __exit__(self, exc_type, exc_val, exc_tb): self.close() def accumulate(self, uttid, dataelem):",
"and feature matrix where each row vector correpsonds to a feature vector per",
"self.arkdata[uttid] = dataelem self.uttids.append(uttid) def open(self, arkfile): \"\"\" Set the ark file to",
"2018 <NAME> # # Permission is hereby granted, free of charge, to any",
"an utterance ID and vector :returns: (string, numpy.vector) \"\"\" uttid = b'' while",
"as a key and data as a value \"\"\" raise NotImplemented('Implement this') def",
"self.arkfp.read(1) if arkdata == b'': raise StopIteration('End of wav ark file') c =",
"end symbol 'B' endSym = struct.unpack('<s', arkdata)[0] if endSym != BIV_SYM: raise ValueError('ERROR:",
"c == b' ': arkdata = self.arkfp.read(1) # skip '\\0' arkdata = self.arkfp.read(1)",
"__init__(self, store_image=False): KaldiArkReader.__init__(self, store_image) self.riff_header = None self.samplerate = None self.num_channels = None",
"file will be kept in RAM if True \"\"\" self.arkfp = None self.curr_arkfile",
"not None: self.accumulate(uttid, intVec) uttid2data = {uttid:intVec} uttid = b'' yield uttid2data else:",
"in uttids: outData = b'' for c in uttid + ' ': outData",
"self.arkfp.read(4) # read no. frames frameN = struct.unpack('<i', arkdata)[0] # read the coefficients",
"b'' yield uttid2data else: uttid += c class KaldiArkWriter: \"\"\" Base class for",
"ID as a key and data as a value \"\"\" raise NotImplemented('Implement this')",
"= None self.uttids = None def __enter__(self): return self def __iter__(self): \"\"\" Read",
"RIFF file into the wav ark file \"\"\" outData = b'' for c",
"%s: Unmatched symbol %s!=%s' %(self.curr_arkfile, endSym, BIV_SYM)) arkdata = self.arkfp.read(1) # skip one",
"this software and associated documentation files (the \"Software\"), to deal # in the",
"= numpy.reshape(struct.unpack('<%df' %(coeffN), arkdata), (frameN,featD)) uttid = uttid.decode() if self.arkdata is not None:",
"' ': outData += struct.pack('<c', c.encode()) self.arkfp.write(outData) with open(riff_file, 'rb') as riffF: self.arkfp.write(riffF.read())",
"THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. \"\"\"",
"is not None: self.arkdata = {} self.uttids = [] def seek(self, position_in_bytes): \"\"\"",
"ValueError('ERROR: %s: Unmatched symbol %s!=%s' %(self.curr_arkfile, endSym, BIV_SYM)) arkdata = self.arkfp.read(1) # skip",
"= b'' yield uttid2data else: uttid += c class KaldiArkWriter: \"\"\" Base class",
"with open(riff_file, 'rb') as riffF: self.arkfp.write(riffF.read()) self.arkfp.flush() def test(): import argparse def build_parser():",
"uttid = b'' yield uttid2data else: uttid += c class KaldiArkWriter: \"\"\" Base",
"granted, free of charge, to any person obtaining a copy # of this",
"Byte header block of the RIFF file riff_header = self.arkfp.read(44) # skip '\\0'",
"Basic classes to read/write a binary Kaldi ark file \"\"\" import struct, numpy",
"and this permission notice shall be included in all # copies or substantial",
"b'BFM ' BIV_SYM = b'B' FEAT_BYTE_SIZE = b'\\x04' NULLC = b'\\0' WAV_SYM =",
"16-bit integer vector :returns: (string, numpy.int16 vector) \"\"\" uttid = b'' while True:",
"range(frameN): for coeff in feMat[frameX]: outData += struct.pack('<f', coeff) self.arkfp.write(outData) self.arkfp.flush() class KaldiIntVectorArkWriter(KaldiArkWriter):",
"a binary Kaldi ark file \"\"\" import struct, numpy BFM_SYM = b'BFM '",
"# Permission is hereby granted, free of charge, to any person obtaining a",
"= uttid.decode() if self.arkdata is not None: self.accumulate(uttid, intVec) uttid2data = {uttid:intVec} uttid",
"IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF",
"Unmatched symbol %s!=%s' %(self.curr_arkfile, endSym, BIV_SYM)) arkdata = self.arkfp.read(1) # skip one byte",
"None self.uttids = None def __enter__(self): return self def __iter__(self): \"\"\" Read each",
"per sample.' % (self.curr_arkfile, bitsPerSample)) uttBinary = self.arkfp.read(dataLength) # expecting 16 bit per",
"arkdata )[0] arkdata = self.arkfp.read(1) # skip one byte data '\\x04' arkdata =",
"= 36 + dataLength return (riff_header[0:4] + struct.pack('<L', totalChunkSize) + riff_header[8:40] + struct.pack('<L',",
"self.arkfp is not None: self.arkfp.seek(position_in_bytes, 0) class KaldiFeatArkReader(KaldiArkReader): \"\"\" Read a Kaldi .feat.ark",
"= self.arkfp.read(1) if arkdata == b'': raise StopIteration('End of feat ark file') c",
"corrected header information uttid2header = correct_chunk_size(len(samples), uttid2headers[uttid]) self.arkfp.write(uttid2header) outData = b'' for samp",
"'B' endSym = struct.unpack('<s', arkdata)[0] if endSym != BIV_SYM: raise ValueError('ERROR: %s: Unmatched",
"uttid in uttids: outData = b'' for c in uttid + ' ':",
"# divide 2 (Byte) self.samplerate = struct.unpack('<L', riff_header[24:28])[0] self.num_channels = struct.unpack('<h', riff_header[22:24])[0] if",
"KaldiArkWriter: \"\"\" Base class for writing a Kaldi ark file \"\"\" def __init__(self):",
"ark file \"\"\" def __init__(self): KaldiArkWriter.__init__(self) def write(self, uttid2feats, uttids=None): if uttids is",
"uttid in uttids: feMat = uttid2feats[uttid] frameN = len(feMat) featD = len(feMat[0]) outData",
"OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION",
"Read a Kaldi integer-vector file per utterance iteratively \"\"\" def __init__(self, store_image=False): KaldiArkReader.__init__(self,",
"without restriction, including without limitation the rights # to use, copy, modify, merge,",
"endSym)) arkdata = self.arkfp.read(1) # skip one byte data '\\x04' arkdata = self.arkfp.read(4)",
"def accumulate(self, uttid, dataelem): \"\"\" Store all the utterance data into the RAM",
"= struct.unpack('<h', riff_header[22:24])[0] if endSym != WAV_SYM: raise ValueError('ERROR: %s: could not find",
"of wav ark file') c = struct.unpack('<s', arkdata)[0] if c == b' ':",
"Store all the utterance data into the RAM if this is constructed with",
"bytesPerSample totalChunkSize = 36 + dataLength return (riff_header[0:4] + struct.pack('<L', totalChunkSize) + riff_header[8:40]",
"def __init__(self, store_image=False): KaldiArkReader.__init__(self, store_image) def __iter__(self): \"\"\" Return a tuple of an",
"= b'B' FEAT_BYTE_SIZE = b'\\x04' NULLC = b'\\0' WAV_SYM = b'RIFF' class KaldiArkReader:",
"== b' ': # read the 44 Byte header block of the RIFF",
"integer vector :returns: (string, numpy.int16 vector) \"\"\" uttid = b'' while True: arkdata",
"i in numpy.arange(0,len(uttBinary), 2)] samples = numpy.array(numpy.int16(numpy.resize(uttInt, (len(uttInt),)))) self.riff_header = riff_header uttid =",
"reader = KaldiWavArkReader() writer = KaldiWavArkWriter() else: reader = KaldiIntVectorArkReader() writer = KaldiIntVectorArkWriter()",
"You can pick up the file position from .scp file \"\"\" if self.arkfp",
"= frameN * featD # read the coefficients arkdata = self.arkfp.read(coeffN * 4)",
"ark file') c = struct.unpack('<s', arkdata)[0] if c == b' ': arkdata =",
"copies of the Software, and to permit persons to whom the Software is",
"featD = len(feMat[0]) outData = b'' for c in uttid + ' ':",
":returns: (string, numpy.int16 vector) \"\"\" uttid = b'' while True: arkdata = self.arkfp.read(1)",
"b'' for coeff in intVec: outData += struct.pack('<c', FEAT_BYTE_SIZE) outData += struct.pack('<i', coeff)",
"\"\"\" Read a Kaldi .feat.ark file per utterance iteratively \"\"\" def __init__(self, store_image=False):",
"ValueError('ERROR: %s could not find BFM but %s' %(self.curr_arkfile, endSym)) arkdata = self.arkfp.read(1)",
"if c == b' ': arkdata = self.arkfp.read(1) # skip '\\0' arkdata =",
"arkdata = self.arkfp.read(4) # read the dimension featD = struct.unpack( '<I', arkdata )[0]",
"\"\"\" Base class for writing a Kaldi ark file \"\"\" def __init__(self): self.arkfp",
"\"\"\" Write utterance data as a Kaldi .feat.ark file \"\"\" def __init__(self): KaldiArkWriter.__init__(self)",
"b'RIFF' class KaldiArkReader: \"\"\" Base class for readling a Kaldi ark file \"\"\"",
"riff_header uttid = uttid.decode() if self.arkdata is not None: self.accumulate(uttid, samples) uttid2data =",
"ark file \"\"\" outData = b'' for c in uttid + ' ':",
"'\\x04' arkdata = self.arkfp.read(4) # read the dimension featD = struct.unpack( '<I', arkdata",
"outData += struct.pack('<c', c.encode()) outData += struct.pack('<c', NULLC) for c in BIV_SYM.decode(): outData",
"obtaining a copy # of this software and associated documentation files (the \"Software\"),",
"self.arkfp.write(outData) samples = uttid2feats[uttid] # write the corrected header information uttid2header = correct_chunk_size(len(samples),",
"uttid2data = {uttid:feMat} uttid = b'' yield uttid2data else: uttid += c class",
"if c == b' ': # read the 44 Byte header block of",
"file') c = struct.unpack('<s', arkdata)[0] if c == b' ': arkdata = self.arkfp.read(1)",
"uttid2feats, uttids=None): if uttids is None: uttids = list(uttid2feats.keys()) for uttid in uttids:",
"outData = b'' for samp in samples: outData += struct.pack('<h', samp) self.arkfp.write(outData) self.arkfp.flush()",
"shall be included in all # copies or substantial portions of the Software.",
"uttid = b'' while True: arkdata = self.arkfp.read(1) if arkdata == b'': break",
"c in uttid + ' ': outData += struct.pack('<c', c.encode()) outData += struct.pack('<c',",
"read no. frames frameN = struct.unpack('<i', arkdata)[0] # read the coefficients vals =",
"read the dimension featD = struct.unpack( '<I', arkdata )[0] coeffN = frameN *",
"build_parser() args, argv = parser.parse_known_args() if args.type == 'f': reader = KaldiFeatArkReader() writer",
"uttid2headers[uttid]) self.arkfp.write(uttid2header) outData = b'' for samp in samples: outData += struct.pack('<h', samp)",
"divide 2 (Byte) self.samplerate = struct.unpack('<L', riff_header[24:28])[0] self.num_channels = struct.unpack('<h', riff_header[22:24])[0] if endSym",
"a feature vector per frame :returns: (string, numpy.matrix) \"\"\" uttid = b'' while",
"= struct.unpack('<h', riff_header[34:36])[0] # nsamps = int(dataLength / (bitsPerSample/8)) # divide 2 (Byte)",
"'\\x04' arkdata = self.arkfp.read(4) # read no. frames frameN = struct.unpack( '<I', arkdata",
"+= struct.pack('<c', FEAT_BYTE_SIZE) outData += struct.pack('<i', coeff) self.arkfp.write(outData) self.arkfp.flush() def correct_chunk_size(numSamples, riff_header): \"\"\"",
"any person obtaining a copy # of this software and associated documentation files",
"will be kept in RAM if True \"\"\" self.arkfp = None self.curr_arkfile =",
"c.encode()) self.arkfp.write(outData) samples = uttid2feats[uttid] # write the corrected header information uttid2header =",
"for samp in samples: outData += struct.pack('<h', samp) self.arkfp.write(outData) self.arkfp.flush() def dump_riff_file(self, riff_file,",
"= struct.unpack('<s', arkdata)[0] if c == b' ': arkdata = self.arkfp.read(1) # skip",
"store_image) self.riff_header = None self.samplerate = None self.num_channels = None def get_riff_header(self): return",
"= open(arkfile, 'rb') self.curr_arkfile = arkfile def close(self): \"\"\" Close the file pointer",
"BIV_SYM = b'B' FEAT_BYTE_SIZE = b'\\x04' NULLC = b'\\0' WAV_SYM = b'RIFF' class",
"IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED,",
"\"\"\" Read a Kaldi integer-vector file per utterance iteratively \"\"\" def __init__(self, store_image=False):",
"a copy # of this software and associated documentation files (the \"Software\"), to",
"no. frames frameN = struct.unpack('<i', arkdata)[0] # read the coefficients vals = []",
"of an utterance ID and vector :returns: (string, numpy.vector) \"\"\" uttid = b''",
"if this is constructed with store_image = True. \"\"\" if self.arkdata is None:",
"riffF: self.arkfp.write(riffF.read()) self.arkfp.flush() def test(): import argparse def build_parser(): parser = argparse.ArgumentParser(description='List utterance",
"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #",
"(the \"Software\"), to deal # in the Software without restriction, including without limitation",
"= self.arkfp.read(1) arkdata = self.arkfp.read(4) vals.append(struct.unpack('<i', arkdata)[0]) intVec = numpy.array(vals) uttid = uttid.decode()",
"Read each utterance from the ark file and return it :returns : Python",
"numpy.vector) \"\"\" uttid = b'' while True: arkdata = self.arkfp.read(1) if arkdata ==",
"self.arkfp.write(outData) self.arkfp.flush() def dump_riff_file(self, riff_file, uttid): \"\"\" Dump the data in a RIFF",
"charge, to any person obtaining a copy # of this software and associated",
"outData += struct.pack('<c', c.encode()) self.arkfp.write(outData) samples = uttid2feats[uttid] # write the corrected header",
"for c in uttid + ' ': outData += struct.pack('<c', c.encode()) self.arkfp.write(outData) with",
"b'' while True: arkdata = self.arkfp.read(1) if arkdata == b'': raise StopIteration('End of",
"\"\"\" def __init__(self): self.arkfp = None def __entry__(self): return self def __exit__(self, exc_type,",
"KaldiWavArkReader(KaldiArkReader): \"\"\" Read a Kaldi .wav.ark file per utterance iteratively \"\"\" def __init__(self,",
"utterance ID as a key and data as a value \"\"\" raise NotImplemented('Implement",
"arkdata = self.arkfp.read(1) if arkdata == b'': raise StopIteration('End of wav ark file')",
"open(riff_file, 'rb') as riffF: self.arkfp.write(riffF.read()) self.arkfp.flush() def test(): import argparse def build_parser(): parser",
"limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or",
"Set the ark file to be read later \"\"\" if self.arkfp is not",
"self.arkfp.read(4) # read no. frames frameN = struct.unpack( '<I', arkdata )[0] arkdata =",
"Python dictionary that contains the utterance ID as a key and data as",
"dataLength = struct.unpack('<L', riff_header[40:44])[0] bitsPerSample = struct.unpack('<h', riff_header[34:36])[0] # nsamps = int(dataLength /",
"= [] self.arkdata[uttid] = dataelem self.uttids.append(uttid) def open(self, arkfile): \"\"\" Set the ark",
"None class KaldiFeatArkWriter(KaldiArkWriter): \"\"\" Write utterance data as a Kaldi .feat.ark file \"\"\"",
"outData +=struct.pack('<c', c.encode()) outData += struct.pack('<c', FEAT_BYTE_SIZE) outData += struct.pack('<I', frameN) self.arkfp.write(outData) #",
"def __entry__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() def open(self, arkfile):",
"riff_header[22:24])[0] if endSym != WAV_SYM: raise ValueError('ERROR: %s: could not find %s but",
"ark file and return it :returns : Python dictionary that contains the utterance",
"= struct.unpack('<4s', arkdata)[0] if endSym != BFM_SYM: raise ValueError('ERROR: %s could not find",
"class KaldiIntVectorArkReader(KaldiArkReader): \"\"\" Read a Kaldi integer-vector file per utterance iteratively \"\"\" def",
"but %d bits per sample.' % (self.curr_arkfile, bitsPerSample)) uttBinary = self.arkfp.read(dataLength) # expecting",
"KaldiWavArkWriter(KaldiArkWriter): \"\"\" Write utterance data as a Kaldi .wav.ark file \"\"\" def __init__(self):",
"__exit__(self, exc_type, exc_val, exc_tb): self.close() def open(self, arkfile): if self.arkfp is not None:",
"= uttid2feats[uttid] # write data header frameN = len(intVec) outData = b'' for",
"\"\"\" Return a tuple of an utterance ID and vector :returns: (string, numpy.vector)",
"+= c class KaldiWavArkReader(KaldiArkReader): \"\"\" Read a Kaldi .wav.ark file per utterance iteratively",
"[] def seek(self, position_in_bytes): \"\"\" Skip the file pointer. You can pick up",
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR",
"EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,",
"file pointer. You can pick up the file position from .scp file \"\"\"",
"yield uttid2data else: uttid += c class KaldiIntVectorArkReader(KaldiArkReader): \"\"\" Read a Kaldi integer-vector",
"self.arkfp = open(arkfile, 'rb') self.curr_arkfile = arkfile def close(self): \"\"\" Close the file",
"__enter__(self): return self def __iter__(self): \"\"\" Read each utterance from the ark file",
"= struct.unpack( '<I', arkdata )[0] arkdata = self.arkfp.read(1) # skip one byte data",
"above copyright notice and this permission notice shall be included in all #",
"\"\"\" import struct, numpy BFM_SYM = b'BFM ' BIV_SYM = b'B' FEAT_BYTE_SIZE =",
"if self.arkdata is not None: self.arkdata = {} self.uttids = [] def seek(self,",
"wav ark file \"\"\" outData = b'' for c in uttid + '",
"': # read the 44 Byte header block of the RIFF file riff_header",
"def test(): import argparse def build_parser(): parser = argparse.ArgumentParser(description='List utterance IDs in the",
"uttid += c class KaldiArkWriter: \"\"\" Base class for writing a Kaldi ark",
"struct.pack('<c', c.encode()) self.arkfp.write(outData) samples = uttid2feats[uttid] # write the corrected header information uttid2header",
"# # Permission is hereby granted, free of charge, to any person obtaining",
"the data in a RIFF file into the wav ark file \"\"\" outData",
"= numpy.array(vals) uttid = uttid.decode() if self.arkdata is not None: self.accumulate(uttid, intVec) uttid2data",
":params store_image: Every utterance data in the ark file will be kept in",
"StopIteration('End of wav ark file') c = struct.unpack('<s', arkdata)[0] if c == b'",
"= {uttid:feMat} uttid = b'' yield uttid2data else: uttid += c class KaldiIntVectorArkReader(KaldiArkReader):",
"= None self.curr_arkfile = None if self.arkdata is not None: self.arkdata = {}",
"path') parser.add_argument('output_ark', help='output ark path') return parser parser = build_parser() args, argv =",
"the ark file and return it :returns : Python dictionary that contains the",
"uttid2data = {uttid:samples} uttid = b'' yield uttid2data else: uttid += c class",
"[] self.arkdata[uttid] = dataelem self.uttids.append(uttid) def open(self, arkfile): \"\"\" Set the ark file",
"FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE",
"outData += struct.pack('<c', c.encode()) outData += struct.pack('<c', NULLC) for c in BFM_SYM.decode(): outData",
"PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING",
"# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS",
"samples: outData += struct.pack('<h', samp) self.arkfp.write(outData) self.arkfp.flush() def dump_riff_file(self, riff_file, uttid): \"\"\" Dump",
"for c in uttid + ' ': outData += struct.pack('<c', c.encode()) self.arkfp.write(outData) samples",
"= numSamples * bytesPerSample totalChunkSize = 36 + dataLength return (riff_header[0:4] + struct.pack('<L',",
"= self.arkfp.read(4) # read the end symbol 'BFM ' endSym = struct.unpack('<4s', arkdata)[0]",
"write actual vector data outData = b'' for coeff in intVec: outData +=",
"frame :returns: (string, numpy.matrix) \"\"\" uttid = b'' while True: arkdata = self.arkfp.read(1)",
"the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell",
"file per utterance iteratively \"\"\" def __init__(self, store_image=False): KaldiArkReader.__init__(self, store_image) def __iter__(self): \"\"\"",
"for uttid in uttids: feMat = uttid2feats[uttid] frameN = len(feMat) featD = len(feMat[0])",
"an utterance ID and audio samples as a 16-bit integer vector :returns: (string,",
"of the Software, and to permit persons to whom the Software is #",
"self.riff_header def get_samplerate(self): return self.samplerate def get_num_channel(self): return self.num_channels def __iter__(self): \"\"\" Return",
"uttid = b'' yield uttid2data else: uttid += c class KaldiWavArkReader(KaldiArkReader): \"\"\" Read",
"up the file position from .scp file \"\"\" if self.arkfp is not None:",
"the RAM if this is constructed with store_image = True. \"\"\" if self.arkdata",
"\"\"\" if self.arkfp is not None: raise IOError('call close() first') self.arkfp = open(arkfile,",
"None if self.arkdata is not None: self.arkdata = {} self.uttids = [] def",
"# SOFTWARE. \"\"\" Basic classes to read/write a binary Kaldi ark file \"\"\"",
"Constructor of KaldiArkReader :params store_image: Every utterance data in the ark file will",
"symbol 'B' endSym = struct.unpack('<s', arkdata)[0] if endSym != BIV_SYM: raise ValueError('ERROR: %s:",
"the wav ark file \"\"\" outData = b'' for c in uttid +",
"== 'f': reader = KaldiFeatArkReader() writer = KaldiFeatArkWriter() elif args.type == 'w': reader",
"': outData += struct.pack('<c', c.encode()) self.arkfp.write(outData) with open(riff_file, 'rb') as riffF: self.arkfp.write(riffF.read()) self.arkfp.flush()",
"struct.pack('<c', c.encode()) outData += struct.pack('<c', NULLC) for c in BFM_SYM.decode(): outData +=struct.pack('<c', c.encode())",
"parser = build_parser() args, argv = parser.parse_known_args() if args.type == 'f': reader =",
"parser parser = build_parser() args, argv = parser.parse_known_args() if args.type == 'f': reader",
"the utterance data into the RAM if this is constructed with store_image =",
"frameX in range(frameN): for coeff in feMat[frameX]: outData += struct.pack('<f', coeff) self.arkfp.write(outData) self.arkfp.flush()",
"return self.riff_header def get_samplerate(self): return self.samplerate def get_num_channel(self): return self.num_channels def __iter__(self): \"\"\"",
"including without limitation the rights # to use, copy, modify, merge, publish, distribute,",
"uttid.decode() if self.arkdata is not None: self.accumulate(uttid, feMat) uttid2data = {uttid:feMat} uttid =",
"= len(intVec) outData = b'' for c in uttid + ' ': outData",
"coding: utf-8 -*- # # MIT License # # Copyright (c) 2018 <NAME>",
"arkdata == b'': raise StopIteration('End of feat ark file') c = struct.unpack('<s', arkdata)[0]",
"from .scp file \"\"\" if self.arkfp is not None: self.arkfp.seek(position_in_bytes, 0) class KaldiFeatArkReader(KaldiArkReader):",
"(i/f/w)') parser.add_argument('input_ark', help='input ark path') parser.add_argument('output_ark', help='output ark path') return parser parser =",
"= uttid.decode() if self.arkdata is not None: self.accumulate(uttid, samples) uttid2data = {uttid:samples} uttid",
"data into image self.arkdata = {} # arkdata[ID] = {matrix|vector} self.uttids = []",
"if endSym != BFM_SYM: raise ValueError('ERROR: %s could not find BFM but %s'",
"an utterance ID and feature matrix where each row vector correpsonds to a",
"OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS",
"= open(arkfile, 'wb') def close(self): if self.arkfp is not None: self.arkfp.close() self.arkfp =",
"return it :returns : Python dictionary that contains the utterance ID as a",
"FEAT_BYTE_SIZE) outData += struct.pack('<I', frameN) self.arkfp.write(outData) # write actual vector data outData =",
"argv = parser.parse_known_args() if args.type == 'f': reader = KaldiFeatArkReader() writer = KaldiFeatArkWriter()",
"riff_header[8:40] + struct.pack('<L', dataLength) + riff_header[44:]) class KaldiWavArkWriter(KaldiArkWriter): \"\"\" Write utterance data as",
"in intVec: outData += struct.pack('<c', FEAT_BYTE_SIZE) outData += struct.pack('<i', coeff) self.arkfp.write(outData) self.arkfp.flush() def",
"utterance data as a Kaldi int-vector ark file \"\"\" def __init__(self): KaldiArkWriter.__init__(self) def",
"the Software is # furnished to do so, subject to the following conditions:",
"subject to the following conditions: # # The above copyright notice and this",
"self.arkdata is not None: self.accumulate(uttid, intVec) uttid2data = {uttid:intVec} uttid = b'' yield",
"c.encode()) outData += struct.pack('<c', NULLC) for c in BFM_SYM.decode(): outData +=struct.pack('<c', c.encode()) outData",
"write the corrected header information uttid2header = correct_chunk_size(len(samples), uttid2headers[uttid]) self.arkfp.write(uttid2header) outData = b''",
"= int(dataLength / (bitsPerSample/8)) # divide 2 (Byte) self.samplerate = struct.unpack('<L', riff_header[24:28])[0] self.num_channels",
"store_image == True:# store all the utterance data into image self.arkdata = {}",
"TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.",
"for i in numpy.arange(0,len(uttBinary), 2)] samples = numpy.array(numpy.int16(numpy.resize(uttInt, (len(uttInt),)))) self.riff_header = riff_header uttid",
"coeff) self.arkfp.write(outData) self.arkfp.flush() class KaldiIntVectorArkWriter(KaldiArkWriter): \"\"\" Write utterance data as a Kaldi int-vector",
"None def get_riff_header(self): return self.riff_header def get_samplerate(self): return self.samplerate def get_num_channel(self): return self.num_channels",
"samples = uttid2feats[uttid] # write the corrected header information uttid2header = correct_chunk_size(len(samples), uttid2headers[uttid])",
"= None if store_image == True:# store all the utterance data into image",
"class KaldiFeatArkWriter(KaldiArkWriter): \"\"\" Write utterance data as a Kaldi .feat.ark file \"\"\" def",
"that contains the utterance ID as a key and data as a value",
"exc_type, exc_val, exc_tb): self.close() def open(self, arkfile): if self.arkfp is not None: raise",
"uttids is None: uttids = list(uttid2feats.keys()) for uttid in uttids: intVec = uttid2feats[uttid]",
"%(self.curr_arkfile, WAV_SYM, endSym)) if bitsPerSample != 16: raise ValueError('ERROR: %s: expecting utterance with",
"\"\"\" Store all the utterance data into the RAM if this is constructed",
"arkdata[ID] = {matrix|vector} self.uttids = [] # remember the order of utterance IDs",
"self.curr_arkfile = arkfile def close(self): \"\"\" Close the file pointer if it is",
"SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #",
"all the utterance data into the RAM if this is constructed with store_image",
"format but %d bits per sample.' % (self.curr_arkfile, bitsPerSample)) uttBinary = self.arkfp.read(dataLength) #",
"# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies",
"else: self.arkdata = None self.uttids = None def __enter__(self): return self def __iter__(self):",
"arkdata = self.arkfp.read(1) # skip '\\0' arkdata = self.arkfp.read(1) # read the end",
"Read a Kaldi .wav.ark file per utterance iteratively \"\"\" def __init__(self, store_image=False): KaldiArkReader.__init__(self,",
"Write utterance data as a Kaldi .feat.ark file \"\"\" def __init__(self): KaldiArkWriter.__init__(self) def",
"the RIFF file riff_header = self.arkfp.read(44) # skip '\\0' endSym = struct.unpack('<4s',riff_header[0:4])[0] dataLength",
"coefficients vals = [] for i in range(frameN): arkdata = self.arkfp.read(1) arkdata =",
"feature vector per frame :returns: (string, numpy.matrix) \"\"\" uttid = b'' while True:",
"uttid2feats[uttid] # write the corrected header information uttid2header = correct_chunk_size(len(samples), uttid2headers[uttid]) self.arkfp.write(uttid2header) outData",
"is hereby granted, free of charge, to any person obtaining a copy #",
"raise ValueError('ERROR: %s: expecting utterance with int16 format but %d bits per sample.'",
"a Kaldi ark file \"\"\" def __init__(self, store_image=False): \"\"\" Constructor of KaldiArkReader :params",
"# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE",
"else: uttid += c class KaldiArkWriter: \"\"\" Base class for writing a Kaldi",
"self.arkfp.write(riffF.read()) self.arkfp.flush() def test(): import argparse def build_parser(): parser = argparse.ArgumentParser(description='List utterance IDs",
"into image self.arkdata = {} # arkdata[ID] = {matrix|vector} self.uttids = [] #",
"bitsPerSample = struct.unpack('<h', riff_header[34:36])[0] # nsamps = int(dataLength / (bitsPerSample/8)) # divide 2",
"if arkdata == b'': break c = struct.unpack('<s', arkdata)[0] if c == b'",
"if self.arkfp is not None: raise IOError('call close() first') self.arkfp = open(arkfile, 'wb')",
"numSamples * bytesPerSample totalChunkSize = 36 + dataLength return (riff_header[0:4] + struct.pack('<L', totalChunkSize)",
"arkdata), (frameN,featD)) uttid = uttid.decode() if self.arkdata is not None: self.accumulate(uttid, feMat) uttid2data",
"c.encode()) outData += struct.pack('<c', FEAT_BYTE_SIZE) outData += struct.pack('<I', frameN) outData += struct.pack('<c', FEAT_BYTE_SIZE)",
"import struct, numpy BFM_SYM = b'BFM ' BIV_SYM = b'B' FEAT_BYTE_SIZE = b'\\x04'",
"self def __iter__(self): \"\"\" Read each utterance from the ark file and return",
"so, subject to the following conditions: # # The above copyright notice and",
"= b'\\0' WAV_SYM = b'RIFF' class KaldiArkReader: \"\"\" Base class for readling a",
"a tuple of an utterance ID and audio samples as a 16-bit integer",
"type (i/f/w)') parser.add_argument('input_ark', help='input ark path') parser.add_argument('output_ark', help='output ark path') return parser parser",
"for uttid in uttids: intVec = uttid2feats[uttid] # write data header frameN =",
"\"\"\" outData = b'' for c in uttid + ' ': outData +=",
"%(coeffN), arkdata), (frameN,featD)) uttid = uttid.decode() if self.arkdata is not None: self.accumulate(uttid, feMat)",
"\"\"\" Dump the data in a RIFF file into the wav ark file",
"if args.type == 'w': writer.write(uttid2data, {list(uttid2data.keys())[0]:reader.get_riff_header()}) else: writer.write(uttid2data) reader.close() writer.close() if __name__ ==",
"= list(uttid2feats.keys()) for uttid in uttids: intVec = uttid2feats[uttid] # write data header",
"copy # of this software and associated documentation files (the \"Software\"), to deal",
"44 Byte header block of the RIFF file riff_header = self.arkfp.read(44) # skip",
"(c) 2018 <NAME> # # Permission is hereby granted, free of charge, to",
"b'': break c = struct.unpack('<s', arkdata)[0] if c == b' ': arkdata =",
"None: uttids = list(uttid2feats.keys()) for uttid in uttids: feMat = uttid2feats[uttid] frameN =",
"uttid += c class KaldiWavArkReader(KaldiArkReader): \"\"\" Read a Kaldi .wav.ark file per utterance",
"' endSym = struct.unpack('<4s', arkdata)[0] if endSym != BFM_SYM: raise ValueError('ERROR: %s could",
"pointer if it is opened \"\"\" if self.arkfp is not None: self.arkfp.close() self.arkfp",
"is None: uttids = list(uttid2feats.keys()) for uttid in uttids: feMat = uttid2feats[uttid] frameN",
"= struct.unpack('<4s',riff_header[0:4])[0] dataLength = struct.unpack('<L', riff_header[40:44])[0] bitsPerSample = struct.unpack('<h', riff_header[34:36])[0] # nsamps =",
"None: self.arkfp.close() self.arkfp = None self.curr_arkfile = None if self.arkdata is not None:",
"self.arkfp.read(1) # skip '\\0' arkdata = self.arkfp.read(4) # read the end symbol 'BFM",
"Kaldi ark file \"\"\" def __init__(self): self.arkfp = None def __entry__(self): return self",
"arkdata == b'': break c = struct.unpack('<s', arkdata)[0] if c == b' ':",
"in RAM if True \"\"\" self.arkfp = None self.curr_arkfile = None if store_image",
"not None: self.arkfp.seek(position_in_bytes, 0) class KaldiFeatArkReader(KaldiArkReader): \"\"\" Read a Kaldi .feat.ark file per",
"'<I', arkdata )[0] arkdata = self.arkfp.read(1) # skip one byte data '\\x04' arkdata",
"uttids: intVec = uttid2feats[uttid] # write data header frameN = len(intVec) outData =",
"feMat = uttid2feats[uttid] frameN = len(feMat) featD = len(feMat[0]) outData = b'' for",
"later \"\"\" if self.arkfp is not None: raise IOError('call close() first') self.arkfp =",
"/ (bitsPerSample/8)) # divide 2 (Byte) self.samplerate = struct.unpack('<L', riff_header[24:28])[0] self.num_channels = struct.unpack('<h',",
"= b'\\x04' NULLC = b'\\0' WAV_SYM = b'RIFF' class KaldiArkReader: \"\"\" Base class",
"correct_chunk_size(len(samples), uttid2headers[uttid]) self.arkfp.write(uttid2header) outData = b'' for samp in samples: outData += struct.pack('<h',",
"if arkdata == b'': raise StopIteration('End of feat ark file') c = struct.unpack('<s',",
"uttid2data = {uttid:intVec} uttid = b'' yield uttid2data else: uttid += c class",
"+=struct.pack('<c', c.encode()) outData += struct.pack('<c', FEAT_BYTE_SIZE) outData += struct.pack('<I', frameN) self.arkfp.write(outData) # write",
"self.arkfp.write(outData) self.arkfp.flush() class KaldiIntVectorArkWriter(KaldiArkWriter): \"\"\" Write utterance data as a Kaldi int-vector ark",
"self.arkfp.read(1) if arkdata == b'': raise StopIteration('End of feat ark file') c =",
"sublicense, and/or sell # copies of the Software, and to permit persons to",
"feMat) uttid2data = {uttid:feMat} uttid = b'' yield uttid2data else: uttid += c",
"self.accumulate(uttid, feMat) uttid2data = {uttid:feMat} uttid = b'' yield uttid2data else: uttid +=",
"struct.pack('<c', FEAT_BYTE_SIZE) outData += struct.pack('<I', frameN) self.arkfp.write(outData) # write actual vector data outData",
"self.arkdata = {} self.uttids = [] def seek(self, position_in_bytes): \"\"\" Skip the file",
"arkdata = self.arkfp.read(4) # read no. frames frameN = struct.unpack('<i', arkdata)[0] # read",
"skip '\\0' arkdata = self.arkfp.read(4) # read the end symbol 'BFM ' endSym",
"coeffN = frameN * featD # read the coefficients arkdata = self.arkfp.read(coeffN *",
"# read no. frames frameN = struct.unpack( '<I', arkdata )[0] arkdata = self.arkfp.read(1)",
"uttids: outData = b'' for c in uttid + ' ': outData +=",
"{} self.uttids = [] self.arkdata[uttid] = dataelem self.uttids.append(uttid) def open(self, arkfile): \"\"\" Set",
"== b' ': arkdata = self.arkfp.read(1) # skip '\\0' arkdata = self.arkfp.read(1) #",
"c = struct.unpack('<s', arkdata)[0] if c == b' ': arkdata = self.arkfp.read(1) #",
"args.type == 'w': reader = KaldiWavArkReader() writer = KaldiWavArkWriter() else: reader = KaldiIntVectorArkReader()",
"else: uttid += c class KaldiIntVectorArkReader(KaldiArkReader): \"\"\" Read a Kaldi integer-vector file per",
"# copies of the Software, and to permit persons to whom the Software",
"= self.arkfp.read(1) if arkdata == b'': raise StopIteration('End of wav ark file') c",
"read the end symbol 'BFM ' endSym = struct.unpack('<4s', arkdata)[0] if endSym !=",
"struct.unpack( '<I', arkdata )[0] coeffN = frameN * featD # read the coefficients",
"uttid2feats[uttid] # write data header frameN = len(intVec) outData = b'' for c",
"FEAT_BYTE_SIZE) outData += struct.pack('<i', coeff) self.arkfp.write(outData) self.arkfp.flush() def correct_chunk_size(numSamples, riff_header): \"\"\" Correct the",
"in uttids: intVec = uttid2feats[uttid] # write data header frameN = len(intVec) outData",
"as a Kaldi .wav.ark file \"\"\" def __init__(self): KaldiArkWriter.__init__(self) def write(self, uttid2feats, uttid2headers,",
"\"\"\" Base class for readling a Kaldi ark file \"\"\" def __init__(self, store_image=False):",
"KaldiFeatArkReader() writer = KaldiFeatArkWriter() elif args.type == 'w': reader = KaldiWavArkReader() writer =",
"int(dataLength / (bitsPerSample/8)) # divide 2 (Byte) self.samplerate = struct.unpack('<L', riff_header[24:28])[0] self.num_channels =",
"%d bits per sample.' % (self.curr_arkfile, bitsPerSample)) uttBinary = self.arkfp.read(dataLength) # expecting 16",
"frameN = len(feMat) featD = len(feMat[0]) outData = b'' for c in uttid",
"Kaldi ark file \"\"\" import struct, numpy BFM_SYM = b'BFM ' BIV_SYM =",
"b'' yield uttid2data else: uttid += c class KaldiIntVectorArkReader(KaldiArkReader): \"\"\" Read a Kaldi",
"coeff in intVec: outData += struct.pack('<c', FEAT_BYTE_SIZE) outData += struct.pack('<i', coeff) self.arkfp.write(outData) self.arkfp.flush()",
"Return a tuple of an utterance ID and feature matrix where each row",
"IDs in an ark file else: self.arkdata = None self.uttids = None def",
"c class KaldiWavArkReader(KaldiArkReader): \"\"\" Read a Kaldi .wav.ark file per utterance iteratively \"\"\"",
"uttids=None): if uttids is None: uttids = list(uttid2feats.keys()) for uttid in uttids: intVec",
"# expecting 16 bit per sample uttInt = [struct.unpack('<h', uttBinary[i:i+2]) for i in",
"None: uttids = list(uttid2feats.keys()) for uttid in uttids: intVec = uttid2feats[uttid] # write",
"could not find BFM but %s' %(self.curr_arkfile, endSym)) arkdata = self.arkfp.read(1) # skip",
"CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #",
"Dump the data in a RIFF file into the wav ark file \"\"\"",
"yield uttid2data else: uttid += c class KaldiArkWriter: \"\"\" Base class for writing",
"= b'' for coeff in intVec: outData += struct.pack('<c', FEAT_BYTE_SIZE) outData += struct.pack('<i',",
"in reader: print(('uttid: %s' %list(uttid2data.keys())[0])) if args.type == 'w': writer.write(uttid2data, {list(uttid2data.keys())[0]:reader.get_riff_header()}) else: writer.write(uttid2data)",
"# remember the order of utterance IDs in an ark file else: self.arkdata",
"+= struct.pack('<f', coeff) self.arkfp.write(outData) self.arkfp.flush() class KaldiIntVectorArkWriter(KaldiArkWriter): \"\"\" Write utterance data as a",
"self.arkfp.close() self.arkfp = None class KaldiFeatArkWriter(KaldiArkWriter): \"\"\" Write utterance data as a Kaldi",
"def seek(self, position_in_bytes): \"\"\" Skip the file pointer. You can pick up the",
"% (self.curr_arkfile, bitsPerSample)) uttBinary = self.arkfp.read(dataLength) # expecting 16 bit per sample uttInt",
"position from .scp file \"\"\" if self.arkfp is not None: self.arkfp.seek(position_in_bytes, 0) class",
"FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF",
"+= struct.pack('<I', frameN) self.arkfp.write(outData) # write actual vector data outData = b'' for",
"None self.curr_arkfile = None if self.arkdata is not None: self.arkdata = {} self.uttids",
"-*- coding: utf-8 -*- # # MIT License # # Copyright (c) 2018",
"dimension featD = struct.unpack( '<I', arkdata )[0] coeffN = frameN * featD #",
"merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to",
"__init__(self): KaldiArkWriter.__init__(self) def write(self, uttid2feats, uttid2headers, uttids=None): if uttids is None: uttids =",
"endSym != BFM_SYM: raise ValueError('ERROR: %s could not find BFM but %s' %(self.curr_arkfile,",
"ark path') return parser parser = build_parser() args, argv = parser.parse_known_args() if args.type",
"KaldiIntVectorArkReader(KaldiArkReader): \"\"\" Read a Kaldi integer-vector file per utterance iteratively \"\"\" def __init__(self,",
"= build_parser() args, argv = parser.parse_known_args() if args.type == 'f': reader = KaldiFeatArkReader()",
"utterance iteratively \"\"\" def __init__(self, store_image=False): KaldiArkReader.__init__(self, store_image) def __iter__(self): \"\"\" Return a",
"for c in BIV_SYM.decode(): outData +=struct.pack('<c', c.encode()) outData += struct.pack('<c', FEAT_BYTE_SIZE) outData +=",
"Copyright (c) 2018 <NAME> # # Permission is hereby granted, free of charge,",
"{uttid:feMat} uttid = b'' yield uttid2data else: uttid += c class KaldiIntVectorArkReader(KaldiArkReader): \"\"\"",
"Write utterance data as a Kaldi .wav.ark file \"\"\" def __init__(self): KaldiArkWriter.__init__(self) def",
"header frameN = len(intVec) outData = b'' for c in uttid + '",
"= b'' while True: arkdata = self.arkfp.read(1) if arkdata == b'': raise StopIteration('End",
"data as a Kaldi int-vector ark file \"\"\" def __init__(self): KaldiArkWriter.__init__(self) def write(self,",
"4) feMat = numpy.reshape(struct.unpack('<%df' %(coeffN), arkdata), (frameN,featD)) uttid = uttid.decode() if self.arkdata is",
"self.samplerate def get_num_channel(self): return self.num_channels def __iter__(self): \"\"\" Return a tuple of an",
"BFM_SYM = b'BFM ' BIV_SYM = b'B' FEAT_BYTE_SIZE = b'\\x04' NULLC = b'\\0'",
"vector :returns: (string, numpy.int16 vector) \"\"\" uttid = b'' while True: arkdata =",
"vector data outData = b'' for coeff in intVec: outData += struct.pack('<c', FEAT_BYTE_SIZE)",
"def __init__(self): KaldiArkWriter.__init__(self) def write(self, uttid2feats, uttid2headers, uttids=None): if uttids is None: uttids",
"a value \"\"\" raise NotImplemented('Implement this') def __exit__(self, exc_type, exc_val, exc_tb): self.close() def",
"def __iter__(self): \"\"\" Return a tuple of an utterance ID and audio samples",
"whom the Software is # furnished to do so, subject to the following",
"totalChunkSize = 36 + dataLength return (riff_header[0:4] + struct.pack('<L', totalChunkSize) + riff_header[8:40] +",
"outData += struct.pack('<c', FEAT_BYTE_SIZE) outData += struct.pack('<i', coeff) self.arkfp.write(outData) self.arkfp.flush() def correct_chunk_size(numSamples, riff_header):",
"copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software,",
"None self.curr_arkfile = None if store_image == True:# store all the utterance data",
"the utterance data into image self.arkdata = {} # arkdata[ID] = {matrix|vector} self.uttids",
"uttid = uttid.decode() if self.arkdata is not None: self.accumulate(uttid, intVec) uttid2data = {uttid:intVec}",
"skip one byte data '\\x04' arkdata = self.arkfp.read(4) # read no. frames frameN",
"': arkdata = self.arkfp.read(1) # skip '\\0' arkdata = self.arkfp.read(1) # read the",
"is # furnished to do so, subject to the following conditions: # #",
"DEALINGS IN THE # SOFTWARE. \"\"\" Basic classes to read/write a binary Kaldi",
"in feMat[frameX]: outData += struct.pack('<f', coeff) self.arkfp.write(outData) self.arkfp.flush() class KaldiIntVectorArkWriter(KaldiArkWriter): \"\"\" Write utterance",
"not find %s but %s' %(self.curr_arkfile, WAV_SYM, endSym)) if bitsPerSample != 16: raise",
".scp file \"\"\" if self.arkfp is not None: self.arkfp.seek(position_in_bytes, 0) class KaldiFeatArkReader(KaldiArkReader): \"\"\"",
"self.arkfp.read(4) # read the dimension featD = struct.unpack( '<I', arkdata )[0] coeffN =",
"= self.arkfp.read(coeffN * 4) feMat = numpy.reshape(struct.unpack('<%df' %(coeffN), arkdata), (frameN,featD)) uttid = uttid.decode()",
"def __init__(self, store_image=False): \"\"\" Constructor of KaldiArkReader :params store_image: Every utterance data in",
"def get_num_channel(self): return self.num_channels def __iter__(self): \"\"\" Return a tuple of an utterance",
"outData = b'' for coeff in intVec: outData += struct.pack('<c', FEAT_BYTE_SIZE) outData +=",
"def __enter__(self): return self def __iter__(self): \"\"\" Read each utterance from the ark",
"break c = struct.unpack('<s', arkdata)[0] if c == b' ': arkdata = self.arkfp.read(1)",
"path') return parser parser = build_parser() args, argv = parser.parse_known_args() if args.type ==",
"class KaldiIntVectorArkWriter(KaldiArkWriter): \"\"\" Write utterance data as a Kaldi int-vector ark file \"\"\"",
"= arkfile def close(self): \"\"\" Close the file pointer if it is opened",
"arkdata = self.arkfp.read(1) if arkdata == b'': break c = struct.unpack('<s', arkdata)[0] if",
"+ dataLength return (riff_header[0:4] + struct.pack('<L', totalChunkSize) + riff_header[8:40] + struct.pack('<L', dataLength) +",
":returns: (string, numpy.matrix) \"\"\" uttid = b'' while True: arkdata = self.arkfp.read(1) if",
"if self.arkfp is not None: self.arkfp.close() self.arkfp = None class KaldiFeatArkWriter(KaldiArkWriter): \"\"\" Write",
"OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE",
"it :returns : Python dictionary that contains the utterance ID as a key",
"file pointer if it is opened \"\"\" if self.arkfp is not None: self.arkfp.close()",
"the order of utterance IDs in an ark file else: self.arkdata = None",
"outData += struct.pack('<I', featD) self.arkfp.write(outData) outData = b'' for frameX in range(frameN): for",
"KaldiIntVectorArkWriter() reader.open(args.input_ark) writer.open(args.output_ark) for uttid2data in reader: print(('uttid: %s' %list(uttid2data.keys())[0])) if args.type ==",
"one byte data '\\x04' arkdata = self.arkfp.read(4) # read no. frames frameN =",
"KaldiArkWriter.__init__(self) def write(self, uttid2feats, uttids=None): if uttids is None: uttids = list(uttid2feats.keys()) for",
"file \"\"\" def __init__(self): KaldiArkWriter.__init__(self) def write(self, uttid2feats, uttid2headers, uttids=None): if uttids is",
"ValueError('ERROR: %s: expecting utterance with int16 format but %d bits per sample.' %",
"= list(uttid2feats.keys()) for uttid in uttids: outData = b'' for c in uttid",
"None: self.accumulate(uttid, intVec) uttid2data = {uttid:intVec} uttid = b'' yield uttid2data else: uttid",
"order of utterance IDs in an ark file else: self.arkdata = None self.uttids",
"outData = b'' for frameX in range(frameN): for coeff in feMat[frameX]: outData +=",
"NULLC) for c in BFM_SYM.decode(): outData +=struct.pack('<c', c.encode()) outData += struct.pack('<c', FEAT_BYTE_SIZE) outData",
"a tuple of an utterance ID and vector :returns: (string, numpy.vector) \"\"\" uttid",
"if self.arkfp is not None: self.arkfp.seek(position_in_bytes, 0) class KaldiFeatArkReader(KaldiArkReader): \"\"\" Read a Kaldi",
"uttid.decode() if self.arkdata is not None: self.accumulate(uttid, samples) uttid2data = {uttid:samples} uttid =",
"OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY,",
"self.arkdata is None: self.arkdata = {} self.uttids = [] self.arkdata[uttid] = dataelem self.uttids.append(uttid)",
"KaldiFeatArkWriter(KaldiArkWriter): \"\"\" Write utterance data as a Kaldi .feat.ark file \"\"\" def __init__(self):",
"frameN * featD # read the coefficients arkdata = self.arkfp.read(coeffN * 4) feMat",
"+ ' ': outData += struct.pack('<c', c.encode()) self.arkfp.write(outData) samples = uttid2feats[uttid] # write",
"exc_tb): self.close() def open(self, arkfile): if self.arkfp is not None: raise IOError('call close()",
"furnished to do so, subject to the following conditions: # # The above",
"intVec = uttid2feats[uttid] # write data header frameN = len(intVec) outData = b''",
"= dataelem self.uttids.append(uttid) def open(self, arkfile): \"\"\" Set the ark file to be",
"read the coefficients arkdata = self.arkfp.read(coeffN * 4) feMat = numpy.reshape(struct.unpack('<%df' %(coeffN), arkdata),",
"= struct.unpack( '<h', riff_header[34:36] )[0] // 8 dataLength = numSamples * bytesPerSample totalChunkSize",
"<reponame>musiclvme/distant_speech_recognition<filename>btk20_src/lib/pykaldiarkio.py #!/usr/bin/env python # -*- coding: utf-8 -*- # # MIT License #",
"def write(self, uttid2feats, uttids=None): if uttids is None: uttids = list(uttid2feats.keys()) for uttid",
"self def __exit__(self, exc_type, exc_val, exc_tb): self.close() def open(self, arkfile): if self.arkfp is",
"\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT",
"struct.unpack( '<I', arkdata )[0] arkdata = self.arkfp.read(1) # skip one byte data '\\x04'",
"expecting 16 bit per sample uttInt = [struct.unpack('<h', uttBinary[i:i+2]) for i in numpy.arange(0,len(uttBinary),",
"close() first') self.arkfp = open(arkfile, 'wb') def close(self): if self.arkfp is not None:",
"%s: expecting utterance with int16 format but %d bits per sample.' % (self.curr_arkfile,",
"pick up the file position from .scp file \"\"\" if self.arkfp is not",
"struct.pack('<c', NULLC) for c in BIV_SYM.decode(): outData +=struct.pack('<c', c.encode()) outData += struct.pack('<c', FEAT_BYTE_SIZE)",
"value \"\"\" raise NotImplemented('Implement this') def __exit__(self, exc_type, exc_val, exc_tb): self.close() def accumulate(self,",
"if self.arkdata is not None: self.accumulate(uttid, feMat) uttid2data = {uttid:feMat} uttid = b''",
"outData += struct.pack('<I', frameN) outData += struct.pack('<c', FEAT_BYTE_SIZE) outData += struct.pack('<I', featD) self.arkfp.write(outData)",
"self.riff_header = None self.samplerate = None self.num_channels = None def get_riff_header(self): return self.riff_header",
"= {matrix|vector} self.uttids = [] # remember the order of utterance IDs in",
"self.riff_header = riff_header uttid = uttid.decode() if self.arkdata is not None: self.accumulate(uttid, samples)",
"bitsPerSample != 16: raise ValueError('ERROR: %s: expecting utterance with int16 format but %d",
"featD = struct.unpack( '<I', arkdata )[0] coeffN = frameN * featD # read",
"+ ' ': outData += struct.pack('<c', c.encode()) outData += struct.pack('<c', NULLC) for c",
"(riff_header[0:4] + struct.pack('<L', totalChunkSize) + riff_header[8:40] + struct.pack('<L', dataLength) + riff_header[44:]) class KaldiWavArkWriter(KaldiArkWriter):",
"<NAME> # # Permission is hereby granted, free of charge, to any person",
"for frameX in range(frameN): for coeff in feMat[frameX]: outData += struct.pack('<f', coeff) self.arkfp.write(outData)",
"= correct_chunk_size(len(samples), uttid2headers[uttid]) self.arkfp.write(uttid2header) outData = b'' for samp in samples: outData +=",
"notice shall be included in all # copies or substantial portions of the",
"feMat[frameX]: outData += struct.pack('<f', coeff) self.arkfp.write(outData) self.arkfp.flush() class KaldiIntVectorArkWriter(KaldiArkWriter): \"\"\" Write utterance data",
"outData += struct.pack('<c', NULLC) for c in BIV_SYM.decode(): outData +=struct.pack('<c', c.encode()) outData +=",
"get_riff_header(self): return self.riff_header def get_samplerate(self): return self.samplerate def get_num_channel(self): return self.num_channels def __iter__(self):",
"= self.arkfp.read(1) # read the end symbol 'B' endSym = struct.unpack('<s', arkdata)[0] if",
"store_image=False): \"\"\" Constructor of KaldiArkReader :params store_image: Every utterance data in the ark",
"file \"\"\" if self.arkfp is not None: self.arkfp.seek(position_in_bytes, 0) class KaldiFeatArkReader(KaldiArkReader): \"\"\" Read",
"Close the file pointer if it is opened \"\"\" if self.arkfp is not",
"uttids = list(uttid2feats.keys()) for uttid in uttids: intVec = uttid2feats[uttid] # write data",
"= True. \"\"\" if self.arkdata is None: self.arkdata = {} self.uttids = []",
"+ struct.pack('<L', dataLength) + riff_header[44:]) class KaldiWavArkWriter(KaldiArkWriter): \"\"\" Write utterance data as a",
"* 4) feMat = numpy.reshape(struct.unpack('<%df' %(coeffN), arkdata), (frameN,featD)) uttid = uttid.decode() if self.arkdata",
"outData = b'' for c in uttid + ' ': outData += struct.pack('<c',",
"the coefficients arkdata = self.arkfp.read(coeffN * 4) feMat = numpy.reshape(struct.unpack('<%df' %(coeffN), arkdata), (frameN,featD))",
"writer = KaldiFeatArkWriter() elif args.type == 'w': reader = KaldiWavArkReader() writer = KaldiWavArkWriter()",
"raise ValueError('ERROR: %s: could not find %s but %s' %(self.curr_arkfile, WAV_SYM, endSym)) if",
"\"\"\" Correct the data length in header information; see http://soundfile.sapp.org/doc/WaveFormat/ for details \"\"\"",
"the utterance ID as a key and data as a value \"\"\" raise",
"uttid): \"\"\" Dump the data in a RIFF file into the wav ark",
"utf-8 -*- # # MIT License # # Copyright (c) 2018 <NAME> #",
"ark file \"\"\" def __init__(self): self.arkfp = None def __entry__(self): return self def",
"classes to read/write a binary Kaldi ark file \"\"\" import struct, numpy BFM_SYM",
"self.accumulate(uttid, intVec) uttid2data = {uttid:intVec} uttid = b'' yield uttid2data else: uttid +=",
"store_image: Every utterance data in the ark file will be kept in RAM",
"per utterance iteratively \"\"\" def __init__(self, store_image=False): KaldiArkReader.__init__(self, store_image) def __iter__(self): \"\"\" Return",
"\"\"\" Write utterance data as a Kaldi int-vector ark file \"\"\" def __init__(self):",
"= [] def seek(self, position_in_bytes): \"\"\" Skip the file pointer. You can pick",
"read the end symbol 'B' endSym = struct.unpack('<s', arkdata)[0] if endSym != BIV_SYM:",
"deal # in the Software without restriction, including without limitation the rights #",
"# skip '\\0' arkdata = self.arkfp.read(4) # read the end symbol 'BFM '",
"WAV_SYM = b'RIFF' class KaldiArkReader: \"\"\" Base class for readling a Kaldi ark",
"seek(self, position_in_bytes): \"\"\" Skip the file pointer. You can pick up the file",
"feature matrix where each row vector correpsonds to a feature vector per frame",
"OR OTHER DEALINGS IN THE # SOFTWARE. \"\"\" Basic classes to read/write a",
"a Kaldi int-vector ark file \"\"\" def __init__(self): KaldiArkWriter.__init__(self) def write(self, uttid2feats, uttids=None):",
"to read/write a binary Kaldi ark file \"\"\" import struct, numpy BFM_SYM =",
"self.arkfp.read(4) vals.append(struct.unpack('<i', arkdata)[0]) intVec = numpy.array(vals) uttid = uttid.decode() if self.arkdata is not",
"self.arkfp.read(44) # skip '\\0' endSym = struct.unpack('<4s',riff_header[0:4])[0] dataLength = struct.unpack('<L', riff_header[40:44])[0] bitsPerSample =",
"__init__(self): self.arkfp = None def __entry__(self): return self def __exit__(self, exc_type, exc_val, exc_tb):",
"struct.pack('<c', FEAT_BYTE_SIZE) outData += struct.pack('<I', featD) self.arkfp.write(outData) outData = b'' for frameX in",
"utterance data as a Kaldi .wav.ark file \"\"\" def __init__(self): KaldiArkWriter.__init__(self) def write(self,",
"FEAT_BYTE_SIZE) outData += struct.pack('<I', frameN) outData += struct.pack('<c', FEAT_BYTE_SIZE) outData += struct.pack('<I', featD)",
"\"\"\" if self.arkdata is None: self.arkdata = {} self.uttids = [] self.arkdata[uttid] =",
"file into the wav ark file \"\"\" outData = b'' for c in",
"open(self, arkfile): \"\"\" Set the ark file to be read later \"\"\" if",
"as a 16-bit integer vector :returns: (string, numpy.int16 vector) \"\"\" uttid = b''",
"writing a Kaldi ark file \"\"\" def __init__(self): self.arkfp = None def __entry__(self):",
"= struct.unpack('<i', arkdata)[0] # read the coefficients vals = [] for i in",
"None def __entry__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() def open(self,",
"+= struct.pack('<c', c.encode()) outData += struct.pack('<c', NULLC) for c in BIV_SYM.decode(): outData +=struct.pack('<c',",
"def __exit__(self, exc_type, exc_val, exc_tb): self.close() def accumulate(self, uttid, dataelem): \"\"\" Store all",
"KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF",
"into the RAM if this is constructed with store_image = True. \"\"\" if",
"to whom the Software is # furnished to do so, subject to the",
"be included in all # copies or substantial portions of the Software. #",
"if bitsPerSample != 16: raise ValueError('ERROR: %s: expecting utterance with int16 format but",
"= b'' for frameX in range(frameN): for coeff in feMat[frameX]: outData += struct.pack('<f',",
"b'': raise StopIteration('End of wav ark file') c = struct.unpack('<s', arkdata)[0] if c",
"{uttid:intVec} uttid = b'' yield uttid2data else: uttid += c class KaldiWavArkReader(KaldiArkReader): \"\"\"",
"= struct.unpack( '<I', arkdata )[0] coeffN = frameN * featD # read the",
"self.arkfp.write(outData) outData = b'' for frameX in range(frameN): for coeff in feMat[frameX]: outData",
"(string, numpy.vector) \"\"\" uttid = b'' while True: arkdata = self.arkfp.read(1) if arkdata",
"riff_file, uttid): \"\"\" Dump the data in a RIFF file into the wav",
"raise StopIteration('End of feat ark file') c = struct.unpack('<s', arkdata)[0] if c ==",
"else: uttid += c class KaldiWavArkReader(KaldiArkReader): \"\"\" Read a Kaldi .wav.ark file per",
"self.arkdata = {} self.uttids = [] self.arkdata[uttid] = dataelem self.uttids.append(uttid) def open(self, arkfile):",
"\"\"\" def __init__(self): KaldiArkWriter.__init__(self) def write(self, uttid2feats, uttids=None): if uttids is None: uttids",
"utterance ID and audio samples as a 16-bit integer vector :returns: (string, numpy.int16",
"+ ' ': outData += struct.pack('<c', c.encode()) self.arkfp.write(outData) with open(riff_file, 'rb') as riffF:",
"THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR",
"Return a tuple of an utterance ID and audio samples as a 16-bit",
"to be read later \"\"\" if self.arkfp is not None: raise IOError('call close()",
"argparse.ArgumentParser(description='List utterance IDs in the ark file') parser.add_argument('-t', '--type', default='f', help='Ark file type",
"None self.samplerate = None self.num_channels = None def get_riff_header(self): return self.riff_header def get_samplerate(self):",
"len(intVec) outData = b'' for c in uttid + ' ': outData +=",
"uttid = b'' yield uttid2data else: uttid += c class KaldiIntVectorArkReader(KaldiArkReader): \"\"\" Read",
"OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR",
"FEAT_BYTE_SIZE = b'\\x04' NULLC = b'\\0' WAV_SYM = b'RIFF' class KaldiArkReader: \"\"\" Base",
"sell # copies of the Software, and to permit persons to whom the",
"kept in RAM if True \"\"\" self.arkfp = None self.curr_arkfile = None if",
"can pick up the file position from .scp file \"\"\" if self.arkfp is",
"None: self.accumulate(uttid, feMat) uttid2data = {uttid:feMat} uttid = b'' yield uttid2data else: uttid",
"struct.pack('<h', samp) self.arkfp.write(outData) self.arkfp.flush() def dump_riff_file(self, riff_file, uttid): \"\"\" Dump the data in",
"print(('uttid: %s' %list(uttid2data.keys())[0])) if args.type == 'w': writer.write(uttid2data, {list(uttid2data.keys())[0]:reader.get_riff_header()}) else: writer.write(uttid2data) reader.close() writer.close()",
"BFM_SYM: raise ValueError('ERROR: %s could not find BFM but %s' %(self.curr_arkfile, endSym)) arkdata",
"struct.pack('<I', frameN) self.arkfp.write(outData) # write actual vector data outData = b'' for coeff",
"self.arkfp.read(dataLength) # expecting 16 bit per sample uttInt = [struct.unpack('<h', uttBinary[i:i+2]) for i",
"if self.arkfp is not None: raise IOError('call close() first') self.arkfp = open(arkfile, 'rb')",
"IDs in the ark file') parser.add_argument('-t', '--type', default='f', help='Ark file type (i/f/w)') parser.add_argument('input_ark',",
"riff_header[40:44])[0] bitsPerSample = struct.unpack('<h', riff_header[34:36])[0] # nsamps = int(dataLength / (bitsPerSample/8)) # divide",
"Kaldi ark file \"\"\" def __init__(self, store_image=False): \"\"\" Constructor of KaldiArkReader :params store_image:",
"!= WAV_SYM: raise ValueError('ERROR: %s: could not find %s but %s' %(self.curr_arkfile, WAV_SYM,",
"the end symbol 'B' endSym = struct.unpack('<s', arkdata)[0] if endSym != BIV_SYM: raise",
"BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR",
"this permission notice shall be included in all # copies or substantial portions",
"= struct.unpack('<s', arkdata)[0] if endSym != BIV_SYM: raise ValueError('ERROR: %s: Unmatched symbol %s!=%s'",
"= uttid.decode() if self.arkdata is not None: self.accumulate(uttid, feMat) uttid2data = {uttid:feMat} uttid",
"OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT",
"b'\\x04' NULLC = b'\\0' WAV_SYM = b'RIFF' class KaldiArkReader: \"\"\" Base class for",
"riff_header[44:]) class KaldiWavArkWriter(KaldiArkWriter): \"\"\" Write utterance data as a Kaldi .wav.ark file \"\"\"",
"files (the \"Software\"), to deal # in the Software without restriction, including without",
"True. \"\"\" if self.arkdata is None: self.arkdata = {} self.uttids = [] self.arkdata[uttid]",
"self.num_channels def __iter__(self): \"\"\" Return a tuple of an utterance ID and audio",
"row vector correpsonds to a feature vector per frame :returns: (string, numpy.matrix) \"\"\"",
"but %s' %(self.curr_arkfile, WAV_SYM, endSym)) if bitsPerSample != 16: raise ValueError('ERROR: %s: expecting",
"samples as a 16-bit integer vector :returns: (string, numpy.int16 vector) \"\"\" uttid =",
"see http://soundfile.sapp.org/doc/WaveFormat/ for details \"\"\" bytesPerSample = struct.unpack( '<h', riff_header[34:36] )[0] // 8",
"NotImplemented('Implement this') def __exit__(self, exc_type, exc_val, exc_tb): self.close() def accumulate(self, uttid, dataelem): \"\"\"",
"following conditions: # # The above copyright notice and this permission notice shall",
"sample.' % (self.curr_arkfile, bitsPerSample)) uttBinary = self.arkfp.read(dataLength) # expecting 16 bit per sample",
"self.num_channels = struct.unpack('<h', riff_header[22:24])[0] if endSym != WAV_SYM: raise ValueError('ERROR: %s: could not",
"file type (i/f/w)') parser.add_argument('input_ark', help='input ark path') parser.add_argument('output_ark', help='output ark path') return parser",
"\"\"\" def __init__(self): KaldiArkWriter.__init__(self) def write(self, uttid2feats, uttid2headers, uttids=None): if uttids is None:",
"class for readling a Kaldi ark file \"\"\" def __init__(self, store_image=False): \"\"\" Constructor",
"read the 44 Byte header block of the RIFF file riff_header = self.arkfp.read(44)",
"ark file \"\"\" import struct, numpy BFM_SYM = b'BFM ' BIV_SYM = b'B'",
"\"\"\" Close the file pointer if it is opened \"\"\" if self.arkfp is",
"(Byte) self.samplerate = struct.unpack('<L', riff_header[24:28])[0] self.num_channels = struct.unpack('<h', riff_header[22:24])[0] if endSym != WAV_SYM:",
"data in the ark file will be kept in RAM if True \"\"\"",
"dataLength = numSamples * bytesPerSample totalChunkSize = 36 + dataLength return (riff_header[0:4] +",
"True:# store all the utterance data into image self.arkdata = {} # arkdata[ID]",
"file \"\"\" import struct, numpy BFM_SYM = b'BFM ' BIV_SYM = b'B' FEAT_BYTE_SIZE",
"= KaldiWavArkReader() writer = KaldiWavArkWriter() else: reader = KaldiIntVectorArkReader() writer = KaldiIntVectorArkWriter() reader.open(args.input_ark)",
"HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN",
"numpy.arange(0,len(uttBinary), 2)] samples = numpy.array(numpy.int16(numpy.resize(uttInt, (len(uttInt),)))) self.riff_header = riff_header uttid = uttid.decode() if",
"b'B' FEAT_BYTE_SIZE = b'\\x04' NULLC = b'\\0' WAV_SYM = b'RIFF' class KaldiArkReader: \"\"\"",
"ID and vector :returns: (string, numpy.vector) \"\"\" uttid = b'' while True: arkdata",
"frames frameN = struct.unpack('<i', arkdata)[0] # read the coefficients vals = [] for",
"__init__(self): KaldiArkWriter.__init__(self) def write(self, uttid2feats, uttids=None): if uttids is None: uttids = list(uttid2feats.keys())",
".wav.ark file \"\"\" def __init__(self): KaldiArkWriter.__init__(self) def write(self, uttid2feats, uttid2headers, uttids=None): if uttids",
"while True: arkdata = self.arkfp.read(1) if arkdata == b'': raise StopIteration('End of feat",
"= None def __entry__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() def",
"copyright notice and this permission notice shall be included in all # copies",
"outData += struct.pack('<i', coeff) self.arkfp.write(outData) self.arkfp.flush() def correct_chunk_size(numSamples, riff_header): \"\"\" Correct the data",
"endSym != BIV_SYM: raise ValueError('ERROR: %s: Unmatched symbol %s!=%s' %(self.curr_arkfile, endSym, BIV_SYM)) arkdata",
"# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER",
"outData += struct.pack('<I', frameN) self.arkfp.write(outData) # write actual vector data outData = b''",
"Return a tuple of an utterance ID and vector :returns: (string, numpy.vector) \"\"\"",
"uttids = list(uttid2feats.keys()) for uttid in uttids: outData = b'' for c in",
"in uttid + ' ': outData += struct.pack('<c', c.encode()) self.arkfp.write(outData) with open(riff_file, 'rb')",
"'<h', riff_header[34:36] )[0] // 8 dataLength = numSamples * bytesPerSample totalChunkSize = 36",
"expecting utterance with int16 format but %d bits per sample.' % (self.curr_arkfile, bitsPerSample))",
"uttid2feats[uttid] frameN = len(feMat) featD = len(feMat[0]) outData = b'' for c in",
"def correct_chunk_size(numSamples, riff_header): \"\"\" Correct the data length in header information; see http://soundfile.sapp.org/doc/WaveFormat/",
"= b'' yield uttid2data else: uttid += c class KaldiIntVectorArkReader(KaldiArkReader): \"\"\" Read a",
"%s' %(self.curr_arkfile, WAV_SYM, endSym)) if bitsPerSample != 16: raise ValueError('ERROR: %s: expecting utterance",
"is not None: raise IOError('call close() first') self.arkfp = open(arkfile, 'rb') self.curr_arkfile =",
"is None: uttids = list(uttid2feats.keys()) for uttid in uttids: intVec = uttid2feats[uttid] #",
"ValueError('ERROR: %s: could not find %s but %s' %(self.curr_arkfile, WAV_SYM, endSym)) if bitsPerSample",
"NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY",
"struct.unpack( '<h', riff_header[34:36] )[0] // 8 dataLength = numSamples * bytesPerSample totalChunkSize =",
"binary Kaldi ark file \"\"\" import struct, numpy BFM_SYM = b'BFM ' BIV_SYM",
"exc_tb): self.close() def accumulate(self, uttid, dataelem): \"\"\" Store all the utterance data into",
"iteratively \"\"\" def __init__(self, store_image=False): KaldiArkReader.__init__(self, store_image) self.riff_header = None self.samplerate = None",
"utterance iteratively \"\"\" def __init__(self, store_image=False): KaldiArkReader.__init__(self, store_image) self.riff_header = None self.samplerate =",
"exc_val, exc_tb): self.close() def open(self, arkfile): if self.arkfp is not None: raise IOError('call",
"+= struct.pack('<c', FEAT_BYTE_SIZE) outData += struct.pack('<I', featD) self.arkfp.write(outData) outData = b'' for frameX",
"IOError('call close() first') self.arkfp = open(arkfile, 'wb') def close(self): if self.arkfp is not",
"args, argv = parser.parse_known_args() if args.type == 'f': reader = KaldiFeatArkReader() writer =",
"actual vector data outData = b'' for coeff in intVec: outData += struct.pack('<c',",
"FEAT_BYTE_SIZE) outData += struct.pack('<I', featD) self.arkfp.write(outData) outData = b'' for frameX in range(frameN):",
"data '\\x04' arkdata = self.arkfp.read(4) # read no. frames frameN = struct.unpack('<i', arkdata)[0]",
"(len(uttInt),)))) self.riff_header = riff_header uttid = uttid.decode() if self.arkdata is not None: self.accumulate(uttid,",
"= len(feMat) featD = len(feMat[0]) outData = b'' for c in uttid +",
"key and data as a value \"\"\" raise NotImplemented('Implement this') def __exit__(self, exc_type,",
"== b'': break c = struct.unpack('<s', arkdata)[0] if c == b' ': arkdata",
"write(self, uttid2feats, uttids=None): if uttids is None: uttids = list(uttid2feats.keys()) for uttid in",
"arkdata = self.arkfp.read(coeffN * 4) feMat = numpy.reshape(struct.unpack('<%df' %(coeffN), arkdata), (frameN,featD)) uttid =",
"struct.pack('<c', FEAT_BYTE_SIZE) outData += struct.pack('<i', coeff) self.arkfp.write(outData) self.arkfp.flush() def correct_chunk_size(numSamples, riff_header): \"\"\" Correct",
"[struct.unpack('<h', uttBinary[i:i+2]) for i in numpy.arange(0,len(uttBinary), 2)] samples = numpy.array(numpy.int16(numpy.resize(uttInt, (len(uttInt),)))) self.riff_header =",
"= {} # arkdata[ID] = {matrix|vector} self.uttids = [] # remember the order",
"struct.unpack('<s', arkdata)[0] if c == b' ': arkdata = self.arkfp.read(1) # skip '\\0'",
"self.arkfp is not None: raise IOError('call close() first') self.arkfp = open(arkfile, 'wb') def",
"== 'w': reader = KaldiWavArkReader() writer = KaldiWavArkWriter() else: reader = KaldiIntVectorArkReader() writer",
"a RIFF file into the wav ark file \"\"\" outData = b'' for",
"struct.pack('<c', NULLC) for c in BFM_SYM.decode(): outData +=struct.pack('<c', c.encode()) outData += struct.pack('<c', FEAT_BYTE_SIZE)",
"# # MIT License # # Copyright (c) 2018 <NAME> # # Permission",
"but %s' %(self.curr_arkfile, endSym)) arkdata = self.arkfp.read(1) # skip one byte data '\\x04'",
"no. frames frameN = struct.unpack( '<I', arkdata )[0] arkdata = self.arkfp.read(1) # skip",
"in a RIFF file into the wav ark file \"\"\" outData = b''",
"KaldiFeatArkReader(KaldiArkReader): \"\"\" Read a Kaldi .feat.ark file per utterance iteratively \"\"\" def __init__(self,",
"struct.unpack('<h', riff_header[34:36])[0] # nsamps = int(dataLength / (bitsPerSample/8)) # divide 2 (Byte) self.samplerate",
"for details \"\"\" bytesPerSample = struct.unpack( '<h', riff_header[34:36] )[0] // 8 dataLength =",
"__init__(self, store_image=False): KaldiArkReader.__init__(self, store_image) def __iter__(self): \"\"\" Return a tuple of an utterance",
"\"\"\" raise NotImplemented('Implement this') def __exit__(self, exc_type, exc_val, exc_tb): self.close() def accumulate(self, uttid,",
"self.arkfp.read(coeffN * 4) feMat = numpy.reshape(struct.unpack('<%df' %(coeffN), arkdata), (frameN,featD)) uttid = uttid.decode() if",
"ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT,",
"None: self.arkfp.seek(position_in_bytes, 0) class KaldiFeatArkReader(KaldiArkReader): \"\"\" Read a Kaldi .feat.ark file per utterance",
"import argparse def build_parser(): parser = argparse.ArgumentParser(description='List utterance IDs in the ark file')",
"+ struct.pack('<L', totalChunkSize) + riff_header[8:40] + struct.pack('<L', dataLength) + riff_header[44:]) class KaldiWavArkWriter(KaldiArkWriter): \"\"\"",
"uttid2feats, uttid2headers, uttids=None): if uttids is None: uttids = list(uttid2feats.keys()) for uttid in",
"def get_riff_header(self): return self.riff_header def get_samplerate(self): return self.samplerate def get_num_channel(self): return self.num_channels def",
"if arkdata == b'': raise StopIteration('End of wav ark file') c = struct.unpack('<s',",
"KaldiArkReader: \"\"\" Base class for readling a Kaldi ark file \"\"\" def __init__(self,",
"not None: self.arkfp.close() self.arkfp = None self.curr_arkfile = None if self.arkdata is not",
"accumulate(self, uttid, dataelem): \"\"\" Store all the utterance data into the RAM if",
"range(frameN): arkdata = self.arkfp.read(1) arkdata = self.arkfp.read(4) vals.append(struct.unpack('<i', arkdata)[0]) intVec = numpy.array(vals) uttid",
"None: self.arkdata = {} self.uttids = [] def seek(self, position_in_bytes): \"\"\" Skip the",
"'<I', arkdata )[0] coeffN = frameN * featD # read the coefficients arkdata",
"2)] samples = numpy.array(numpy.int16(numpy.resize(uttInt, (len(uttInt),)))) self.riff_header = riff_header uttid = uttid.decode() if self.arkdata",
"# read the dimension featD = struct.unpack( '<I', arkdata )[0] coeffN = frameN",
"to the following conditions: # # The above copyright notice and this permission",
"\"\"\" uttid = b'' while True: arkdata = self.arkfp.read(1) if arkdata == b'':",
"arkdata)[0] if endSym != BFM_SYM: raise ValueError('ERROR: %s could not find BFM but",
"for coeff in intVec: outData += struct.pack('<c', FEAT_BYTE_SIZE) outData += struct.pack('<i', coeff) self.arkfp.write(outData)",
"utterance IDs in the ark file') parser.add_argument('-t', '--type', default='f', help='Ark file type (i/f/w)')",
"def get_samplerate(self): return self.samplerate def get_num_channel(self): return self.num_channels def __iter__(self): \"\"\" Return a",
"list(uttid2feats.keys()) for uttid in uttids: intVec = uttid2feats[uttid] # write data header frameN",
"dataelem self.uttids.append(uttid) def open(self, arkfile): \"\"\" Set the ark file to be read",
"c = struct.unpack('<s', arkdata)[0] if c == b' ': # read the 44",
"# skip '\\0' endSym = struct.unpack('<4s',riff_header[0:4])[0] dataLength = struct.unpack('<L', riff_header[40:44])[0] bitsPerSample = struct.unpack('<h',",
"dataLength return (riff_header[0:4] + struct.pack('<L', totalChunkSize) + riff_header[8:40] + struct.pack('<L', dataLength) + riff_header[44:])",
":returns: (string, numpy.vector) \"\"\" uttid = b'' while True: arkdata = self.arkfp.read(1) if",
"Software is # furnished to do so, subject to the following conditions: #",
"\"\"\" def __init__(self, store_image=False): \"\"\" Constructor of KaldiArkReader :params store_image: Every utterance data",
"self.arkfp is not None: raise IOError('call close() first') self.arkfp = open(arkfile, 'rb') self.curr_arkfile",
"uttid2data else: uttid += c class KaldiWavArkReader(KaldiArkReader): \"\"\" Read a Kaldi .wav.ark file",
"all # copies or substantial portions of the Software. # # THE SOFTWARE",
"the data length in header information; see http://soundfile.sapp.org/doc/WaveFormat/ for details \"\"\" bytesPerSample =",
"parser.add_argument('output_ark', help='output ark path') return parser parser = build_parser() args, argv = parser.parse_known_args()",
"self.arkfp.close() self.arkfp = None self.curr_arkfile = None if self.arkdata is not None: self.arkdata",
"SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. \"\"\" Basic",
"%s' %list(uttid2data.keys())[0])) if args.type == 'w': writer.write(uttid2data, {list(uttid2data.keys())[0]:reader.get_riff_header()}) else: writer.write(uttid2data) reader.close() writer.close() if",
"= None self.num_channels = None def get_riff_header(self): return self.riff_header def get_samplerate(self): return self.samplerate",
"frames frameN = struct.unpack( '<I', arkdata )[0] arkdata = self.arkfp.read(1) # skip one",
"coeff in feMat[frameX]: outData += struct.pack('<f', coeff) self.arkfp.write(outData) self.arkfp.flush() class KaldiIntVectorArkWriter(KaldiArkWriter): \"\"\" Write",
"\"\"\" Return a tuple of an utterance ID and audio samples as a",
"THE # SOFTWARE. \"\"\" Basic classes to read/write a binary Kaldi ark file",
"permission notice shall be included in all # copies or substantial portions of",
"None: self.arkdata = {} self.uttids = [] self.arkdata[uttid] = dataelem self.uttids.append(uttid) def open(self,",
"BIV_SYM: raise ValueError('ERROR: %s: Unmatched symbol %s!=%s' %(self.curr_arkfile, endSym, BIV_SYM)) arkdata = self.arkfp.read(1)",
"i in range(frameN): arkdata = self.arkfp.read(1) arkdata = self.arkfp.read(4) vals.append(struct.unpack('<i', arkdata)[0]) intVec =",
"a Kaldi .feat.ark file \"\"\" def __init__(self): KaldiArkWriter.__init__(self) def write(self, uttid2feats, uttids=None): if",
"(frameN,featD)) uttid = uttid.decode() if self.arkdata is not None: self.accumulate(uttid, feMat) uttid2data =",
"%s!=%s' %(self.curr_arkfile, endSym, BIV_SYM)) arkdata = self.arkfp.read(1) # skip one byte data '\\x04'",
"\"\"\" Set the ark file to be read later \"\"\" if self.arkfp is",
"self.accumulate(uttid, samples) uttid2data = {uttid:samples} uttid = b'' yield uttid2data else: uttid +=",
"True: arkdata = self.arkfp.read(1) if arkdata == b'': raise StopIteration('End of wav ark",
"WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT",
"OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN",
"'w': reader = KaldiWavArkReader() writer = KaldiWavArkWriter() else: reader = KaldiIntVectorArkReader() writer =",
"# read the 44 Byte header block of the RIFF file riff_header =",
"= struct.unpack('<L', riff_header[40:44])[0] bitsPerSample = struct.unpack('<h', riff_header[34:36])[0] # nsamps = int(dataLength / (bitsPerSample/8))",
"= KaldiFeatArkWriter() elif args.type == 'w': reader = KaldiWavArkReader() writer = KaldiWavArkWriter() else:",
"parser.add_argument('-t', '--type', default='f', help='Ark file type (i/f/w)') parser.add_argument('input_ark', help='input ark path') parser.add_argument('output_ark', help='output",
"use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the",
"first') self.arkfp = open(arkfile, 'rb') self.curr_arkfile = arkfile def close(self): \"\"\" Close the",
"0) class KaldiFeatArkReader(KaldiArkReader): \"\"\" Read a Kaldi .feat.ark file per utterance iteratively \"\"\"",
"the following conditions: # # The above copyright notice and this permission notice",
"LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND",
"None def __enter__(self): return self def __iter__(self): \"\"\" Read each utterance from the",
"rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #",
"class KaldiFeatArkReader(KaldiArkReader): \"\"\" Read a Kaldi .feat.ark file per utterance iteratively \"\"\" def",
"store_image) def __iter__(self): \"\"\" Return a tuple of an utterance ID and vector",
"outData +=struct.pack('<c', c.encode()) outData += struct.pack('<c', FEAT_BYTE_SIZE) outData += struct.pack('<I', frameN) outData +=",
"= b'' while True: arkdata = self.arkfp.read(1) if arkdata == b'': break c",
"+= struct.pack('<c', NULLC) for c in BIV_SYM.decode(): outData +=struct.pack('<c', c.encode()) outData += struct.pack('<c',",
"OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING",
"frameN) outData += struct.pack('<c', FEAT_BYTE_SIZE) outData += struct.pack('<I', featD) self.arkfp.write(outData) outData = b''",
"ark file \"\"\" def __init__(self, store_image=False): \"\"\" Constructor of KaldiArkReader :params store_image: Every",
"arkdata)[0] if c == b' ': # read the 44 Byte header block",
"reader: print(('uttid: %s' %list(uttid2data.keys())[0])) if args.type == 'w': writer.write(uttid2data, {list(uttid2data.keys())[0]:reader.get_riff_header()}) else: writer.write(uttid2data) reader.close()",
"to do so, subject to the following conditions: # # The above copyright",
"# skip '\\0' arkdata = self.arkfp.read(1) # read the end symbol 'B' endSym",
"help='output ark path') return parser parser = build_parser() args, argv = parser.parse_known_args() if",
"in uttid + ' ': outData += struct.pack('<c', c.encode()) self.arkfp.write(outData) samples = uttid2feats[uttid]",
"= b'BFM ' BIV_SYM = b'B' FEAT_BYTE_SIZE = b'\\x04' NULLC = b'\\0' WAV_SYM",
"in header information; see http://soundfile.sapp.org/doc/WaveFormat/ for details \"\"\" bytesPerSample = struct.unpack( '<h', riff_header[34:36]",
"data as a Kaldi .wav.ark file \"\"\" def __init__(self): KaldiArkWriter.__init__(self) def write(self, uttid2feats,",
"byte data '\\x04' arkdata = self.arkfp.read(4) # read no. frames frameN = struct.unpack(",
"return (riff_header[0:4] + struct.pack('<L', totalChunkSize) + riff_header[8:40] + struct.pack('<L', dataLength) + riff_header[44:]) class",
"list(uttid2feats.keys()) for uttid in uttids: outData = b'' for c in uttid +",
"writer = KaldiWavArkWriter() else: reader = KaldiIntVectorArkReader() writer = KaldiIntVectorArkWriter() reader.open(args.input_ark) writer.open(args.output_ark) for",
"to a feature vector per frame :returns: (string, numpy.matrix) \"\"\" uttid = b''",
"without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense,",
"KaldiIntVectorArkReader() writer = KaldiIntVectorArkWriter() reader.open(args.input_ark) writer.open(args.output_ark) for uttid2data in reader: print(('uttid: %s' %list(uttid2data.keys())[0]))",
"as a value \"\"\" raise NotImplemented('Implement this') def __exit__(self, exc_type, exc_val, exc_tb): self.close()",
"in all # copies or substantial portions of the Software. # # THE",
"per utterance iteratively \"\"\" def __init__(self, store_image=False): KaldiArkReader.__init__(self, store_image) self.riff_header = None self.samplerate",
"byte data '\\x04' arkdata = self.arkfp.read(4) # read the dimension featD = struct.unpack(",
"image self.arkdata = {} # arkdata[ID] = {matrix|vector} self.uttids = [] # remember",
"self.arkfp.write(outData) with open(riff_file, 'rb') as riffF: self.arkfp.write(riffF.read()) self.arkfp.flush() def test(): import argparse def",
"c in BIV_SYM.decode(): outData +=struct.pack('<c', c.encode()) outData += struct.pack('<c', FEAT_BYTE_SIZE) outData += struct.pack('<I',",
"for readling a Kaldi ark file \"\"\" def __init__(self, store_image=False): \"\"\" Constructor of",
"self.arkfp.read(1) # skip '\\0' arkdata = self.arkfp.read(1) # read the end symbol 'B'",
"__init__(self, store_image=False): \"\"\" Constructor of KaldiArkReader :params store_image: Every utterance data in the",
"frameN = len(intVec) outData = b'' for c in uttid + ' ':",
"a tuple of an utterance ID and feature matrix where each row vector",
"not None: self.arkdata = {} self.uttids = [] def seek(self, position_in_bytes): \"\"\" Skip",
"riff_header): \"\"\" Correct the data length in header information; see http://soundfile.sapp.org/doc/WaveFormat/ for details",
"the end symbol 'BFM ' endSym = struct.unpack('<4s', arkdata)[0] if endSym != BFM_SYM:",
"uttid + ' ': outData += struct.pack('<c', c.encode()) self.arkfp.write(outData) with open(riff_file, 'rb') as",
"= self.arkfp.read(4) # read no. frames frameN = struct.unpack('<i', arkdata)[0] # read the",
"= [] # remember the order of utterance IDs in an ark file",
"= KaldiIntVectorArkReader() writer = KaldiIntVectorArkWriter() reader.open(args.input_ark) writer.open(args.output_ark) for uttid2data in reader: print(('uttid: %s'",
"file and return it :returns : Python dictionary that contains the utterance ID",
"the ark file') parser.add_argument('-t', '--type', default='f', help='Ark file type (i/f/w)') parser.add_argument('input_ark', help='input ark",
"struct.pack('<c', c.encode()) self.arkfp.write(outData) with open(riff_file, 'rb') as riffF: self.arkfp.write(riffF.read()) self.arkfp.flush() def test(): import",
"\"\"\" Basic classes to read/write a binary Kaldi ark file \"\"\" import struct,",
"\"\"\" def __init__(self, store_image=False): KaldiArkReader.__init__(self, store_image) def __iter__(self): \"\"\" Return a tuple of",
"get_samplerate(self): return self.samplerate def get_num_channel(self): return self.num_channels def __iter__(self): \"\"\" Return a tuple",
"writer.open(args.output_ark) for uttid2data in reader: print(('uttid: %s' %list(uttid2data.keys())[0])) if args.type == 'w': writer.write(uttid2data,",
"= None def __enter__(self): return self def __iter__(self): \"\"\" Read each utterance from",
"if uttids is None: uttids = list(uttid2feats.keys()) for uttid in uttids: feMat =",
"skip '\\0' endSym = struct.unpack('<4s',riff_header[0:4])[0] dataLength = struct.unpack('<L', riff_header[40:44])[0] bitsPerSample = struct.unpack('<h', riff_header[34:36])[0]",
"coefficients arkdata = self.arkfp.read(coeffN * 4) feMat = numpy.reshape(struct.unpack('<%df' %(coeffN), arkdata), (frameN,featD)) uttid",
"modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and",
"ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES",
"self.arkfp.read(1) # skip one byte data '\\x04' arkdata = self.arkfp.read(4) # read no.",
"for c in uttid + ' ': outData += struct.pack('<c', c.encode()) outData +=",
"%s could not find BFM but %s' %(self.curr_arkfile, endSym)) arkdata = self.arkfp.read(1) #",
"if self.arkdata is not None: self.accumulate(uttid, samples) uttid2data = {uttid:samples} uttid = b''",
"Kaldi integer-vector file per utterance iteratively \"\"\" def __init__(self, store_image=False): KaldiArkReader.__init__(self, store_image) def",
"def __iter__(self): \"\"\" Return a tuple of an utterance ID and vector :returns:",
"symbol %s!=%s' %(self.curr_arkfile, endSym, BIV_SYM)) arkdata = self.arkfp.read(1) # skip one byte data",
"publish, distribute, sublicense, and/or sell # copies of the Software, and to permit",
"not None: raise IOError('call close() first') self.arkfp = open(arkfile, 'wb') def close(self): if",
"' BIV_SYM = b'B' FEAT_BYTE_SIZE = b'\\x04' NULLC = b'\\0' WAV_SYM = b'RIFF'",
"pointer. You can pick up the file position from .scp file \"\"\" if",
"# skip one byte data '\\x04' arkdata = self.arkfp.read(4) # read the dimension",
"class KaldiWavArkWriter(KaldiArkWriter): \"\"\" Write utterance data as a Kaldi .wav.ark file \"\"\" def",
"ark file') parser.add_argument('-t', '--type', default='f', help='Ark file type (i/f/w)') parser.add_argument('input_ark', help='input ark path')",
"': arkdata = self.arkfp.read(1) # skip '\\0' arkdata = self.arkfp.read(4) # read the",
"featD # read the coefficients arkdata = self.arkfp.read(coeffN * 4) feMat = numpy.reshape(struct.unpack('<%df'",
"in BFM_SYM.decode(): outData +=struct.pack('<c', c.encode()) outData += struct.pack('<c', FEAT_BYTE_SIZE) outData += struct.pack('<I', frameN)",
"'BFM ' endSym = struct.unpack('<4s', arkdata)[0] if endSym != BFM_SYM: raise ValueError('ERROR: %s",
"# read the end symbol 'B' endSym = struct.unpack('<s', arkdata)[0] if endSym !=",
"riff_header = self.arkfp.read(44) # skip '\\0' endSym = struct.unpack('<4s',riff_header[0:4])[0] dataLength = struct.unpack('<L', riff_header[40:44])[0]",
"samples) uttid2data = {uttid:samples} uttid = b'' yield uttid2data else: uttid += c",
"utterance ID and feature matrix where each row vector correpsonds to a feature",
"endSym = struct.unpack('<4s', arkdata)[0] if endSym != BFM_SYM: raise ValueError('ERROR: %s could not",
"self.uttids.append(uttid) def open(self, arkfile): \"\"\" Set the ark file to be read later",
"AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR",
"bytesPerSample = struct.unpack( '<h', riff_header[34:36] )[0] // 8 dataLength = numSamples * bytesPerSample",
"read the coefficients vals = [] for i in range(frameN): arkdata = self.arkfp.read(1)",
"def open(self, arkfile): if self.arkfp is not None: raise IOError('call close() first') self.arkfp",
"self.arkfp = None self.curr_arkfile = None if store_image == True:# store all the",
"return self.samplerate def get_num_channel(self): return self.num_channels def __iter__(self): \"\"\" Return a tuple of",
"arkdata = self.arkfp.read(1) arkdata = self.arkfp.read(4) vals.append(struct.unpack('<i', arkdata)[0]) intVec = numpy.array(vals) uttid =",
"raise IOError('call close() first') self.arkfp = open(arkfile, 'wb') def close(self): if self.arkfp is",
"self.arkdata = None self.uttids = None def __enter__(self): return self def __iter__(self): \"\"\"",
"b'': raise StopIteration('End of feat ark file') c = struct.unpack('<s', arkdata)[0] if c",
"remember the order of utterance IDs in an ark file else: self.arkdata =",
"arkdata == b'': raise StopIteration('End of wav ark file') c = struct.unpack('<s', arkdata)[0]",
"True \"\"\" self.arkfp = None self.curr_arkfile = None if store_image == True:# store",
"in samples: outData += struct.pack('<h', samp) self.arkfp.write(outData) self.arkfp.flush() def dump_riff_file(self, riff_file, uttid): \"\"\"",
"uttid in uttids: intVec = uttid2feats[uttid] # write data header frameN = len(intVec)",
"while True: arkdata = self.arkfp.read(1) if arkdata == b'': raise StopIteration('End of wav",
"dataelem): \"\"\" Store all the utterance data into the RAM if this is",
"b'' while True: arkdata = self.arkfp.read(1) if arkdata == b'': break c =",
"uttid = b'' while True: arkdata = self.arkfp.read(1) if arkdata == b'': raise",
"of utterance IDs in an ark file else: self.arkdata = None self.uttids =",
"bits per sample.' % (self.curr_arkfile, bitsPerSample)) uttBinary = self.arkfp.read(dataLength) # expecting 16 bit",
"c in uttid + ' ': outData += struct.pack('<c', c.encode()) self.arkfp.write(outData) samples =",
"Read a Kaldi .feat.ark file per utterance iteratively \"\"\" def __init__(self, store_image=False): KaldiArkReader.__init__(self,",
"# in the Software without restriction, including without limitation the rights # to",
"utterance data in the ark file will be kept in RAM if True",
"MIT License # # Copyright (c) 2018 <NAME> # # Permission is hereby",
"parser.parse_known_args() if args.type == 'f': reader = KaldiFeatArkReader() writer = KaldiFeatArkWriter() elif args.type",
"each row vector correpsonds to a feature vector per frame :returns: (string, numpy.matrix)",
"per frame :returns: (string, numpy.matrix) \"\"\" uttid = b'' while True: arkdata =",
"self.arkfp.write(outData) # write actual vector data outData = b'' for coeff in intVec:",
"tuple of an utterance ID and audio samples as a 16-bit integer vector",
"# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS",
"is None: uttids = list(uttid2feats.keys()) for uttid in uttids: outData = b'' for",
"struct.pack('<i', coeff) self.arkfp.write(outData) self.arkfp.flush() def correct_chunk_size(numSamples, riff_header): \"\"\" Correct the data length in",
"uttids=None): if uttids is None: uttids = list(uttid2feats.keys()) for uttid in uttids: outData",
"in uttids: feMat = uttid2feats[uttid] frameN = len(feMat) featD = len(feMat[0]) outData =",
"endSym = struct.unpack('<4s',riff_header[0:4])[0] dataLength = struct.unpack('<L', riff_header[40:44])[0] bitsPerSample = struct.unpack('<h', riff_header[34:36])[0] # nsamps",
"utterance IDs in an ark file else: self.arkdata = None self.uttids = None",
"parser.add_argument('input_ark', help='input ark path') parser.add_argument('output_ark', help='output ark path') return parser parser = build_parser()",
"AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE",
"KaldiArkReader :params store_image: Every utterance data in the ark file will be kept",
"args.type == 'w': writer.write(uttid2data, {list(uttid2data.keys())[0]:reader.get_riff_header()}) else: writer.write(uttid2data) reader.close() writer.close() if __name__ == '__main__':",
"file to be read later \"\"\" if self.arkfp is not None: raise IOError('call",
")[0] coeffN = frameN * featD # read the coefficients arkdata = self.arkfp.read(coeffN",
"= self.arkfp.read(dataLength) # expecting 16 bit per sample uttInt = [struct.unpack('<h', uttBinary[i:i+2]) for",
"__iter__(self): \"\"\" Return a tuple of an utterance ID and vector :returns: (string,",
"raise StopIteration('End of wav ark file') c = struct.unpack('<s', arkdata)[0] if c ==",
"WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO",
"uttInt = [struct.unpack('<h', uttBinary[i:i+2]) for i in numpy.arange(0,len(uttBinary), 2)] samples = numpy.array(numpy.int16(numpy.resize(uttInt, (len(uttInt),))))",
"file riff_header = self.arkfp.read(44) # skip '\\0' endSym = struct.unpack('<4s',riff_header[0:4])[0] dataLength = struct.unpack('<L',",
"vals = [] for i in range(frameN): arkdata = self.arkfp.read(1) arkdata = self.arkfp.read(4)",
"def __init__(self): self.arkfp = None def __entry__(self): return self def __exit__(self, exc_type, exc_val,",
"tuple of an utterance ID and feature matrix where each row vector correpsonds",
"file \"\"\" outData = b'' for c in uttid + ' ': outData",
"= self.arkfp.read(1) if arkdata == b'': break c = struct.unpack('<s', arkdata)[0] if c",
"COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER",
"data in a RIFF file into the wav ark file \"\"\" outData =",
"readling a Kaldi ark file \"\"\" def __init__(self, store_image=False): \"\"\" Constructor of KaldiArkReader",
"= struct.unpack('<L', riff_header[24:28])[0] self.num_channels = struct.unpack('<h', riff_header[22:24])[0] if endSym != WAV_SYM: raise ValueError('ERROR:",
"Kaldi .wav.ark file per utterance iteratively \"\"\" def __init__(self, store_image=False): KaldiArkReader.__init__(self, store_image) self.riff_header",
"file \"\"\" def __init__(self, store_image=False): \"\"\" Constructor of KaldiArkReader :params store_image: Every utterance",
"numpy.array(vals) uttid = uttid.decode() if self.arkdata is not None: self.accumulate(uttid, intVec) uttid2data =",
"copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED",
"outData += struct.pack('<c', c.encode()) self.arkfp.write(outData) with open(riff_file, 'rb') as riffF: self.arkfp.write(riffF.read()) self.arkfp.flush() def",
"None if store_image == True:# store all the utterance data into image self.arkdata",
"first') self.arkfp = open(arkfile, 'wb') def close(self): if self.arkfp is not None: self.arkfp.close()",
"self.uttids = [] # remember the order of utterance IDs in an ark",
"c == b' ': arkdata = self.arkfp.read(1) # skip '\\0' arkdata = self.arkfp.read(4)",
"of KaldiArkReader :params store_image: Every utterance data in the ark file will be",
"write(self, uttid2feats, uttid2headers, uttids=None): if uttids is None: uttids = list(uttid2feats.keys()) for uttid",
"not None: self.accumulate(uttid, feMat) uttid2data = {uttid:feMat} uttid = b'' yield uttid2data else:",
"Permission is hereby granted, free of charge, to any person obtaining a copy",
"utterance data into image self.arkdata = {} # arkdata[ID] = {matrix|vector} self.uttids =",
"outData += struct.pack('<c', FEAT_BYTE_SIZE) outData += struct.pack('<I', frameN) outData += struct.pack('<c', FEAT_BYTE_SIZE) outData",
"vector correpsonds to a feature vector per frame :returns: (string, numpy.matrix) \"\"\" uttid",
"IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT",
"Software without restriction, including without limitation the rights # to use, copy, modify,",
"samp) self.arkfp.write(outData) self.arkfp.flush() def dump_riff_file(self, riff_file, uttid): \"\"\" Dump the data in a",
"uttids = list(uttid2feats.keys()) for uttid in uttids: feMat = uttid2feats[uttid] frameN = len(feMat)",
"-*- # # MIT License # # Copyright (c) 2018 <NAME> # #",
"c class KaldiIntVectorArkReader(KaldiArkReader): \"\"\" Read a Kaldi integer-vector file per utterance iteratively \"\"\"",
"{} self.uttids = [] def seek(self, position_in_bytes): \"\"\" Skip the file pointer. You",
"class for writing a Kaldi ark file \"\"\" def __init__(self): self.arkfp = None",
"# The above copyright notice and this permission notice shall be included in",
"# of this software and associated documentation files (the \"Software\"), to deal #",
"intVec = numpy.array(vals) uttid = uttid.decode() if self.arkdata is not None: self.accumulate(uttid, intVec)",
"uttBinary = self.arkfp.read(dataLength) # expecting 16 bit per sample uttInt = [struct.unpack('<h', uttBinary[i:i+2])",
"c in uttid + ' ': outData += struct.pack('<c', c.encode()) self.arkfp.write(outData) with open(riff_file,",
"'wb') def close(self): if self.arkfp is not None: self.arkfp.close() self.arkfp = None class",
"WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE.",
"substantial portions of the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\",",
"c.encode()) self.arkfp.write(outData) with open(riff_file, 'rb') as riffF: self.arkfp.write(riffF.read()) self.arkfp.flush() def test(): import argparse",
"of an utterance ID and audio samples as a 16-bit integer vector :returns:",
"None self.num_channels = None def get_riff_header(self): return self.riff_header def get_samplerate(self): return self.samplerate def",
"contains the utterance ID as a key and data as a value \"\"\"",
"details \"\"\" bytesPerSample = struct.unpack( '<h', riff_header[34:36] )[0] // 8 dataLength = numSamples",
"restriction, including without limitation the rights # to use, copy, modify, merge, publish,",
"arkfile): if self.arkfp is not None: raise IOError('call close() first') self.arkfp = open(arkfile,",
"\"\"\" Constructor of KaldiArkReader :params store_image: Every utterance data in the ark file",
"// 8 dataLength = numSamples * bytesPerSample totalChunkSize = 36 + dataLength return",
"this') def __exit__(self, exc_type, exc_val, exc_tb): self.close() def accumulate(self, uttid, dataelem): \"\"\" Store",
"IOError('call close() first') self.arkfp = open(arkfile, 'rb') self.curr_arkfile = arkfile def close(self): \"\"\"",
".feat.ark file \"\"\" def __init__(self): KaldiArkWriter.__init__(self) def write(self, uttid2feats, uttids=None): if uttids is",
"b'' for c in uttid + ' ': outData += struct.pack('<c', c.encode()) self.arkfp.write(outData)",
"THE USE OR OTHER DEALINGS IN THE # SOFTWARE. \"\"\" Basic classes to",
"(string, numpy.int16 vector) \"\"\" uttid = b'' while True: arkdata = self.arkfp.read(1) if",
"# copies or substantial portions of the Software. # # THE SOFTWARE IS",
"exc_type, exc_val, exc_tb): self.close() def accumulate(self, uttid, dataelem): \"\"\" Store all the utterance",
"else: reader = KaldiIntVectorArkReader() writer = KaldiIntVectorArkWriter() reader.open(args.input_ark) writer.open(args.output_ark) for uttid2data in reader:",
"store_image = True. \"\"\" if self.arkdata is None: self.arkdata = {} self.uttids =",
"raise IOError('call close() first') self.arkfp = open(arkfile, 'rb') self.curr_arkfile = arkfile def close(self):",
"a Kaldi .feat.ark file per utterance iteratively \"\"\" def __init__(self, store_image=False): KaldiArkReader.__init__(self, store_image)",
"skip one byte data '\\x04' arkdata = self.arkfp.read(4) # read the dimension featD",
"in range(frameN): arkdata = self.arkfp.read(1) arkdata = self.arkfp.read(4) vals.append(struct.unpack('<i', arkdata)[0]) intVec = numpy.array(vals)",
"nsamps = int(dataLength / (bitsPerSample/8)) # divide 2 (Byte) self.samplerate = struct.unpack('<L', riff_header[24:28])[0]",
"per sample uttInt = [struct.unpack('<h', uttBinary[i:i+2]) for i in numpy.arange(0,len(uttBinary), 2)] samples =",
"arkdata)[0]) intVec = numpy.array(vals) uttid = uttid.decode() if self.arkdata is not None: self.accumulate(uttid,",
"self.arkfp.read(1) arkdata = self.arkfp.read(4) vals.append(struct.unpack('<i', arkdata)[0]) intVec = numpy.array(vals) uttid = uttid.decode() if",
"self.arkfp = None self.curr_arkfile = None if self.arkdata is not None: self.arkdata =",
"if uttids is None: uttids = list(uttid2feats.keys()) for uttid in uttids: intVec =",
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR",
"uttid + ' ': outData += struct.pack('<c', c.encode()) outData += struct.pack('<c', NULLC) for",
"== True:# store all the utterance data into image self.arkdata = {} #",
")[0] arkdata = self.arkfp.read(1) # skip one byte data '\\x04' arkdata = self.arkfp.read(4)",
"int16 format but %d bits per sample.' % (self.curr_arkfile, bitsPerSample)) uttBinary = self.arkfp.read(dataLength)",
"a Kaldi .wav.ark file per utterance iteratively \"\"\" def __init__(self, store_image=False): KaldiArkReader.__init__(self, store_image)",
"# Copyright (c) 2018 <NAME> # # Permission is hereby granted, free of",
"# read the coefficients vals = [] for i in range(frameN): arkdata =",
"= {uttid:samples} uttid = b'' yield uttid2data else: uttid += c class KaldiArkWriter:",
"for uttid2data in reader: print(('uttid: %s' %list(uttid2data.keys())[0])) if args.type == 'w': writer.write(uttid2data, {list(uttid2data.keys())[0]:reader.get_riff_header()})",
"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER",
"+= struct.pack('<c', FEAT_BYTE_SIZE) outData += struct.pack('<I', frameN) outData += struct.pack('<c', FEAT_BYTE_SIZE) outData +=",
"def close(self): if self.arkfp is not None: self.arkfp.close() self.arkfp = None class KaldiFeatArkWriter(KaldiArkWriter):",
"dataLength) + riff_header[44:]) class KaldiWavArkWriter(KaldiArkWriter): \"\"\" Write utterance data as a Kaldi .wav.ark",
"+= struct.pack('<i', coeff) self.arkfp.write(outData) self.arkfp.flush() def correct_chunk_size(numSamples, riff_header): \"\"\" Correct the data length",
"{} # arkdata[ID] = {matrix|vector} self.uttids = [] # remember the order of",
"as a Kaldi .feat.ark file \"\"\" def __init__(self): KaldiArkWriter.__init__(self) def write(self, uttid2feats, uttids=None):",
"is constructed with store_image = True. \"\"\" if self.arkdata is None: self.arkdata =",
"for writing a Kaldi ark file \"\"\" def __init__(self): self.arkfp = None def",
"associated documentation files (the \"Software\"), to deal # in the Software without restriction,",
"def dump_riff_file(self, riff_file, uttid): \"\"\" Dump the data in a RIFF file into",
"= argparse.ArgumentParser(description='List utterance IDs in the ark file') parser.add_argument('-t', '--type', default='f', help='Ark file",
"of this software and associated documentation files (the \"Software\"), to deal # in",
"# # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,",
"= struct.unpack('<s', arkdata)[0] if c == b' ': # read the 44 Byte",
"+= struct.pack('<c', c.encode()) self.arkfp.write(outData) with open(riff_file, 'rb') as riffF: self.arkfp.write(riffF.read()) self.arkfp.flush() def test():",
"self.uttids = None def __enter__(self): return self def __iter__(self): \"\"\" Read each utterance",
"None: raise IOError('call close() first') self.arkfp = open(arkfile, 'rb') self.curr_arkfile = arkfile def",
"= b'' yield uttid2data else: uttid += c class KaldiWavArkReader(KaldiArkReader): \"\"\" Read a",
"b'' for frameX in range(frameN): for coeff in feMat[frameX]: outData += struct.pack('<f', coeff)",
"to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of",
"b' ': # read the 44 Byte header block of the RIFF file",
"self.arkfp.read(1) # read the end symbol 'B' endSym = struct.unpack('<s', arkdata)[0] if endSym",
"store_image=False): KaldiArkReader.__init__(self, store_image) self.riff_header = None self.samplerate = None self.num_channels = None def",
"EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,",
"length in header information; see http://soundfile.sapp.org/doc/WaveFormat/ for details \"\"\" bytesPerSample = struct.unpack( '<h',",
"the Software without restriction, including without limitation the rights # to use, copy,",
"ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN",
"self.arkfp = None def __entry__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close()",
"uttid2data else: uttid += c class KaldiIntVectorArkReader(KaldiArkReader): \"\"\" Read a Kaldi integer-vector file",
"person obtaining a copy # of this software and associated documentation files (the",
"is not None: self.arkfp.close() self.arkfp = None class KaldiFeatArkWriter(KaldiArkWriter): \"\"\" Write utterance data",
"block of the RIFF file riff_header = self.arkfp.read(44) # skip '\\0' endSym =",
"' ': outData += struct.pack('<c', c.encode()) self.arkfp.write(outData) samples = uttid2feats[uttid] # write the",
"\"\"\" bytesPerSample = struct.unpack( '<h', riff_header[34:36] )[0] // 8 dataLength = numSamples *",
"b'' for samp in samples: outData += struct.pack('<h', samp) self.arkfp.write(outData) self.arkfp.flush() def dump_riff_file(self,",
"None: raise IOError('call close() first') self.arkfp = open(arkfile, 'wb') def close(self): if self.arkfp",
"self.arkfp = None class KaldiFeatArkWriter(KaldiArkWriter): \"\"\" Write utterance data as a Kaldi .feat.ark",
"struct, numpy BFM_SYM = b'BFM ' BIV_SYM = b'B' FEAT_BYTE_SIZE = b'\\x04' NULLC",
"the file pointer if it is opened \"\"\" if self.arkfp is not None:",
"None: uttids = list(uttid2feats.keys()) for uttid in uttids: outData = b'' for c",
"def build_parser(): parser = argparse.ArgumentParser(description='List utterance IDs in the ark file') parser.add_argument('-t', '--type',",
"the corrected header information uttid2header = correct_chunk_size(len(samples), uttid2headers[uttid]) self.arkfp.write(uttid2header) outData = b'' for",
"persons to whom the Software is # furnished to do so, subject to",
"struct.unpack('<4s',riff_header[0:4])[0] dataLength = struct.unpack('<L', riff_header[40:44])[0] bitsPerSample = struct.unpack('<h', riff_header[34:36])[0] # nsamps = int(dataLength",
": Python dictionary that contains the utterance ID as a key and data",
"python # -*- coding: utf-8 -*- # # MIT License # # Copyright",
"riff_header[34:36])[0] # nsamps = int(dataLength / (bitsPerSample/8)) # divide 2 (Byte) self.samplerate =",
"dump_riff_file(self, riff_file, uttid): \"\"\" Dump the data in a RIFF file into the",
"conditions: # # The above copyright notice and this permission notice shall be",
"INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A",
"BFM but %s' %(self.curr_arkfile, endSym)) arkdata = self.arkfp.read(1) # skip one byte data",
"OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,",
"documentation files (the \"Software\"), to deal # in the Software without restriction, including",
"symbol 'BFM ' endSym = struct.unpack('<4s', arkdata)[0] if endSym != BFM_SYM: raise ValueError('ERROR:",
"is not None: raise IOError('call close() first') self.arkfp = open(arkfile, 'wb') def close(self):",
"or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED \"AS",
"get_num_channel(self): return self.num_channels def __iter__(self): \"\"\" Return a tuple of an utterance ID",
"arkdata)[0] if c == b' ': arkdata = self.arkfp.read(1) # skip '\\0' arkdata",
"of charge, to any person obtaining a copy # of this software and",
"class KaldiArkReader: \"\"\" Base class for readling a Kaldi ark file \"\"\" def",
"self.arkfp is not None: self.arkfp.close() self.arkfp = None class KaldiFeatArkWriter(KaldiArkWriter): \"\"\" Write utterance",
"def __init__(self): KaldiArkWriter.__init__(self) def write(self, uttid2feats, uttids=None): if uttids is None: uttids =",
"struct.pack('<c', c.encode()) outData += struct.pack('<c', NULLC) for c in BIV_SYM.decode(): outData +=struct.pack('<c', c.encode())",
"self.arkfp is not None: self.arkfp.close() self.arkfp = None self.curr_arkfile = None if self.arkdata",
"struct.unpack('<L', riff_header[40:44])[0] bitsPerSample = struct.unpack('<h', riff_header[34:36])[0] # nsamps = int(dataLength / (bitsPerSample/8)) #",
"in numpy.arange(0,len(uttBinary), 2)] samples = numpy.array(numpy.int16(numpy.resize(uttInt, (len(uttInt),)))) self.riff_header = riff_header uttid = uttid.decode()",
"+= struct.pack('<I', frameN) outData += struct.pack('<c', FEAT_BYTE_SIZE) outData += struct.pack('<I', featD) self.arkfp.write(outData) outData",
"= self.arkfp.read(1) # skip one byte data '\\x04' arkdata = self.arkfp.read(4) # read",
"= b'' for samp in samples: outData += struct.pack('<h', samp) self.arkfp.write(outData) self.arkfp.flush() def",
"struct.unpack('<s', arkdata)[0] if c == b' ': # read the 44 Byte header",
"if endSym != BIV_SYM: raise ValueError('ERROR: %s: Unmatched symbol %s!=%s' %(self.curr_arkfile, endSym, BIV_SYM))",
"outData += struct.pack('<c', FEAT_BYTE_SIZE) outData += struct.pack('<I', frameN) self.arkfp.write(outData) # write actual vector",
"numpy.array(numpy.int16(numpy.resize(uttInt, (len(uttInt),)))) self.riff_header = riff_header uttid = uttid.decode() if self.arkdata is not None:",
"be read later \"\"\" if self.arkfp is not None: raise IOError('call close() first')",
"struct.pack('<L', dataLength) + riff_header[44:]) class KaldiWavArkWriter(KaldiArkWriter): \"\"\" Write utterance data as a Kaldi",
"as riffF: self.arkfp.write(riffF.read()) self.arkfp.flush() def test(): import argparse def build_parser(): parser = argparse.ArgumentParser(description='List",
"KaldiWavArkWriter() else: reader = KaldiIntVectorArkReader() writer = KaldiIntVectorArkWriter() reader.open(args.input_ark) writer.open(args.output_ark) for uttid2data in",
"parser = argparse.ArgumentParser(description='List utterance IDs in the ark file') parser.add_argument('-t', '--type', default='f', help='Ark",
"def open(self, arkfile): \"\"\" Set the ark file to be read later \"\"\"",
"self.samplerate = None self.num_channels = None def get_riff_header(self): return self.riff_header def get_samplerate(self): return",
"file \"\"\" def __init__(self): KaldiArkWriter.__init__(self) def write(self, uttid2feats, uttids=None): if uttids is None:",
"raise ValueError('ERROR: %s could not find BFM but %s' %(self.curr_arkfile, endSym)) arkdata =",
"the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF",
"arkdata = self.arkfp.read(1) # skip one byte data '\\x04' arkdata = self.arkfp.read(4) #",
"the ark file to be read later \"\"\" if self.arkfp is not None:",
"= KaldiIntVectorArkWriter() reader.open(args.input_ark) writer.open(args.output_ark) for uttid2data in reader: print(('uttid: %s' %list(uttid2data.keys())[0])) if args.type",
"and associated documentation files (the \"Software\"), to deal # in the Software without",
"data '\\x04' arkdata = self.arkfp.read(4) # read no. frames frameN = struct.unpack( '<I',",
"frameN = struct.unpack( '<I', arkdata )[0] arkdata = self.arkfp.read(1) # skip one byte",
"riff_header[34:36] )[0] // 8 dataLength = numSamples * bytesPerSample totalChunkSize = 36 +",
"a Kaldi ark file \"\"\" def __init__(self): self.arkfp = None def __entry__(self): return",
"'--type', default='f', help='Ark file type (i/f/w)') parser.add_argument('input_ark', help='input ark path') parser.add_argument('output_ark', help='output ark",
"self.arkfp.flush() def test(): import argparse def build_parser(): parser = argparse.ArgumentParser(description='List utterance IDs in",
"len(feMat) featD = len(feMat[0]) outData = b'' for c in uttid + '",
"write data header frameN = len(intVec) outData = b'' for c in uttid",
"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #",
"= self.arkfp.read(4) # read no. frames frameN = struct.unpack( '<I', arkdata )[0] arkdata",
"utterance ID and vector :returns: (string, numpy.vector) \"\"\" uttid = b'' while True:",
"Kaldi .wav.ark file \"\"\" def __init__(self): KaldiArkWriter.__init__(self) def write(self, uttid2feats, uttid2headers, uttids=None): if",
"= uttid2feats[uttid] # write the corrected header information uttid2header = correct_chunk_size(len(samples), uttid2headers[uttid]) self.arkfp.write(uttid2header)",
"# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR",
"arkdata )[0] coeffN = frameN * featD # read the coefficients arkdata =",
"uttid.decode() if self.arkdata is not None: self.accumulate(uttid, intVec) uttid2data = {uttid:intVec} uttid =",
"OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE",
"uttid, dataelem): \"\"\" Store all the utterance data into the RAM if this",
"if endSym != WAV_SYM: raise ValueError('ERROR: %s: could not find %s but %s'",
"+= struct.pack('<I', featD) self.arkfp.write(outData) outData = b'' for frameX in range(frameN): for coeff",
"build_parser(): parser = argparse.ArgumentParser(description='List utterance IDs in the ark file') parser.add_argument('-t', '--type', default='f',",
"arkdata)[0] # read the coefficients vals = [] for i in range(frameN): arkdata",
"of the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY",
"while True: arkdata = self.arkfp.read(1) if arkdata == b'': break c = struct.unpack('<s',",
"bit per sample uttInt = [struct.unpack('<h', uttBinary[i:i+2]) for i in numpy.arange(0,len(uttBinary), 2)] samples",
"+= struct.pack('<c', NULLC) for c in BFM_SYM.decode(): outData +=struct.pack('<c', c.encode()) outData += struct.pack('<c',",
"8 dataLength = numSamples * bytesPerSample totalChunkSize = 36 + dataLength return (riff_header[0:4]",
"= list(uttid2feats.keys()) for uttid in uttids: feMat = uttid2feats[uttid] frameN = len(feMat) featD",
"def __iter__(self): \"\"\" Read each utterance from the ark file and return it",
"intVec: outData += struct.pack('<c', FEAT_BYTE_SIZE) outData += struct.pack('<i', coeff) self.arkfp.write(outData) self.arkfp.flush() def correct_chunk_size(numSamples,",
"struct.pack('<f', coeff) self.arkfp.write(outData) self.arkfp.flush() class KaldiIntVectorArkWriter(KaldiArkWriter): \"\"\" Write utterance data as a Kaldi",
"in uttid + ' ': outData += struct.pack('<c', c.encode()) outData += struct.pack('<c', NULLC)",
"file position from .scp file \"\"\" if self.arkfp is not None: self.arkfp.seek(position_in_bytes, 0)",
"__iter__(self): \"\"\" Read each utterance from the ark file and return it :returns",
"notice and this permission notice shall be included in all # copies or",
"integer-vector file per utterance iteratively \"\"\" def __init__(self, store_image=False): KaldiArkReader.__init__(self, store_image) def __iter__(self):",
"(bitsPerSample/8)) # divide 2 (Byte) self.samplerate = struct.unpack('<L', riff_header[24:28])[0] self.num_channels = struct.unpack('<h', riff_header[22:24])[0]",
"uttBinary[i:i+2]) for i in numpy.arange(0,len(uttBinary), 2)] samples = numpy.array(numpy.int16(numpy.resize(uttInt, (len(uttInt),)))) self.riff_header = riff_header",
"data into the RAM if this is constructed with store_image = True. \"\"\"",
"information uttid2header = correct_chunk_size(len(samples), uttid2headers[uttid]) self.arkfp.write(uttid2header) outData = b'' for samp in samples:",
"\"\"\" self.arkfp = None self.curr_arkfile = None if store_image == True:# store all",
"self.arkfp.flush() def dump_riff_file(self, riff_file, uttid): \"\"\" Dump the data in a RIFF file",
"= None class KaldiFeatArkWriter(KaldiArkWriter): \"\"\" Write utterance data as a Kaldi .feat.ark file",
"uttid2headers, uttids=None): if uttids is None: uttids = list(uttid2feats.keys()) for uttid in uttids:",
"'\\0' endSym = struct.unpack('<4s',riff_header[0:4])[0] dataLength = struct.unpack('<L', riff_header[40:44])[0] bitsPerSample = struct.unpack('<h', riff_header[34:36])[0] #",
"WAV_SYM, endSym)) if bitsPerSample != 16: raise ValueError('ERROR: %s: expecting utterance with int16",
"self.arkfp.seek(position_in_bytes, 0) class KaldiFeatArkReader(KaldiArkReader): \"\"\" Read a Kaldi .feat.ark file per utterance iteratively",
"b' ': arkdata = self.arkfp.read(1) # skip '\\0' arkdata = self.arkfp.read(4) # read",
"default='f', help='Ark file type (i/f/w)') parser.add_argument('input_ark', help='input ark path') parser.add_argument('output_ark', help='output ark path')",
"True: arkdata = self.arkfp.read(1) if arkdata == b'': break c = struct.unpack('<s', arkdata)[0]",
"find %s but %s' %(self.curr_arkfile, WAV_SYM, endSym)) if bitsPerSample != 16: raise ValueError('ERROR:",
"an ark file else: self.arkdata = None self.uttids = None def __enter__(self): return",
"+= struct.pack('<c', c.encode()) self.arkfp.write(outData) samples = uttid2feats[uttid] # write the corrected header information",
"= b'' for c in uttid + ' ': outData += struct.pack('<c', c.encode())",
"self.arkdata is not None: self.accumulate(uttid, feMat) uttid2data = {uttid:feMat} uttid = b'' yield",
"if self.arkdata is not None: self.accumulate(uttid, intVec) uttid2data = {uttid:intVec} uttid = b''",
"b'' yield uttid2data else: uttid += c class KaldiWavArkReader(KaldiArkReader): \"\"\" Read a Kaldi",
"samples = numpy.array(numpy.int16(numpy.resize(uttInt, (len(uttInt),)))) self.riff_header = riff_header uttid = uttid.decode() if self.arkdata is",
"read/write a binary Kaldi ark file \"\"\" import struct, numpy BFM_SYM = b'BFM",
"is not None: self.arkfp.close() self.arkfp = None self.curr_arkfile = None if self.arkdata is",
"data '\\x04' arkdata = self.arkfp.read(4) # read the dimension featD = struct.unpack( '<I',",
"+=struct.pack('<c', c.encode()) outData += struct.pack('<c', FEAT_BYTE_SIZE) outData += struct.pack('<I', frameN) outData += struct.pack('<c',",
"= KaldiWavArkWriter() else: reader = KaldiIntVectorArkReader() writer = KaldiIntVectorArkWriter() reader.open(args.input_ark) writer.open(args.output_ark) for uttid2data",
"exc_val, exc_tb): self.close() def accumulate(self, uttid, dataelem): \"\"\" Store all the utterance data",
"a Kaldi integer-vector file per utterance iteratively \"\"\" def __init__(self, store_image=False): KaldiArkReader.__init__(self, store_image)",
"elif args.type == 'w': reader = KaldiWavArkReader() writer = KaldiWavArkWriter() else: reader =",
"is not None: self.accumulate(uttid, samples) uttid2data = {uttid:samples} uttid = b'' yield uttid2data",
"'f': reader = KaldiFeatArkReader() writer = KaldiFeatArkWriter() elif args.type == 'w': reader =",
"= KaldiFeatArkReader() writer = KaldiFeatArkWriter() elif args.type == 'w': reader = KaldiWavArkReader() writer",
"free of charge, to any person obtaining a copy # of this software",
"of feat ark file') c = struct.unpack('<s', arkdata)[0] if c == b' ':",
"outData += struct.pack('<c', FEAT_BYTE_SIZE) outData += struct.pack('<I', featD) self.arkfp.write(outData) outData = b'' for",
"= {} self.uttids = [] def seek(self, position_in_bytes): \"\"\" Skip the file pointer.",
"with store_image = True. \"\"\" if self.arkdata is None: self.arkdata = {} self.uttids",
"Skip the file pointer. You can pick up the file position from .scp",
"%(self.curr_arkfile, endSym, BIV_SYM)) arkdata = self.arkfp.read(1) # skip one byte data '\\x04' arkdata",
"(self.curr_arkfile, bitsPerSample)) uttBinary = self.arkfp.read(dataLength) # expecting 16 bit per sample uttInt =",
"StopIteration('End of feat ark file') c = struct.unpack('<s', arkdata)[0] if c == b'",
"__entry__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() def open(self, arkfile): if",
"data outData = b'' for coeff in intVec: outData += struct.pack('<c', FEAT_BYTE_SIZE) outData",
"b'' for c in uttid + ' ': outData += struct.pack('<c', c.encode()) outData",
"matrix where each row vector correpsonds to a feature vector per frame :returns:",
"= len(feMat[0]) outData = b'' for c in uttid + ' ': outData",
"16: raise ValueError('ERROR: %s: expecting utterance with int16 format but %d bits per",
"arkdata = self.arkfp.read(4) # read no. frames frameN = struct.unpack( '<I', arkdata )[0]",
"the dimension featD = struct.unpack( '<I', arkdata )[0] coeffN = frameN * featD",
"close() first') self.arkfp = open(arkfile, 'rb') self.curr_arkfile = arkfile def close(self): \"\"\" Close",
"numpy.matrix) \"\"\" uttid = b'' while True: arkdata = self.arkfp.read(1) if arkdata ==",
"KaldiArkReader.__init__(self, store_image) self.riff_header = None self.samplerate = None self.num_channels = None def get_riff_header(self):",
".feat.ark file per utterance iteratively \"\"\" def __init__(self, store_image=False): KaldiArkReader.__init__(self, store_image) def __iter__(self):",
"[] for i in range(frameN): arkdata = self.arkfp.read(1) arkdata = self.arkfp.read(4) vals.append(struct.unpack('<i', arkdata)[0])",
"arkdata)[0] if endSym != BIV_SYM: raise ValueError('ERROR: %s: Unmatched symbol %s!=%s' %(self.curr_arkfile, endSym,",
"Correct the data length in header information; see http://soundfile.sapp.org/doc/WaveFormat/ for details \"\"\" bytesPerSample",
"position_in_bytes): \"\"\" Skip the file pointer. You can pick up the file position",
"= {} self.uttids = [] self.arkdata[uttid] = dataelem self.uttids.append(uttid) def open(self, arkfile): \"\"\"",
"= self.arkfp.read(1) # skip '\\0' arkdata = self.arkfp.read(4) # read the end symbol",
"= [] for i in range(frameN): arkdata = self.arkfp.read(1) arkdata = self.arkfp.read(4) vals.append(struct.unpack('<i',",
"THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN",
"a Kaldi .wav.ark file \"\"\" def __init__(self): KaldiArkWriter.__init__(self) def write(self, uttid2feats, uttid2headers, uttids=None):",
"arkdata = self.arkfp.read(4) # read the end symbol 'BFM ' endSym = struct.unpack('<4s',",
"return parser parser = build_parser() args, argv = parser.parse_known_args() if args.type == 'f':",
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #",
"SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES",
"ark file else: self.arkdata = None self.uttids = None def __enter__(self): return self",
"if True \"\"\" self.arkfp = None self.curr_arkfile = None if store_image == True:#",
"opened \"\"\" if self.arkfp is not None: self.arkfp.close() self.arkfp = None self.curr_arkfile =",
"\"\"\" Return a tuple of an utterance ID and feature matrix where each",
"!= BFM_SYM: raise ValueError('ERROR: %s could not find BFM but %s' %(self.curr_arkfile, endSym))",
"argparse def build_parser(): parser = argparse.ArgumentParser(description='List utterance IDs in the ark file') parser.add_argument('-t',",
"Software, and to permit persons to whom the Software is # furnished to",
"if self.arkfp is not None: self.arkfp.close() self.arkfp = None self.curr_arkfile = None if",
"self.arkfp = open(arkfile, 'wb') def close(self): if self.arkfp is not None: self.arkfp.close() self.arkfp",
"return self def __iter__(self): \"\"\" Read each utterance from the ark file and",
"utterance from the ark file and return it :returns : Python dictionary that",
"* featD # read the coefficients arkdata = self.arkfp.read(coeffN * 4) feMat =",
"numpy BFM_SYM = b'BFM ' BIV_SYM = b'B' FEAT_BYTE_SIZE = b'\\x04' NULLC =",
"riff_header[24:28])[0] self.num_channels = struct.unpack('<h', riff_header[22:24])[0] if endSym != WAV_SYM: raise ValueError('ERROR: %s: could",
"# # Copyright (c) 2018 <NAME> # # Permission is hereby granted, free",
"uttid2header = correct_chunk_size(len(samples), uttid2headers[uttid]) self.arkfp.write(uttid2header) outData = b'' for samp in samples: outData",
"endSym = struct.unpack('<s', arkdata)[0] if endSym != BIV_SYM: raise ValueError('ERROR: %s: Unmatched symbol",
"__iter__(self): \"\"\" Return a tuple of an utterance ID and feature matrix where",
"audio samples as a 16-bit integer vector :returns: (string, numpy.int16 vector) \"\"\" uttid",
"16 bit per sample uttInt = [struct.unpack('<h', uttBinary[i:i+2]) for i in numpy.arange(0,len(uttBinary), 2)]",
"intVec) uttid2data = {uttid:intVec} uttid = b'' yield uttid2data else: uttid += c",
"'\\x04' arkdata = self.arkfp.read(4) # read no. frames frameN = struct.unpack('<i', arkdata)[0] #",
"class KaldiWavArkReader(KaldiArkReader): \"\"\" Read a Kaldi .wav.ark file per utterance iteratively \"\"\" def",
"if args.type == 'f': reader = KaldiFeatArkReader() writer = KaldiFeatArkWriter() elif args.type ==",
"' ': outData += struct.pack('<c', c.encode()) outData += struct.pack('<c', NULLC) for c in",
"the 44 Byte header block of the RIFF file riff_header = self.arkfp.read(44) #",
"correpsonds to a feature vector per frame :returns: (string, numpy.matrix) \"\"\" uttid =",
"# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,",
"Base class for writing a Kaldi ark file \"\"\" def __init__(self): self.arkfp =",
"= b'RIFF' class KaldiArkReader: \"\"\" Base class for readling a Kaldi ark file",
"# MIT License # # Copyright (c) 2018 <NAME> # # Permission is",
"': outData += struct.pack('<c', c.encode()) outData += struct.pack('<c', NULLC) for c in BIV_SYM.decode():",
"= numpy.array(numpy.int16(numpy.resize(uttInt, (len(uttInt),)))) self.riff_header = riff_header uttid = uttid.decode() if self.arkdata is not",
"feat ark file') c = struct.unpack('<s', arkdata)[0] if c == b' ': arkdata",
"uttids: feMat = uttid2feats[uttid] frameN = len(feMat) featD = len(feMat[0]) outData = b''",
"reader = KaldiIntVectorArkReader() writer = KaldiIntVectorArkWriter() reader.open(args.input_ark) writer.open(args.output_ark) for uttid2data in reader: print(('uttid:",
"def close(self): \"\"\" Close the file pointer if it is opened \"\"\" if",
"file else: self.arkdata = None self.uttids = None def __enter__(self): return self def",
"RIFF file riff_header = self.arkfp.read(44) # skip '\\0' endSym = struct.unpack('<4s',riff_header[0:4])[0] dataLength =",
"OTHER DEALINGS IN THE # SOFTWARE. \"\"\" Basic classes to read/write a binary",
"in the Software without restriction, including without limitation the rights # to use,",
"(string, numpy.matrix) \"\"\" uttid = b'' while True: arkdata = self.arkfp.read(1) if arkdata",
"= self.arkfp.read(1) # skip '\\0' arkdata = self.arkfp.read(1) # read the end symbol",
"for coeff in feMat[frameX]: outData += struct.pack('<f', coeff) self.arkfp.write(outData) self.arkfp.flush() class KaldiIntVectorArkWriter(KaldiArkWriter): \"\"\"",
"PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS",
"uttid = uttid.decode() if self.arkdata is not None: self.accumulate(uttid, feMat) uttid2data = {uttid:feMat}",
"http://soundfile.sapp.org/doc/WaveFormat/ for details \"\"\" bytesPerSample = struct.unpack( '<h', riff_header[34:36] )[0] // 8 dataLength",
"is not None: self.arkfp.seek(position_in_bytes, 0) class KaldiFeatArkReader(KaldiArkReader): \"\"\" Read a Kaldi .feat.ark file",
"endSym)) if bitsPerSample != 16: raise ValueError('ERROR: %s: expecting utterance with int16 format",
"a 16-bit integer vector :returns: (string, numpy.int16 vector) \"\"\" uttid = b'' while",
"data as a value \"\"\" raise NotImplemented('Implement this') def __exit__(self, exc_type, exc_val, exc_tb):",
"read later \"\"\" if self.arkfp is not None: raise IOError('call close() first') self.arkfp",
"numpy.int16 vector) \"\"\" uttid = b'' while True: arkdata = self.arkfp.read(1) if arkdata",
"uttid + ' ': outData += struct.pack('<c', c.encode()) self.arkfp.write(outData) samples = uttid2feats[uttid] #",
"help='input ark path') parser.add_argument('output_ark', help='output ark path') return parser parser = build_parser() args,",
"and return it :returns : Python dictionary that contains the utterance ID as",
"__iter__(self): \"\"\" Return a tuple of an utterance ID and audio samples as",
"arkdata = self.arkfp.read(1) if arkdata == b'': raise StopIteration('End of feat ark file')",
"ID and audio samples as a 16-bit integer vector :returns: (string, numpy.int16 vector)",
"Write utterance data as a Kaldi int-vector ark file \"\"\" def __init__(self): KaldiArkWriter.__init__(self)",
"ark file will be kept in RAM if True \"\"\" self.arkfp = None",
"NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE",
"2 (Byte) self.samplerate = struct.unpack('<L', riff_header[24:28])[0] self.num_channels = struct.unpack('<h', riff_header[22:24])[0] if endSym !=",
"MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL",
"def __iter__(self): \"\"\" Return a tuple of an utterance ID and feature matrix",
"open(self, arkfile): if self.arkfp is not None: raise IOError('call close() first') self.arkfp =",
"None: self.arkfp.close() self.arkfp = None class KaldiFeatArkWriter(KaldiArkWriter): \"\"\" Write utterance data as a",
"Every utterance data in the ark file will be kept in RAM if",
"The above copyright notice and this permission notice shall be included in all",
"and/or sell # copies of the Software, and to permit persons to whom",
"+= struct.pack('<c', c.encode()) outData += struct.pack('<c', NULLC) for c in BFM_SYM.decode(): outData +=struct.pack('<c',",
"BFM_SYM.decode(): outData +=struct.pack('<c', c.encode()) outData += struct.pack('<c', FEAT_BYTE_SIZE) outData += struct.pack('<I', frameN) outData",
"bitsPerSample)) uttBinary = self.arkfp.read(dataLength) # expecting 16 bit per sample uttInt = [struct.unpack('<h',",
"for uttid in uttids: outData = b'' for c in uttid + '",
"TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE",
"list(uttid2feats.keys()) for uttid in uttids: feMat = uttid2feats[uttid] frameN = len(feMat) featD =",
"self.arkfp.read(4) # read the end symbol 'BFM ' endSym = struct.unpack('<4s', arkdata)[0] if",
"outData += struct.pack('<c', NULLC) for c in BFM_SYM.decode(): outData +=struct.pack('<c', c.encode()) outData +=",
"is not None: self.accumulate(uttid, intVec) uttid2data = {uttid:intVec} uttid = b'' yield uttid2data",
"uttid2data else: uttid += c class KaldiArkWriter: \"\"\" Base class for writing a",
"= [struct.unpack('<h', uttBinary[i:i+2]) for i in numpy.arange(0,len(uttBinary), 2)] samples = numpy.array(numpy.int16(numpy.resize(uttInt, (len(uttInt),)))) self.riff_header",
"\"\"\" Read each utterance from the ark file and return it :returns :",
"file \"\"\" def __init__(self): self.arkfp = None def __entry__(self): return self def __exit__(self,",
"!= BIV_SYM: raise ValueError('ERROR: %s: Unmatched symbol %s!=%s' %(self.curr_arkfile, endSym, BIV_SYM)) arkdata =",
"# # The above copyright notice and this permission notice shall be included",
"self.curr_arkfile = None if self.arkdata is not None: self.arkdata = {} self.uttids =",
"\"Software\"), to deal # in the Software without restriction, including without limitation the",
"header block of the RIFF file riff_header = self.arkfp.read(44) # skip '\\0' endSym",
"samp in samples: outData += struct.pack('<h', samp) self.arkfp.write(outData) self.arkfp.flush() def dump_riff_file(self, riff_file, uttid):",
"{uttid:samples} uttid = b'' yield uttid2data else: uttid += c class KaldiArkWriter: \"\"\"",
"# write data header frameN = len(intVec) outData = b'' for c in",
"for i in range(frameN): arkdata = self.arkfp.read(1) arkdata = self.arkfp.read(4) vals.append(struct.unpack('<i', arkdata)[0]) intVec",
"uttid2data in reader: print(('uttid: %s' %list(uttid2data.keys())[0])) if args.type == 'w': writer.write(uttid2data, {list(uttid2data.keys())[0]:reader.get_riff_header()}) else:",
"arkfile): \"\"\" Set the ark file to be read later \"\"\" if self.arkfp",
"return self.num_channels def __iter__(self): \"\"\" Return a tuple of an utterance ID and",
"not None: raise IOError('call close() first') self.arkfp = open(arkfile, 'rb') self.curr_arkfile = arkfile",
"[] # remember the order of utterance IDs in an ark file else:",
"': outData += struct.pack('<c', c.encode()) outData += struct.pack('<c', NULLC) for c in BFM_SYM.decode():",
"struct.unpack('<h', riff_header[22:24])[0] if endSym != WAV_SYM: raise ValueError('ERROR: %s: could not find %s",
"IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR",
"distribute, sublicense, and/or sell # copies of the Software, and to permit persons",
"{matrix|vector} self.uttids = [] # remember the order of utterance IDs in an",
"sample uttInt = [struct.unpack('<h', uttBinary[i:i+2]) for i in numpy.arange(0,len(uttBinary), 2)] samples = numpy.array(numpy.int16(numpy.resize(uttInt,",
"in an ark file else: self.arkdata = None self.uttids = None def __enter__(self):",
"read no. frames frameN = struct.unpack( '<I', arkdata )[0] arkdata = self.arkfp.read(1) #",
"len(feMat[0]) outData = b'' for c in uttid + ' ': outData +=",
"test(): import argparse def build_parser(): parser = argparse.ArgumentParser(description='List utterance IDs in the ark",
"= uttid2feats[uttid] frameN = len(feMat) featD = len(feMat[0]) outData = b'' for c",
"KaldiWavArkReader() writer = KaldiWavArkWriter() else: reader = KaldiIntVectorArkReader() writer = KaldiIntVectorArkWriter() reader.open(args.input_ark) writer.open(args.output_ark)",
"WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO",
"WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED",
"arkdata = self.arkfp.read(1) # read the end symbol 'B' endSym = struct.unpack('<s', arkdata)[0]",
"is not None: self.accumulate(uttid, feMat) uttid2data = {uttid:feMat} uttid = b'' yield uttid2data",
"ark path') parser.add_argument('output_ark', help='output ark path') return parser parser = build_parser() args, argv",
"store all the utterance data into image self.arkdata = {} # arkdata[ID] =",
"not find BFM but %s' %(self.curr_arkfile, endSym)) arkdata = self.arkfp.read(1) # skip one",
"outData += struct.pack('<h', samp) self.arkfp.write(outData) self.arkfp.flush() def dump_riff_file(self, riff_file, uttid): \"\"\" Dump the",
"# nsamps = int(dataLength / (bitsPerSample/8)) # divide 2 (Byte) self.samplerate = struct.unpack('<L',",
"portions of the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT",
"do so, subject to the following conditions: # # The above copyright notice",
"KaldiFeatArkWriter() elif args.type == 'w': reader = KaldiWavArkReader() writer = KaldiWavArkWriter() else: reader",
"c.encode()) outData += struct.pack('<c', FEAT_BYTE_SIZE) outData += struct.pack('<I', frameN) self.arkfp.write(outData) # write actual",
"RAM if True \"\"\" self.arkfp = None self.curr_arkfile = None if store_image ==",
"struct.unpack('<4s', arkdata)[0] if endSym != BFM_SYM: raise ValueError('ERROR: %s could not find BFM",
"BIV_SYM)) arkdata = self.arkfp.read(1) # skip one byte data '\\x04' arkdata = self.arkfp.read(4)",
"all the utterance data into image self.arkdata = {} # arkdata[ID] = {matrix|vector}",
"+= c class KaldiIntVectorArkReader(KaldiArkReader): \"\"\" Read a Kaldi integer-vector file per utterance iteratively",
"# read the coefficients arkdata = self.arkfp.read(coeffN * 4) feMat = numpy.reshape(struct.unpack('<%df' %(coeffN),",
"'rb') as riffF: self.arkfp.write(riffF.read()) self.arkfp.flush() def test(): import argparse def build_parser(): parser =",
"Base class for readling a Kaldi ark file \"\"\" def __init__(self, store_image=False): \"\"\"",
"the file pointer. You can pick up the file position from .scp file",
"\"\"\" Write utterance data as a Kaldi .wav.ark file \"\"\" def __init__(self): KaldiArkWriter.__init__(self)",
"permit persons to whom the Software is # furnished to do so, subject",
"class KaldiArkWriter: \"\"\" Base class for writing a Kaldi ark file \"\"\" def",
"store_image=False): KaldiArkReader.__init__(self, store_image) def __iter__(self): \"\"\" Return a tuple of an utterance ID",
"b'\\0' WAV_SYM = b'RIFF' class KaldiArkReader: \"\"\" Base class for readling a Kaldi",
"utterance data as a Kaldi .feat.ark file \"\"\" def __init__(self): KaldiArkWriter.__init__(self) def write(self,",
"wav ark file') c = struct.unpack('<s', arkdata)[0] if c == b' ': #",
"c == b' ': # read the 44 Byte header block of the",
"__exit__(self, exc_type, exc_val, exc_tb): self.close() def accumulate(self, uttid, dataelem): \"\"\" Store all the",
"find BFM but %s' %(self.curr_arkfile, endSym)) arkdata = self.arkfp.read(1) # skip one byte",
"BIV_SYM.decode(): outData +=struct.pack('<c', c.encode()) outData += struct.pack('<c', FEAT_BYTE_SIZE) outData += struct.pack('<I', frameN) self.arkfp.write(outData)",
"of the RIFF file riff_header = self.arkfp.read(44) # skip '\\0' endSym = struct.unpack('<4s',riff_header[0:4])[0]",
"self.arkdata = {} # arkdata[ID] = {matrix|vector} self.uttids = [] # remember the",
"utterance data into the RAM if this is constructed with store_image = True.",
"KaldiIntVectorArkWriter(KaldiArkWriter): \"\"\" Write utterance data as a Kaldi int-vector ark file \"\"\" def",
"data as a Kaldi .feat.ark file \"\"\" def __init__(self): KaldiArkWriter.__init__(self) def write(self, uttid2feats,",
"byte data '\\x04' arkdata = self.arkfp.read(4) # read no. frames frameN = struct.unpack('<i',",
"for c in BFM_SYM.decode(): outData +=struct.pack('<c', c.encode()) outData += struct.pack('<c', FEAT_BYTE_SIZE) outData +=",
"in the ark file') parser.add_argument('-t', '--type', default='f', help='Ark file type (i/f/w)') parser.add_argument('input_ark', help='input",
"feMat = numpy.reshape(struct.unpack('<%df' %(coeffN), arkdata), (frameN,featD)) uttid = uttid.decode() if self.arkdata is not",
"FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS",
"utterance with int16 format but %d bits per sample.' % (self.curr_arkfile, bitsPerSample)) uttBinary",
"Kaldi .feat.ark file per utterance iteratively \"\"\" def __init__(self, store_image=False): KaldiArkReader.__init__(self, store_image) def",
"uttids is None: uttids = list(uttid2feats.keys()) for uttid in uttids: outData = b''",
"if it is opened \"\"\" if self.arkfp is not None: self.arkfp.close() self.arkfp =",
"skip '\\0' arkdata = self.arkfp.read(1) # read the end symbol 'B' endSym =",
"# read no. frames frameN = struct.unpack('<i', arkdata)[0] # read the coefficients vals",
"def __init__(self, store_image=False): KaldiArkReader.__init__(self, store_image) self.riff_header = None self.samplerate = None self.num_channels =",
"%list(uttid2data.keys())[0])) if args.type == 'w': writer.write(uttid2data, {list(uttid2data.keys())[0]:reader.get_riff_header()}) else: writer.write(uttid2data) reader.close() writer.close() if __name__",
"of an utterance ID and feature matrix where each row vector correpsonds to",
"where each row vector correpsonds to a feature vector per frame :returns: (string,",
"correct_chunk_size(numSamples, riff_header): \"\"\" Correct the data length in header information; see http://soundfile.sapp.org/doc/WaveFormat/ for",
"self.close() def open(self, arkfile): if self.arkfp is not None: raise IOError('call close() first')",
"Kaldi .feat.ark file \"\"\" def __init__(self): KaldiArkWriter.__init__(self) def write(self, uttid2feats, uttids=None): if uttids",
"in BIV_SYM.decode(): outData +=struct.pack('<c', c.encode()) outData += struct.pack('<c', FEAT_BYTE_SIZE) outData += struct.pack('<I', frameN)",
"struct.unpack('<i', arkdata)[0] # read the coefficients vals = [] for i in range(frameN):",
"struct.pack('<c', FEAT_BYTE_SIZE) outData += struct.pack('<I', frameN) outData += struct.pack('<c', FEAT_BYTE_SIZE) outData += struct.pack('<I',",
"featD) self.arkfp.write(outData) outData = b'' for frameX in range(frameN): for coeff in feMat[frameX]:",
"c in BFM_SYM.decode(): outData +=struct.pack('<c', c.encode()) outData += struct.pack('<c', FEAT_BYTE_SIZE) outData += struct.pack('<I',",
"and data as a value \"\"\" raise NotImplemented('Implement this') def __exit__(self, exc_type, exc_val,",
"# -*- coding: utf-8 -*- # # MIT License # # Copyright (c)",
"IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE",
"= parser.parse_known_args() if args.type == 'f': reader = KaldiFeatArkReader() writer = KaldiFeatArkWriter() elif",
"header information uttid2header = correct_chunk_size(len(samples), uttid2headers[uttid]) self.arkfp.write(uttid2header) outData = b'' for samp in",
"file') c = struct.unpack('<s', arkdata)[0] if c == b' ': # read the",
"a key and data as a value \"\"\" raise NotImplemented('Implement this') def __exit__(self,",
"open(arkfile, 'wb') def close(self): if self.arkfp is not None: self.arkfp.close() self.arkfp = None",
"outData += struct.pack('<f', coeff) self.arkfp.write(outData) self.arkfp.flush() class KaldiIntVectorArkWriter(KaldiArkWriter): \"\"\" Write utterance data as",
"the coefficients vals = [] for i in range(frameN): arkdata = self.arkfp.read(1) arkdata",
"not None: self.arkfp.close() self.arkfp = None class KaldiFeatArkWriter(KaldiArkWriter): \"\"\" Write utterance data as",
"constructed with store_image = True. \"\"\" if self.arkdata is None: self.arkdata = {}",
"raise ValueError('ERROR: %s: Unmatched symbol %s!=%s' %(self.curr_arkfile, endSym, BIV_SYM)) arkdata = self.arkfp.read(1) #",
"== 'w': writer.write(uttid2data, {list(uttid2data.keys())[0]:reader.get_riff_header()}) else: writer.write(uttid2data) reader.close() writer.close() if __name__ == '__main__': test()",
"data length in header information; see http://soundfile.sapp.org/doc/WaveFormat/ for details \"\"\" bytesPerSample = struct.unpack(",
"header information; see http://soundfile.sapp.org/doc/WaveFormat/ for details \"\"\" bytesPerSample = struct.unpack( '<h', riff_header[34:36] )[0]",
"and audio samples as a 16-bit integer vector :returns: (string, numpy.int16 vector) \"\"\"",
"# arkdata[ID] = {matrix|vector} self.uttids = [] # remember the order of utterance",
"close(self): if self.arkfp is not None: self.arkfp.close() self.arkfp = None class KaldiFeatArkWriter(KaldiArkWriter): \"\"\"",
"struct.pack('<L', totalChunkSize) + riff_header[8:40] + struct.pack('<L', dataLength) + riff_header[44:]) class KaldiWavArkWriter(KaldiArkWriter): \"\"\" Write",
"= None def get_riff_header(self): return self.riff_header def get_samplerate(self): return self.samplerate def get_num_channel(self): return",
"it is opened \"\"\" if self.arkfp is not None: self.arkfp.close() self.arkfp = None",
"NULLC = b'\\0' WAV_SYM = b'RIFF' class KaldiArkReader: \"\"\" Base class for readling",
"dictionary that contains the utterance ID as a key and data as a",
"struct.pack('<I', frameN) outData += struct.pack('<c', FEAT_BYTE_SIZE) outData += struct.pack('<I', featD) self.arkfp.write(outData) outData =",
"= None if self.arkdata is not None: self.arkdata = {} self.uttids = []",
"file per utterance iteratively \"\"\" def __init__(self, store_image=False): KaldiArkReader.__init__(self, store_image) self.riff_header = None",
"totalChunkSize) + riff_header[8:40] + struct.pack('<L', dataLength) + riff_header[44:]) class KaldiWavArkWriter(KaldiArkWriter): \"\"\" Write utterance",
")[0] // 8 dataLength = numSamples * bytesPerSample totalChunkSize = 36 + dataLength",
"as a Kaldi int-vector ark file \"\"\" def __init__(self): KaldiArkWriter.__init__(self) def write(self, uttid2feats,",
"self.arkfp.write(uttid2header) outData = b'' for samp in samples: outData += struct.pack('<h', samp) self.arkfp.write(outData)",
"self.arkfp.read(1) if arkdata == b'': break c = struct.unpack('<s', arkdata)[0] if c ==",
"'\\0' arkdata = self.arkfp.read(4) # read the end symbol 'BFM ' endSym =",
"hereby granted, free of charge, to any person obtaining a copy # of",
"vector) \"\"\" uttid = b'' while True: arkdata = self.arkfp.read(1) if arkdata ==",
"== b'': raise StopIteration('End of feat ark file') c = struct.unpack('<s', arkdata)[0] if",
"open(arkfile, 'rb') self.curr_arkfile = arkfile def close(self): \"\"\" Close the file pointer if",
"%s: could not find %s but %s' %(self.curr_arkfile, WAV_SYM, endSym)) if bitsPerSample !="
] |
[
"None, None) reporter.report_success(it_block, 1000) reporter.report_success(it_block, 500) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"2 passed in 1.50 seconds\")",
"pynetest.expectations import expect from pynetest.lib.result_reporters.printing_reporter import PrintingReporter from pynetest.lib.result_reporters.pyne_result_reporters import PyneStatSummaryReporter from pynetest.lib.pyne_test_blocks",
"None, None) reporter.report_enter_context(describe_block) reporter.report_enter_context(describe_block) reporter.report_exit_context(describe_block) expect(reporter.depth).to_be(1) reporter.report_exit_context(describe_block) expect(reporter.depth).to_be(0) def test__report_end_result__when_a_test_has_failed__it_prints_stats(): with StubPrint(): reporter",
"from pynetest.lib.result_reporters.printing_reporter import PrintingReporter from pynetest.lib.result_reporters.pyne_result_reporters import PyneStatSummaryReporter from pynetest.lib.pyne_test_blocks import ItBlock, DescribeBlock",
"reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 0) expect(reporter.stats.is_failure).to_be(True) def test__report_failure__increases_the_total_timing(): reporter = PyneStatSummaryReporter() it_block =",
"exception\"), 0) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 0) expect(reporter.stats.test_count).to_be(2) def test__report_failure__sets_overall_failure(): reporter = PyneStatSummaryReporter()",
"None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 1000) reporter.report_success(it_block, 500) reporter.report_success(it_block, 500) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"1",
"def test__report_end_result__when_all_tests_passed__it_prints_stats(): with StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter()) it_block = ItBlock(None, None, None) reporter.report_success(it_block,",
"it_block, Exception(\"some exception\"), 0) expect(reporter.stats.is_failure).to_be(True) def test__report_failure__increases_the_total_timing(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None,",
"None) reporter = PyneStatSummaryReporter() reporter.report_enter_context(describe_block) reporter.report_enter_context(describe_block) reporter.report_success(it_block, 1000) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 1000)",
"= ItBlock(None, None, None) reporter.report_pending(it_block) reporter.report_pending(it_block) expect(reporter.stats.test_count).to_be(2) def test__report_enter_context__increases_depth(): reporter = PyneStatSummaryReporter() describe_block",
"it_block = ItBlock(None, None, None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 0) expect(reporter.stats.is_failure).to_be(True) def test__report_failure__increases_the_total_timing():",
"test__report_exit_context__decreases_depth(): reporter = PyneStatSummaryReporter() describe_block = DescribeBlock(None, None, None) reporter.report_enter_context(describe_block) reporter.report_enter_context(describe_block) reporter.report_exit_context(describe_block) expect(reporter.depth).to_be(1)",
"<reponame>Avvir/pyne from pynetest.expectations import expect from pynetest.lib.result_reporters.printing_reporter import PrintingReporter from pynetest.lib.result_reporters.pyne_result_reporters import PyneStatSummaryReporter",
"None, None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 1000) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 20) expect(reporter.stats.total_timing_millis).to_be(1020)",
"DescribeBlock(None, None, None) reporter.report_enter_context(describe_block) expect(reporter.depth).to_be(1) reporter.report_enter_context(describe_block) expect(reporter.depth).to_be(2) def test__report_exit_context__decreases_depth(): reporter = PyneStatSummaryReporter() describe_block",
"= PyneStatSummaryReporter() describe_block = DescribeBlock(None, None, None) reporter.report_enter_context(describe_block) expect(reporter.depth).to_be(1) reporter.report_enter_context(describe_block) expect(reporter.depth).to_be(2) def test__report_exit_context__decreases_depth():",
"reporter.report_end_result() expect(printed_text[0]).to_contain(\"Ran 0 tests\") def test__reset__sets_stats_to_0(): describe_block = DescribeBlock(None, None, None) it_block =",
"def test__report_enter_context__increases_depth(): reporter = PyneStatSummaryReporter() describe_block = DescribeBlock(None, None, None) reporter.report_enter_context(describe_block) expect(reporter.depth).to_be(1) reporter.report_enter_context(describe_block)",
"None, None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 0) expect(reporter.stats.is_failure).to_be(True) def test__report_failure__increases_the_total_timing(): reporter = PyneStatSummaryReporter()",
"StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter()) it_block = ItBlock(None, None, None) reporter.report_success(it_block, 1000) reporter.report_success(it_block, 500)",
"def test__reset__sets_stats_to_0(): describe_block = DescribeBlock(None, None, None) it_block = ItBlock(None, None, None) reporter",
"= ItBlock(None, None, None) reporter.report_success(it_block, 0) reporter.report_success(it_block, 0) expect(reporter.stats.test_count).to_be(2) def test__report_success__increases_the_passes_count(): reporter =",
"ItBlock(None, None, None) reporter.report_success(it_block, 0) reporter.report_success(it_block, 0) expect(reporter.stats.pass_count).to_be(2) def test__report_success__increases_the_total_timing(): reporter = PyneStatSummaryReporter()",
"= ItBlock(None, None, None) reporter.report_success(it_block, 10) reporter.report_success(it_block, 300) expect(reporter.stats.total_timing_millis).to_be(310) def test__report_pending__increases_the_test_run_count(): reporter =",
"None, None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 0) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 0) expect(reporter.stats.test_count).to_be(2)",
"Exception(\"some exception\"), 0) expect(reporter.stats.test_count).to_be(2) def test__report_failure__sets_overall_failure(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None,",
"ItBlock(None, None, None) reporter.report_success(it_block, 10) reporter.report_success(it_block, 300) expect(reporter.stats.total_timing_millis).to_be(310) def test__report_pending__increases_the_test_run_count(): reporter = PyneStatSummaryReporter()",
"ItBlock(None, None, None) reporter.report_pending(it_block) reporter.report_pending(it_block) expect(reporter.stats.test_count).to_be(2) def test__report_enter_context__increases_depth(): reporter = PyneStatSummaryReporter() describe_block =",
"ItBlock(None, None, None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 0) expect(reporter.stats.is_failure).to_be(True) def test__report_failure__increases_the_total_timing(): reporter =",
"None) reporter.report_pending(it_block) reporter.report_pending(it_block) expect(reporter.stats.test_count).to_be(2) def test__report_enter_context__increases_depth(): reporter = PyneStatSummaryReporter() describe_block = DescribeBlock(None, None,",
"None, None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 1000) reporter.report_success(it_block, 500) reporter.report_success(it_block, 500) printed_text.clear() reporter.report_end_result()",
"None, None) reporter = PyneStatSummaryReporter() reporter.report_enter_context(describe_block) reporter.report_enter_context(describe_block) reporter.report_success(it_block, 1000) reporter.report_failure(it_block, it_block, Exception(\"some exception\"),",
"0) expect(reporter.stats.pass_count).to_be(2) def test__report_success__increases_the_total_timing(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_success(it_block,",
"in 1.00 seconds\") def test__report_end_result__when_no_tests_run__reports_stats(): with StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter()) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"Ran",
"it_block, Exception(\"some exception\"), 1000) reporter.report_success(it_block, 500) reporter.report_success(it_block, 500) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"1 failed, 2",
"= PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_success(it_block, 0) reporter.report_success(it_block, 0) expect(reporter.stats.pass_count).to_be(2) def",
"printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"2 passed in 1.50 seconds\") def test__report_end_result__test_is_pending__reports_stats(): with StubPrint(): reporter =",
"def test__report_success__increases_the_test_run_count(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_success(it_block, 0) reporter.report_success(it_block,",
"= ItBlock(None, None, None) reporter = PyneStatSummaryReporter() reporter.report_enter_context(describe_block) reporter.report_enter_context(describe_block) reporter.report_success(it_block, 1000) reporter.report_failure(it_block, it_block,",
"test__report_success__increases_the_total_timing(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_success(it_block, 10) reporter.report_success(it_block, 300)",
"= PyneStatSummaryReporter() describe_block = DescribeBlock(None, None, None) reporter.report_enter_context(describe_block) reporter.report_enter_context(describe_block) reporter.report_exit_context(describe_block) expect(reporter.depth).to_be(1) reporter.report_exit_context(describe_block) expect(reporter.depth).to_be(0)",
"StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter()) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"Ran 0 tests\") def test__reset__sets_stats_to_0(): describe_block =",
"reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_pending(it_block) reporter.report_pending(it_block) expect(reporter.stats.test_count).to_be(2) def test__report_enter_context__increases_depth():",
"reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_success(it_block, 10) reporter.report_success(it_block, 300) expect(reporter.stats.total_timing_millis).to_be(310)",
"reporter.report_end_result() expect(printed_text[0]).to_contain(\"1 passed, 1 pending in 1.00 seconds\") def test__report_end_result__when_no_tests_run__reports_stats(): with StubPrint(): reporter",
"expect(reporter.stats.test_count).to_be(2) def test__report_enter_context__increases_depth(): reporter = PyneStatSummaryReporter() describe_block = DescribeBlock(None, None, None) reporter.report_enter_context(describe_block) expect(reporter.depth).to_be(1)",
"= ItBlock(None, None, None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 0) expect(reporter.stats.is_failure).to_be(True) def test__report_failure__increases_the_total_timing(): reporter",
"reporter.report_success(it_block, 10) reporter.report_success(it_block, 300) expect(reporter.stats.total_timing_millis).to_be(310) def test__report_pending__increases_the_test_run_count(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None,",
"pending=True) reporter.report_success(passing_it_block, 1000) reporter.report_pending(pending_it_block) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"1 passed, 1 pending in 1.00 seconds\")",
"reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 0) expect(reporter.stats.failure_count).to_be(2) def test__report_failure__increases_the_test_run_count(): reporter = PyneStatSummaryReporter() it_block =",
"None) it_block = ItBlock(None, None, None) reporter = PyneStatSummaryReporter() reporter.report_enter_context(describe_block) reporter.report_enter_context(describe_block) reporter.report_success(it_block, 1000)",
"exception\"), 0) expect(reporter.stats.test_count).to_be(2) def test__report_failure__sets_overall_failure(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None)",
"reporter.report_pending(it_block) expect(reporter.stats.test_count).to_be(2) def test__report_enter_context__increases_depth(): reporter = PyneStatSummaryReporter() describe_block = DescribeBlock(None, None, None) reporter.report_enter_context(describe_block)",
"0 tests\") def test__reset__sets_stats_to_0(): describe_block = DescribeBlock(None, None, None) it_block = ItBlock(None, None,",
"from pynetest.lib.pyne_test_blocks import ItBlock, DescribeBlock from tests.test_helpers.fake_print import StubPrint, printed_text def test__report_failure__increases_the_failure_count(): reporter",
"reporter.report_success(it_block, 1000) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 1000) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 1000) reporter.reset()",
"0) reporter.report_success(it_block, 0) expect(reporter.stats.pass_count).to_be(2) def test__report_success__increases_the_total_timing(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None,",
"expect(reporter.stats.failure_count).to_be(2) def test__report_failure__increases_the_test_run_count(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_failure(it_block, it_block,",
"test__report_success__increases_the_test_run_count(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_success(it_block, 0) reporter.report_success(it_block, 0)",
"1000) reporter.report_success(it_block, 500) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"2 passed in 1.50 seconds\") def test__report_end_result__test_is_pending__reports_stats(): with",
"expect(printed_text[0]).to_contain(\"2 passed in 1.50 seconds\") def test__report_end_result__test_is_pending__reports_stats(): with StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter()) passing_it_block",
"None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 0) expect(reporter.stats.is_failure).to_be(True) def test__report_failure__increases_the_total_timing(): reporter = PyneStatSummaryReporter() it_block",
"None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 0) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 0) expect(reporter.stats.failure_count).to_be(2) def",
"test__report_end_result__when_no_tests_run__reports_stats(): with StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter()) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"Ran 0 tests\") def test__reset__sets_stats_to_0():",
"0) expect(reporter.stats.failure_count).to_be(2) def test__report_failure__increases_the_test_run_count(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_failure(it_block,",
"reporter.report_success(it_block, 0) reporter.report_success(it_block, 0) expect(reporter.stats.test_count).to_be(2) def test__report_success__increases_the_passes_count(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None,",
"reporter.report_enter_context(describe_block) expect(reporter.depth).to_be(1) reporter.report_enter_context(describe_block) expect(reporter.depth).to_be(2) def test__report_exit_context__decreases_depth(): reporter = PyneStatSummaryReporter() describe_block = DescribeBlock(None, None,",
"with StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter()) passing_it_block = ItBlock(None, None, None) pending_it_block = ItBlock(None,",
"ItBlock(None, None, None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 1000) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 20)",
"500) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"1 failed, 2 passed in 2.00 seconds\") def test__report_end_result__when_all_tests_passed__it_prints_stats(): with",
"reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_success(it_block, 0) reporter.report_success(it_block, 0) expect(reporter.stats.pass_count).to_be(2)",
"20) expect(reporter.stats.total_timing_millis).to_be(1020) def test__report_success__increases_the_test_run_count(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_success(it_block,",
"= PrintingReporter(PyneStatSummaryReporter()) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"Ran 0 tests\") def test__reset__sets_stats_to_0(): describe_block = DescribeBlock(None, None,",
"test__report_pending__increases_the_test_run_count(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_pending(it_block) reporter.report_pending(it_block) expect(reporter.stats.test_count).to_be(2) def",
"tests.test_helpers.fake_print import StubPrint, printed_text def test__report_failure__increases_the_failure_count(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None,",
"reporter.report_exit_context(describe_block) expect(reporter.depth).to_be(0) def test__report_end_result__when_a_test_has_failed__it_prints_stats(): with StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter()) it_block = ItBlock(None, None,",
"Exception(\"some exception\"), 0) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 0) expect(reporter.stats.failure_count).to_be(2) def test__report_failure__increases_the_test_run_count(): reporter =",
"expect(reporter.depth).to_be(0) def test__report_end_result__when_a_test_has_failed__it_prints_stats(): with StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter()) it_block = ItBlock(None, None, None)",
"passed in 1.50 seconds\") def test__report_end_result__test_is_pending__reports_stats(): with StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter()) passing_it_block =",
"= PrintingReporter(PyneStatSummaryReporter()) passing_it_block = ItBlock(None, None, None) pending_it_block = ItBlock(None, None, None, pending=True)",
"with StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter()) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"Ran 0 tests\") def test__reset__sets_stats_to_0(): describe_block",
"exception\"), 0) expect(reporter.stats.is_failure).to_be(True) def test__report_failure__increases_the_total_timing(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None)",
"None, None) it_block = ItBlock(None, None, None) reporter = PyneStatSummaryReporter() reporter.report_enter_context(describe_block) reporter.report_enter_context(describe_block) reporter.report_success(it_block,",
"printed_text def test__report_failure__increases_the_failure_count(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_failure(it_block, it_block,",
"None, None) reporter.report_success(it_block, 10) reporter.report_success(it_block, 300) expect(reporter.stats.total_timing_millis).to_be(310) def test__report_pending__increases_the_test_run_count(): reporter = PyneStatSummaryReporter() it_block",
"reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 20) expect(reporter.stats.total_timing_millis).to_be(1020) def test__report_success__increases_the_test_run_count(): reporter = PyneStatSummaryReporter() it_block =",
"reporter = PyneStatSummaryReporter() describe_block = DescribeBlock(None, None, None) reporter.report_enter_context(describe_block) expect(reporter.depth).to_be(1) reporter.report_enter_context(describe_block) expect(reporter.depth).to_be(2) def",
"test__report_end_result__test_is_pending__reports_stats(): with StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter()) passing_it_block = ItBlock(None, None, None) pending_it_block =",
"= PyneStatSummaryReporter() reporter.report_enter_context(describe_block) reporter.report_enter_context(describe_block) reporter.report_success(it_block, 1000) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 1000) reporter.report_failure(it_block, it_block,",
"ItBlock, DescribeBlock from tests.test_helpers.fake_print import StubPrint, printed_text def test__report_failure__increases_the_failure_count(): reporter = PyneStatSummaryReporter() it_block",
"import StubPrint, printed_text def test__report_failure__increases_the_failure_count(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None)",
"expect(reporter.stats.total_timing_millis).to_be(310) def test__report_pending__increases_the_test_run_count(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_pending(it_block) reporter.report_pending(it_block)",
"None, None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 0) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 0) expect(reporter.stats.failure_count).to_be(2)",
"it_block, Exception(\"some exception\"), 1000) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 1000) reporter.reset() expect(reporter.stats.pass_count).to_be(0) expect(reporter.stats.is_failure).to_be(False) expect(reporter.stats.total_timing_millis).to_be(0)",
"1000) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 20) expect(reporter.stats.total_timing_millis).to_be(1020) def test__report_success__increases_the_test_run_count(): reporter = PyneStatSummaryReporter() it_block",
"Exception(\"some exception\"), 1000) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 20) expect(reporter.stats.total_timing_millis).to_be(1020) def test__report_success__increases_the_test_run_count(): reporter =",
"test__report_failure__increases_the_total_timing(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"),",
"reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 1000) reporter.report_success(it_block, 500) reporter.report_success(it_block, 500) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"1 failed,",
"pynetest.lib.result_reporters.pyne_result_reporters import PyneStatSummaryReporter from pynetest.lib.pyne_test_blocks import ItBlock, DescribeBlock from tests.test_helpers.fake_print import StubPrint, printed_text",
"from pynetest.expectations import expect from pynetest.lib.result_reporters.printing_reporter import PrintingReporter from pynetest.lib.result_reporters.pyne_result_reporters import PyneStatSummaryReporter from",
"= PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_pending(it_block) reporter.report_pending(it_block) expect(reporter.stats.test_count).to_be(2) def test__report_enter_context__increases_depth(): reporter",
"passing_it_block = ItBlock(None, None, None) pending_it_block = ItBlock(None, None, None, pending=True) reporter.report_success(passing_it_block, 1000)",
"PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 0) reporter.report_failure(it_block, it_block,",
"seconds\") def test__report_end_result__test_is_pending__reports_stats(): with StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter()) passing_it_block = ItBlock(None, None, None)",
"0) reporter.report_success(it_block, 0) expect(reporter.stats.test_count).to_be(2) def test__report_success__increases_the_passes_count(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None,",
"it_block, Exception(\"some exception\"), 0) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 0) expect(reporter.stats.failure_count).to_be(2) def test__report_failure__increases_the_test_run_count(): reporter",
"None, None, pending=True) reporter.report_success(passing_it_block, 1000) reporter.report_pending(pending_it_block) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"1 passed, 1 pending in",
"def test__report_end_result__when_no_tests_run__reports_stats(): with StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter()) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"Ran 0 tests\") def",
"def test__report_success__increases_the_passes_count(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_success(it_block, 0) reporter.report_success(it_block,",
"None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 0) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 0) expect(reporter.stats.test_count).to_be(2) def",
"None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 1000) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 20) expect(reporter.stats.total_timing_millis).to_be(1020) def",
"1000) reporter.report_pending(pending_it_block) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"1 passed, 1 pending in 1.00 seconds\") def test__report_end_result__when_no_tests_run__reports_stats():",
"expect(printed_text[0]).to_contain(\"Ran 0 tests\") def test__reset__sets_stats_to_0(): describe_block = DescribeBlock(None, None, None) it_block = ItBlock(None,",
"1 pending in 1.00 seconds\") def test__report_end_result__when_no_tests_run__reports_stats(): with StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter()) printed_text.clear()",
"None) reporter.report_enter_context(describe_block) expect(reporter.depth).to_be(1) reporter.report_enter_context(describe_block) expect(reporter.depth).to_be(2) def test__report_exit_context__decreases_depth(): reporter = PyneStatSummaryReporter() describe_block = DescribeBlock(None,",
"DescribeBlock(None, None, None) it_block = ItBlock(None, None, None) reporter = PyneStatSummaryReporter() reporter.report_enter_context(describe_block) reporter.report_enter_context(describe_block)",
"1000) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 1000) reporter.reset() expect(reporter.stats.pass_count).to_be(0) expect(reporter.stats.is_failure).to_be(False) expect(reporter.stats.total_timing_millis).to_be(0) expect(reporter.stats.failure_count).to_be(0) expect(reporter.stats.test_count).to_be(0) expect(reporter.depth).to_be(0)",
"= ItBlock(None, None, None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 1000) reporter.report_success(it_block, 500) reporter.report_success(it_block, 500)",
"it_block = ItBlock(None, None, None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 0) reporter.report_failure(it_block, it_block, Exception(\"some",
"reporter.report_pending(pending_it_block) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"1 passed, 1 pending in 1.00 seconds\") def test__report_end_result__when_no_tests_run__reports_stats(): with",
"it_block, Exception(\"some exception\"), 20) expect(reporter.stats.total_timing_millis).to_be(1020) def test__report_success__increases_the_test_run_count(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None,",
"reporter = PrintingReporter(PyneStatSummaryReporter()) passing_it_block = ItBlock(None, None, None) pending_it_block = ItBlock(None, None, None,",
"it_block = ItBlock(None, None, None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 1000) reporter.report_failure(it_block, it_block, Exception(\"some",
"test__report_enter_context__increases_depth(): reporter = PyneStatSummaryReporter() describe_block = DescribeBlock(None, None, None) reporter.report_enter_context(describe_block) expect(reporter.depth).to_be(1) reporter.report_enter_context(describe_block) expect(reporter.depth).to_be(2)",
"def test__report_failure__increases_the_failure_count(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_failure(it_block, it_block, Exception(\"some",
"def test__report_failure__increases_the_total_timing(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_failure(it_block, it_block, Exception(\"some",
"PyneStatSummaryReporter from pynetest.lib.pyne_test_blocks import ItBlock, DescribeBlock from tests.test_helpers.fake_print import StubPrint, printed_text def test__report_failure__increases_the_failure_count():",
"test__report_end_result__when_all_tests_passed__it_prints_stats(): with StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter()) it_block = ItBlock(None, None, None) reporter.report_success(it_block, 1000)",
"= PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_success(it_block, 0) reporter.report_success(it_block, 0) expect(reporter.stats.test_count).to_be(2) def",
"exception\"), 1000) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 1000) reporter.reset() expect(reporter.stats.pass_count).to_be(0) expect(reporter.stats.is_failure).to_be(False) expect(reporter.stats.total_timing_millis).to_be(0) expect(reporter.stats.failure_count).to_be(0) expect(reporter.stats.test_count).to_be(0)",
"reporter.report_pending(it_block) reporter.report_pending(it_block) expect(reporter.stats.test_count).to_be(2) def test__report_enter_context__increases_depth(): reporter = PyneStatSummaryReporter() describe_block = DescribeBlock(None, None, None)",
"test__report_end_result__when_a_test_has_failed__it_prints_stats(): with StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter()) it_block = ItBlock(None, None, None) reporter.report_failure(it_block, it_block,",
"def test__report_success__increases_the_total_timing(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_success(it_block, 10) reporter.report_success(it_block,",
"reporter.report_enter_context(describe_block) reporter.report_success(it_block, 1000) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 1000) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 1000)",
"StubPrint, printed_text def test__report_failure__increases_the_failure_count(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_failure(it_block,",
"StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter()) it_block = ItBlock(None, None, None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"),",
"None, None) reporter.report_success(it_block, 0) reporter.report_success(it_block, 0) expect(reporter.stats.test_count).to_be(2) def test__report_success__increases_the_passes_count(): reporter = PyneStatSummaryReporter() it_block",
"expect from pynetest.lib.result_reporters.printing_reporter import PrintingReporter from pynetest.lib.result_reporters.pyne_result_reporters import PyneStatSummaryReporter from pynetest.lib.pyne_test_blocks import ItBlock,",
"PrintingReporter from pynetest.lib.result_reporters.pyne_result_reporters import PyneStatSummaryReporter from pynetest.lib.pyne_test_blocks import ItBlock, DescribeBlock from tests.test_helpers.fake_print import",
"import PrintingReporter from pynetest.lib.result_reporters.pyne_result_reporters import PyneStatSummaryReporter from pynetest.lib.pyne_test_blocks import ItBlock, DescribeBlock from tests.test_helpers.fake_print",
"expect(reporter.stats.test_count).to_be(2) def test__report_failure__sets_overall_failure(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_failure(it_block, it_block,",
"reporter = PrintingReporter(PyneStatSummaryReporter()) it_block = ItBlock(None, None, None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 1000)",
"printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"1 passed, 1 pending in 1.00 seconds\") def test__report_end_result__when_no_tests_run__reports_stats(): with StubPrint():",
"PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_success(it_block, 0) reporter.report_success(it_block, 0) expect(reporter.stats.pass_count).to_be(2) def test__report_success__increases_the_total_timing():",
"None) reporter.report_enter_context(describe_block) reporter.report_enter_context(describe_block) reporter.report_exit_context(describe_block) expect(reporter.depth).to_be(1) reporter.report_exit_context(describe_block) expect(reporter.depth).to_be(0) def test__report_end_result__when_a_test_has_failed__it_prints_stats(): with StubPrint(): reporter =",
"PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_success(it_block, 0) reporter.report_success(it_block, 0) expect(reporter.stats.test_count).to_be(2) def test__report_success__increases_the_passes_count():",
"= ItBlock(None, None, None) reporter.report_success(it_block, 1000) reporter.report_success(it_block, 500) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"2 passed in",
"import PyneStatSummaryReporter from pynetest.lib.pyne_test_blocks import ItBlock, DescribeBlock from tests.test_helpers.fake_print import StubPrint, printed_text def",
"pending in 1.00 seconds\") def test__report_end_result__when_no_tests_run__reports_stats(): with StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter()) printed_text.clear() reporter.report_end_result()",
"1000) reporter.report_success(it_block, 500) reporter.report_success(it_block, 500) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"1 failed, 2 passed in 2.00",
"reporter.report_exit_context(describe_block) expect(reporter.depth).to_be(1) reporter.report_exit_context(describe_block) expect(reporter.depth).to_be(0) def test__report_end_result__when_a_test_has_failed__it_prints_stats(): with StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter()) it_block =",
"ItBlock(None, None, None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 1000) reporter.report_success(it_block, 500) reporter.report_success(it_block, 500) printed_text.clear()",
"2.00 seconds\") def test__report_end_result__when_all_tests_passed__it_prints_stats(): with StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter()) it_block = ItBlock(None, None,",
"PrintingReporter(PyneStatSummaryReporter()) passing_it_block = ItBlock(None, None, None) pending_it_block = ItBlock(None, None, None, pending=True) reporter.report_success(passing_it_block,",
"reporter.report_success(passing_it_block, 1000) reporter.report_pending(pending_it_block) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"1 passed, 1 pending in 1.00 seconds\") def",
"it_block = ItBlock(None, None, None) reporter.report_pending(it_block) reporter.report_pending(it_block) expect(reporter.stats.test_count).to_be(2) def test__report_enter_context__increases_depth(): reporter = PyneStatSummaryReporter()",
"exception\"), 1000) reporter.report_success(it_block, 500) reporter.report_success(it_block, 500) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"1 failed, 2 passed in",
"= ItBlock(None, None, None) reporter.report_success(it_block, 0) reporter.report_success(it_block, 0) expect(reporter.stats.pass_count).to_be(2) def test__report_success__increases_the_total_timing(): reporter =",
"PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_pending(it_block) reporter.report_pending(it_block) expect(reporter.stats.test_count).to_be(2) def test__report_enter_context__increases_depth(): reporter =",
"expect(printed_text[0]).to_contain(\"1 passed, 1 pending in 1.00 seconds\") def test__report_end_result__when_no_tests_run__reports_stats(): with StubPrint(): reporter =",
"seconds\") def test__report_end_result__when_no_tests_run__reports_stats(): with StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter()) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"Ran 0 tests\")",
"ItBlock(None, None, None) reporter.report_success(it_block, 1000) reporter.report_success(it_block, 500) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"2 passed in 1.50",
"= ItBlock(None, None, None) pending_it_block = ItBlock(None, None, None, pending=True) reporter.report_success(passing_it_block, 1000) reporter.report_pending(pending_it_block)",
"ItBlock(None, None, None) reporter = PyneStatSummaryReporter() reporter.report_enter_context(describe_block) reporter.report_enter_context(describe_block) reporter.report_success(it_block, 1000) reporter.report_failure(it_block, it_block, Exception(\"some",
"Exception(\"some exception\"), 1000) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 1000) reporter.reset() expect(reporter.stats.pass_count).to_be(0) expect(reporter.stats.is_failure).to_be(False) expect(reporter.stats.total_timing_millis).to_be(0) expect(reporter.stats.failure_count).to_be(0)",
"it_block = ItBlock(None, None, None) reporter.report_success(it_block, 0) reporter.report_success(it_block, 0) expect(reporter.stats.pass_count).to_be(2) def test__report_success__increases_the_total_timing(): reporter",
"reporter.report_enter_context(describe_block) reporter.report_exit_context(describe_block) expect(reporter.depth).to_be(1) reporter.report_exit_context(describe_block) expect(reporter.depth).to_be(0) def test__report_end_result__when_a_test_has_failed__it_prints_stats(): with StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter()) it_block",
"reporter.report_success(it_block, 0) expect(reporter.stats.test_count).to_be(2) def test__report_success__increases_the_passes_count(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None)",
"ItBlock(None, None, None) pending_it_block = ItBlock(None, None, None, pending=True) reporter.report_success(passing_it_block, 1000) reporter.report_pending(pending_it_block) printed_text.clear()",
"describe_block = DescribeBlock(None, None, None) it_block = ItBlock(None, None, None) reporter = PyneStatSummaryReporter()",
"= PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 0) reporter.report_failure(it_block,",
"expect(reporter.stats.test_count).to_be(2) def test__report_success__increases_the_passes_count(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_success(it_block, 0)",
"reporter.report_end_result() expect(printed_text[0]).to_contain(\"2 passed in 1.50 seconds\") def test__report_end_result__test_is_pending__reports_stats(): with StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter())",
"0) expect(reporter.stats.is_failure).to_be(True) def test__report_failure__increases_the_total_timing(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_failure(it_block,",
"printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"1 failed, 2 passed in 2.00 seconds\") def test__report_end_result__when_all_tests_passed__it_prints_stats(): with StubPrint():",
"failed, 2 passed in 2.00 seconds\") def test__report_end_result__when_all_tests_passed__it_prints_stats(): with StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter())",
"it_block = ItBlock(None, None, None) reporter = PyneStatSummaryReporter() reporter.report_enter_context(describe_block) reporter.report_enter_context(describe_block) reporter.report_success(it_block, 1000) reporter.report_failure(it_block,",
"def test__report_failure__increases_the_test_run_count(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_failure(it_block, it_block, Exception(\"some",
"None, pending=True) reporter.report_success(passing_it_block, 1000) reporter.report_pending(pending_it_block) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"1 passed, 1 pending in 1.00",
"test__report_success__increases_the_passes_count(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_success(it_block, 0) reporter.report_success(it_block, 0)",
"it_block = ItBlock(None, None, None) reporter.report_success(it_block, 0) reporter.report_success(it_block, 0) expect(reporter.stats.test_count).to_be(2) def test__report_success__increases_the_passes_count(): reporter",
"= ItBlock(None, None, None, pending=True) reporter.report_success(passing_it_block, 1000) reporter.report_pending(pending_it_block) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"1 passed, 1",
"1000) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 1000) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 1000) reporter.reset() expect(reporter.stats.pass_count).to_be(0)",
"pending_it_block = ItBlock(None, None, None, pending=True) reporter.report_success(passing_it_block, 1000) reporter.report_pending(pending_it_block) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"1 passed,",
"from pynetest.lib.result_reporters.pyne_result_reporters import PyneStatSummaryReporter from pynetest.lib.pyne_test_blocks import ItBlock, DescribeBlock from tests.test_helpers.fake_print import StubPrint,",
"= DescribeBlock(None, None, None) reporter.report_enter_context(describe_block) expect(reporter.depth).to_be(1) reporter.report_enter_context(describe_block) expect(reporter.depth).to_be(2) def test__report_exit_context__decreases_depth(): reporter = PyneStatSummaryReporter()",
"reporter = PyneStatSummaryReporter() describe_block = DescribeBlock(None, None, None) reporter.report_enter_context(describe_block) reporter.report_enter_context(describe_block) reporter.report_exit_context(describe_block) expect(reporter.depth).to_be(1) reporter.report_exit_context(describe_block)",
"expect(reporter.stats.pass_count).to_be(2) def test__report_success__increases_the_total_timing(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_success(it_block, 10)",
"reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 1000) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 1000) reporter.reset() expect(reporter.stats.pass_count).to_be(0) expect(reporter.stats.is_failure).to_be(False)",
"0) expect(reporter.stats.test_count).to_be(2) def test__report_success__increases_the_passes_count(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_success(it_block,",
"PrintingReporter(PyneStatSummaryReporter()) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"Ran 0 tests\") def test__reset__sets_stats_to_0(): describe_block = DescribeBlock(None, None, None)",
"exception\"), 0) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 0) expect(reporter.stats.failure_count).to_be(2) def test__report_failure__increases_the_test_run_count(): reporter = PyneStatSummaryReporter()",
"import expect from pynetest.lib.result_reporters.printing_reporter import PrintingReporter from pynetest.lib.result_reporters.pyne_result_reporters import PyneStatSummaryReporter from pynetest.lib.pyne_test_blocks import",
"10) reporter.report_success(it_block, 300) expect(reporter.stats.total_timing_millis).to_be(310) def test__report_pending__increases_the_test_run_count(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None,",
"reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 1000)",
"Exception(\"some exception\"), 0) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 0) expect(reporter.stats.test_count).to_be(2) def test__report_failure__sets_overall_failure(): reporter =",
"def test__report_pending__increases_the_test_run_count(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_pending(it_block) reporter.report_pending(it_block) expect(reporter.stats.test_count).to_be(2)",
"it_block = ItBlock(None, None, None) reporter.report_success(it_block, 1000) reporter.report_success(it_block, 500) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"2 passed",
"it_block, Exception(\"some exception\"), 0) expect(reporter.stats.failure_count).to_be(2) def test__report_failure__increases_the_test_run_count(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None,",
"reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 0) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 0) expect(reporter.stats.test_count).to_be(2) def test__report_failure__sets_overall_failure():",
"expect(reporter.depth).to_be(2) def test__report_exit_context__decreases_depth(): reporter = PyneStatSummaryReporter() describe_block = DescribeBlock(None, None, None) reporter.report_enter_context(describe_block) reporter.report_enter_context(describe_block)",
"PyneStatSummaryReporter() describe_block = DescribeBlock(None, None, None) reporter.report_enter_context(describe_block) reporter.report_enter_context(describe_block) reporter.report_exit_context(describe_block) expect(reporter.depth).to_be(1) reporter.report_exit_context(describe_block) expect(reporter.depth).to_be(0) def",
"reporter.report_end_result() expect(printed_text[0]).to_contain(\"1 failed, 2 passed in 2.00 seconds\") def test__report_end_result__when_all_tests_passed__it_prints_stats(): with StubPrint(): reporter",
"ItBlock(None, None, None, pending=True) reporter.report_success(passing_it_block, 1000) reporter.report_pending(pending_it_block) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"1 passed, 1 pending",
"= DescribeBlock(None, None, None) reporter.report_enter_context(describe_block) reporter.report_enter_context(describe_block) reporter.report_exit_context(describe_block) expect(reporter.depth).to_be(1) reporter.report_exit_context(describe_block) expect(reporter.depth).to_be(0) def test__report_end_result__when_a_test_has_failed__it_prints_stats(): with",
"reporter.report_success(it_block, 500) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"2 passed in 1.50 seconds\") def test__report_end_result__test_is_pending__reports_stats(): with StubPrint():",
"test__report_failure__sets_overall_failure(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"),",
"None) reporter.report_success(it_block, 0) reporter.report_success(it_block, 0) expect(reporter.stats.pass_count).to_be(2) def test__report_success__increases_the_total_timing(): reporter = PyneStatSummaryReporter() it_block =",
"PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_success(it_block, 10) reporter.report_success(it_block, 300) expect(reporter.stats.total_timing_millis).to_be(310) def test__report_pending__increases_the_test_run_count():",
"500) reporter.report_success(it_block, 500) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"1 failed, 2 passed in 2.00 seconds\") def",
"None, None) reporter.report_enter_context(describe_block) expect(reporter.depth).to_be(1) reporter.report_enter_context(describe_block) expect(reporter.depth).to_be(2) def test__report_exit_context__decreases_depth(): reporter = PyneStatSummaryReporter() describe_block =",
"Exception(\"some exception\"), 1000) reporter.report_success(it_block, 500) reporter.report_success(it_block, 500) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"1 failed, 2 passed",
"1.50 seconds\") def test__report_end_result__test_is_pending__reports_stats(): with StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter()) passing_it_block = ItBlock(None, None,",
"it_block, Exception(\"some exception\"), 1000) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 20) expect(reporter.stats.total_timing_millis).to_be(1020) def test__report_success__increases_the_test_run_count(): reporter",
"import ItBlock, DescribeBlock from tests.test_helpers.fake_print import StubPrint, printed_text def test__report_failure__increases_the_failure_count(): reporter = PyneStatSummaryReporter()",
"0) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 0) expect(reporter.stats.failure_count).to_be(2) def test__report_failure__increases_the_test_run_count(): reporter = PyneStatSummaryReporter() it_block",
"describe_block = DescribeBlock(None, None, None) reporter.report_enter_context(describe_block) reporter.report_enter_context(describe_block) reporter.report_exit_context(describe_block) expect(reporter.depth).to_be(1) reporter.report_exit_context(describe_block) expect(reporter.depth).to_be(0) def test__report_end_result__when_a_test_has_failed__it_prints_stats():",
"expect(reporter.depth).to_be(1) reporter.report_exit_context(describe_block) expect(reporter.depth).to_be(0) def test__report_end_result__when_a_test_has_failed__it_prints_stats(): with StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter()) it_block = ItBlock(None,",
"expect(reporter.stats.is_failure).to_be(True) def test__report_failure__increases_the_total_timing(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_failure(it_block, it_block,",
"from tests.test_helpers.fake_print import StubPrint, printed_text def test__report_failure__increases_the_failure_count(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None,",
"300) expect(reporter.stats.total_timing_millis).to_be(310) def test__report_pending__increases_the_test_run_count(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_pending(it_block)",
"reporter.report_enter_context(describe_block) reporter.report_enter_context(describe_block) reporter.report_exit_context(describe_block) expect(reporter.depth).to_be(1) reporter.report_exit_context(describe_block) expect(reporter.depth).to_be(0) def test__report_end_result__when_a_test_has_failed__it_prints_stats(): with StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter())",
"it_block = ItBlock(None, None, None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 1000) reporter.report_success(it_block, 500) reporter.report_success(it_block,",
"in 1.50 seconds\") def test__report_end_result__test_is_pending__reports_stats(): with StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter()) passing_it_block = ItBlock(None,",
"passed in 2.00 seconds\") def test__report_end_result__when_all_tests_passed__it_prints_stats(): with StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter()) it_block =",
"500) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"2 passed in 1.50 seconds\") def test__report_end_result__test_is_pending__reports_stats(): with StubPrint(): reporter",
"reporter.report_success(it_block, 0) reporter.report_success(it_block, 0) expect(reporter.stats.pass_count).to_be(2) def test__report_success__increases_the_total_timing(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None,",
"reporter.report_enter_context(describe_block) expect(reporter.depth).to_be(2) def test__report_exit_context__decreases_depth(): reporter = PyneStatSummaryReporter() describe_block = DescribeBlock(None, None, None) reporter.report_enter_context(describe_block)",
"passed, 1 pending in 1.00 seconds\") def test__report_end_result__when_no_tests_run__reports_stats(): with StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter())",
"test__reset__sets_stats_to_0(): describe_block = DescribeBlock(None, None, None) it_block = ItBlock(None, None, None) reporter =",
"in 2.00 seconds\") def test__report_end_result__when_all_tests_passed__it_prints_stats(): with StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter()) it_block = ItBlock(None,",
"test__report_failure__increases_the_failure_count(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"),",
"None) reporter.report_success(it_block, 10) reporter.report_success(it_block, 300) expect(reporter.stats.total_timing_millis).to_be(310) def test__report_pending__increases_the_test_run_count(): reporter = PyneStatSummaryReporter() it_block =",
"test__report_failure__increases_the_test_run_count(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"),",
"PyneStatSummaryReporter() describe_block = DescribeBlock(None, None, None) reporter.report_enter_context(describe_block) expect(reporter.depth).to_be(1) reporter.report_enter_context(describe_block) expect(reporter.depth).to_be(2) def test__report_exit_context__decreases_depth(): reporter",
"DescribeBlock from tests.test_helpers.fake_print import StubPrint, printed_text def test__report_failure__increases_the_failure_count(): reporter = PyneStatSummaryReporter() it_block =",
"exception\"), 0) expect(reporter.stats.failure_count).to_be(2) def test__report_failure__increases_the_test_run_count(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None)",
"reporter = PrintingReporter(PyneStatSummaryReporter()) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"Ran 0 tests\") def test__reset__sets_stats_to_0(): describe_block = DescribeBlock(None,",
"reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 0)",
"reporter.report_success(it_block, 500) reporter.report_success(it_block, 500) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"1 failed, 2 passed in 2.00 seconds\")",
"= PrintingReporter(PyneStatSummaryReporter()) it_block = ItBlock(None, None, None) reporter.report_success(it_block, 1000) reporter.report_success(it_block, 500) printed_text.clear() reporter.report_end_result()",
"printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"Ran 0 tests\") def test__reset__sets_stats_to_0(): describe_block = DescribeBlock(None, None, None) it_block",
"0) expect(reporter.stats.test_count).to_be(2) def test__report_failure__sets_overall_failure(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_failure(it_block,",
"expect(reporter.stats.total_timing_millis).to_be(1020) def test__report_success__increases_the_test_run_count(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_success(it_block, 0)",
"def test__report_end_result__test_is_pending__reports_stats(): with StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter()) passing_it_block = ItBlock(None, None, None) pending_it_block",
"with StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter()) it_block = ItBlock(None, None, None) reporter.report_failure(it_block, it_block, Exception(\"some",
"= ItBlock(None, None, None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 1000) reporter.report_failure(it_block, it_block, Exception(\"some exception\"),",
"None, None) pending_it_block = ItBlock(None, None, None, pending=True) reporter.report_success(passing_it_block, 1000) reporter.report_pending(pending_it_block) printed_text.clear() reporter.report_end_result()",
"with StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter()) it_block = ItBlock(None, None, None) reporter.report_success(it_block, 1000) reporter.report_success(it_block,",
"PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 0) expect(reporter.stats.is_failure).to_be(True) def",
"reporter.report_success(it_block, 500) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"1 failed, 2 passed in 2.00 seconds\") def test__report_end_result__when_all_tests_passed__it_prints_stats():",
"seconds\") def test__report_end_result__when_all_tests_passed__it_prints_stats(): with StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter()) it_block = ItBlock(None, None, None)",
"= PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 1000) reporter.report_failure(it_block,",
"reporter.report_success(it_block, 300) expect(reporter.stats.total_timing_millis).to_be(310) def test__report_pending__increases_the_test_run_count(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None)",
"Exception(\"some exception\"), 0) expect(reporter.stats.failure_count).to_be(2) def test__report_failure__increases_the_test_run_count(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None,",
"0) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 0) expect(reporter.stats.test_count).to_be(2) def test__report_failure__sets_overall_failure(): reporter = PyneStatSummaryReporter() it_block",
"pynetest.lib.pyne_test_blocks import ItBlock, DescribeBlock from tests.test_helpers.fake_print import StubPrint, printed_text def test__report_failure__increases_the_failure_count(): reporter =",
"exception\"), 20) expect(reporter.stats.total_timing_millis).to_be(1020) def test__report_success__increases_the_test_run_count(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None)",
"def test__report_exit_context__decreases_depth(): reporter = PyneStatSummaryReporter() describe_block = DescribeBlock(None, None, None) reporter.report_enter_context(describe_block) reporter.report_enter_context(describe_block) reporter.report_exit_context(describe_block)",
"expect(printed_text[0]).to_contain(\"1 failed, 2 passed in 2.00 seconds\") def test__report_end_result__when_all_tests_passed__it_prints_stats(): with StubPrint(): reporter =",
"reporter = PrintingReporter(PyneStatSummaryReporter()) it_block = ItBlock(None, None, None) reporter.report_success(it_block, 1000) reporter.report_success(it_block, 500) printed_text.clear()",
"None) pending_it_block = ItBlock(None, None, None, pending=True) reporter.report_success(passing_it_block, 1000) reporter.report_pending(pending_it_block) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"1",
"ItBlock(None, None, None) reporter.report_success(it_block, 0) reporter.report_success(it_block, 0) expect(reporter.stats.test_count).to_be(2) def test__report_success__increases_the_passes_count(): reporter = PyneStatSummaryReporter()",
"reporter.report_success(it_block, 0) expect(reporter.stats.pass_count).to_be(2) def test__report_success__increases_the_total_timing(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None)",
"= PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 0) expect(reporter.stats.is_failure).to_be(True)",
"StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter()) passing_it_block = ItBlock(None, None, None) pending_it_block = ItBlock(None, None,",
"reporter = PyneStatSummaryReporter() reporter.report_enter_context(describe_block) reporter.report_enter_context(describe_block) reporter.report_success(it_block, 1000) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 1000) reporter.report_failure(it_block,",
"reporter.report_enter_context(describe_block) reporter.report_enter_context(describe_block) reporter.report_success(it_block, 1000) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 1000) reporter.report_failure(it_block, it_block, Exception(\"some exception\"),",
"= ItBlock(None, None, None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 0) reporter.report_failure(it_block, it_block, Exception(\"some exception\"),",
"it_block, Exception(\"some exception\"), 0) expect(reporter.stats.test_count).to_be(2) def test__report_failure__sets_overall_failure(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None,",
"pynetest.lib.result_reporters.printing_reporter import PrintingReporter from pynetest.lib.result_reporters.pyne_result_reporters import PyneStatSummaryReporter from pynetest.lib.pyne_test_blocks import ItBlock, DescribeBlock from",
"def test__report_failure__sets_overall_failure(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_failure(it_block, it_block, Exception(\"some",
"reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 1000) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 20) expect(reporter.stats.total_timing_millis).to_be(1020) def test__report_success__increases_the_test_run_count():",
"PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 1000) reporter.report_failure(it_block, it_block,",
"exception\"), 1000) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 20) expect(reporter.stats.total_timing_millis).to_be(1020) def test__report_success__increases_the_test_run_count(): reporter = PyneStatSummaryReporter()",
"reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_success(it_block, 0) reporter.report_success(it_block, 0) expect(reporter.stats.test_count).to_be(2)",
"= PyneStatSummaryReporter() it_block = ItBlock(None, None, None) reporter.report_success(it_block, 10) reporter.report_success(it_block, 300) expect(reporter.stats.total_timing_millis).to_be(310) def",
"None, None) reporter.report_pending(it_block) reporter.report_pending(it_block) expect(reporter.stats.test_count).to_be(2) def test__report_enter_context__increases_depth(): reporter = PyneStatSummaryReporter() describe_block = DescribeBlock(None,",
"describe_block = DescribeBlock(None, None, None) reporter.report_enter_context(describe_block) expect(reporter.depth).to_be(1) reporter.report_enter_context(describe_block) expect(reporter.depth).to_be(2) def test__report_exit_context__decreases_depth(): reporter =",
"DescribeBlock(None, None, None) reporter.report_enter_context(describe_block) reporter.report_enter_context(describe_block) reporter.report_exit_context(describe_block) expect(reporter.depth).to_be(1) reporter.report_exit_context(describe_block) expect(reporter.depth).to_be(0) def test__report_end_result__when_a_test_has_failed__it_prints_stats(): with StubPrint():",
"PrintingReporter(PyneStatSummaryReporter()) it_block = ItBlock(None, None, None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 1000) reporter.report_success(it_block, 500)",
"None) reporter.report_success(it_block, 1000) reporter.report_success(it_block, 500) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"2 passed in 1.50 seconds\") def",
"None, None) reporter.report_success(it_block, 0) reporter.report_success(it_block, 0) expect(reporter.stats.pass_count).to_be(2) def test__report_success__increases_the_total_timing(): reporter = PyneStatSummaryReporter() it_block",
"reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 0) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 0) expect(reporter.stats.failure_count).to_be(2) def test__report_failure__increases_the_test_run_count():",
"PyneStatSummaryReporter() reporter.report_enter_context(describe_block) reporter.report_enter_context(describe_block) reporter.report_success(it_block, 1000) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 1000) reporter.report_failure(it_block, it_block, Exception(\"some",
"PrintingReporter(PyneStatSummaryReporter()) it_block = ItBlock(None, None, None) reporter.report_success(it_block, 1000) reporter.report_success(it_block, 500) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"2",
"Exception(\"some exception\"), 20) expect(reporter.stats.total_timing_millis).to_be(1020) def test__report_success__increases_the_test_run_count(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None,",
"= DescribeBlock(None, None, None) it_block = ItBlock(None, None, None) reporter = PyneStatSummaryReporter() reporter.report_enter_context(describe_block)",
"ItBlock(None, None, None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 0) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 0)",
"Exception(\"some exception\"), 0) expect(reporter.stats.is_failure).to_be(True) def test__report_failure__increases_the_total_timing(): reporter = PyneStatSummaryReporter() it_block = ItBlock(None, None,",
"it_block = ItBlock(None, None, None) reporter.report_success(it_block, 10) reporter.report_success(it_block, 300) expect(reporter.stats.total_timing_millis).to_be(310) def test__report_pending__increases_the_test_run_count(): reporter",
"1.00 seconds\") def test__report_end_result__when_no_tests_run__reports_stats(): with StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter()) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"Ran 0",
"None) reporter.report_success(it_block, 0) reporter.report_success(it_block, 0) expect(reporter.stats.test_count).to_be(2) def test__report_success__increases_the_passes_count(): reporter = PyneStatSummaryReporter() it_block =",
"= PrintingReporter(PyneStatSummaryReporter()) it_block = ItBlock(None, None, None) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 1000) reporter.report_success(it_block,",
"it_block, Exception(\"some exception\"), 0) reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 0) expect(reporter.stats.test_count).to_be(2) def test__report_failure__sets_overall_failure(): reporter",
"2 passed in 2.00 seconds\") def test__report_end_result__when_all_tests_passed__it_prints_stats(): with StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter()) it_block",
"expect(reporter.depth).to_be(1) reporter.report_enter_context(describe_block) expect(reporter.depth).to_be(2) def test__report_exit_context__decreases_depth(): reporter = PyneStatSummaryReporter() describe_block = DescribeBlock(None, None, None)",
"reporter.report_failure(it_block, it_block, Exception(\"some exception\"), 0) expect(reporter.stats.test_count).to_be(2) def test__report_failure__sets_overall_failure(): reporter = PyneStatSummaryReporter() it_block =",
"reporter.report_success(it_block, 1000) reporter.report_success(it_block, 500) printed_text.clear() reporter.report_end_result() expect(printed_text[0]).to_contain(\"2 passed in 1.50 seconds\") def test__report_end_result__test_is_pending__reports_stats():",
"def test__report_end_result__when_a_test_has_failed__it_prints_stats(): with StubPrint(): reporter = PrintingReporter(PyneStatSummaryReporter()) it_block = ItBlock(None, None, None) reporter.report_failure(it_block,",
"tests\") def test__reset__sets_stats_to_0(): describe_block = DescribeBlock(None, None, None) it_block = ItBlock(None, None, None)"
] |
[
"import ray.train as train import zipfile from raypipe import logger from raypipe.core.distribution import",
"raypipe.core.rpipe.utils import zip_dir class TrainReportCallback(Callback): def on_epoch_end(self, epoch:int, logs=None): train.report(**logs) class DistModelSaveCallBack(ModelCheckpoint): def",
"import zip_dir class TrainReportCallback(Callback): def on_epoch_end(self, epoch:int, logs=None): train.report(**logs) class DistModelSaveCallBack(ModelCheckpoint): def __init__(self,save_freq:int,verbose:int):",
"zip_dir(file_path,file_path+\".zip\") with open(file_path+\".zip\",\"rb\") as f: object_store_impl.upload(object_path,f.read()) def on_train_batch_end(self, batch, logs=None): if self._should_save_on_batch(batch): self._save_model(epoch=self._current_epoch,",
"<reponame>billyyann/RayPipe<filename>raypipe/core/rpipe/callback.py import os from tensorflow.python.keras.callbacks import Callback, ModelCheckpoint import ray.train as train import",
"raypipe.core.distribution import object_store_impl from raypipe.core.distribution.object_store import ObjectPath from raypipe.core.rpipe.utils import zip_dir class TrainReportCallback(Callback):",
"object_store_impl from raypipe.core.distribution.object_store import ObjectPath from raypipe.core.rpipe.utils import zip_dir class TrainReportCallback(Callback): def on_epoch_end(self,",
"save_freq=save_freq, verbose=verbose ) @staticmethod def _upload(file_path): path_segments=file_path.split(\"/\") object_path=ObjectPath() object_path.create(\"/\".join(path_segments[:-1]),path_segments[-1]) logger.info(\"=========== Object Path %s",
"class TrainReportCallback(Callback): def on_epoch_end(self, epoch:int, logs=None): train.report(**logs) class DistModelSaveCallBack(ModelCheckpoint): def __init__(self,save_freq:int,verbose:int): self.FILE_PATH_template=\"/tmp/training/cp-{epoch:04d}.ckpt\" super(DistModelSaveCallBack,",
"tensorflow.python.keras.callbacks import Callback, ModelCheckpoint import ray.train as train import zipfile from raypipe import",
"class DistModelSaveCallBack(ModelCheckpoint): def __init__(self,save_freq:int,verbose:int): self.FILE_PATH_template=\"/tmp/training/cp-{epoch:04d}.ckpt\" super(DistModelSaveCallBack, self).__init__( filepath=self.FILE_PATH_template, save_freq=save_freq, verbose=verbose ) @staticmethod def",
"self).__init__( filepath=self.FILE_PATH_template, save_freq=save_freq, verbose=verbose ) @staticmethod def _upload(file_path): path_segments=file_path.split(\"/\") object_path=ObjectPath() object_path.create(\"/\".join(path_segments[:-1]),path_segments[-1]) logger.info(\"=========== Object",
"def on_train_batch_end(self, batch, logs=None): if self._should_save_on_batch(batch): self._save_model(epoch=self._current_epoch, logs=logs) file_path = self._get_file_path(self._current_epoch, logs) #todo",
"%s =========== \"%object_path.get_path()) zip_dir(file_path,file_path+\".zip\") with open(file_path+\".zip\",\"rb\") as f: object_store_impl.upload(object_path,f.read()) def on_train_batch_end(self, batch, logs=None):",
"object_path=ObjectPath() object_path.create(\"/\".join(path_segments[:-1]),path_segments[-1]) logger.info(\"=========== Object Path %s =========== \"%object_path.get_path()) zip_dir(file_path,file_path+\".zip\") with open(file_path+\".zip\",\"rb\") as f:",
"import Callback, ModelCheckpoint import ray.train as train import zipfile from raypipe import logger",
"self.FILE_PATH_template=\"/tmp/training/cp-{epoch:04d}.ckpt\" super(DistModelSaveCallBack, self).__init__( filepath=self.FILE_PATH_template, save_freq=save_freq, verbose=verbose ) @staticmethod def _upload(file_path): path_segments=file_path.split(\"/\") object_path=ObjectPath() object_path.create(\"/\".join(path_segments[:-1]),path_segments[-1])",
"def on_epoch_end(self, epoch:int, logs=None): train.report(**logs) class DistModelSaveCallBack(ModelCheckpoint): def __init__(self,save_freq:int,verbose:int): self.FILE_PATH_template=\"/tmp/training/cp-{epoch:04d}.ckpt\" super(DistModelSaveCallBack, self).__init__( filepath=self.FILE_PATH_template,",
"import zipfile from raypipe import logger from raypipe.core.distribution import object_store_impl from raypipe.core.distribution.object_store import",
"Callback, ModelCheckpoint import ray.train as train import zipfile from raypipe import logger from",
"from raypipe.core.distribution.object_store import ObjectPath from raypipe.core.rpipe.utils import zip_dir class TrainReportCallback(Callback): def on_epoch_end(self, epoch:int,",
"DistModelSaveCallBack(ModelCheckpoint): def __init__(self,save_freq:int,verbose:int): self.FILE_PATH_template=\"/tmp/training/cp-{epoch:04d}.ckpt\" super(DistModelSaveCallBack, self).__init__( filepath=self.FILE_PATH_template, save_freq=save_freq, verbose=verbose ) @staticmethod def _upload(file_path):",
"def _upload(file_path): path_segments=file_path.split(\"/\") object_path=ObjectPath() object_path.create(\"/\".join(path_segments[:-1]),path_segments[-1]) logger.info(\"=========== Object Path %s =========== \"%object_path.get_path()) zip_dir(file_path,file_path+\".zip\") with",
"logger from raypipe.core.distribution import object_store_impl from raypipe.core.distribution.object_store import ObjectPath from raypipe.core.rpipe.utils import zip_dir",
"with open(file_path+\".zip\",\"rb\") as f: object_store_impl.upload(object_path,f.read()) def on_train_batch_end(self, batch, logs=None): if self._should_save_on_batch(batch): self._save_model(epoch=self._current_epoch, logs=logs)",
"\"%object_path.get_path()) zip_dir(file_path,file_path+\".zip\") with open(file_path+\".zip\",\"rb\") as f: object_store_impl.upload(object_path,f.read()) def on_train_batch_end(self, batch, logs=None): if self._should_save_on_batch(batch):",
"def __init__(self,save_freq:int,verbose:int): self.FILE_PATH_template=\"/tmp/training/cp-{epoch:04d}.ckpt\" super(DistModelSaveCallBack, self).__init__( filepath=self.FILE_PATH_template, save_freq=save_freq, verbose=verbose ) @staticmethod def _upload(file_path): path_segments=file_path.split(\"/\")",
"import os from tensorflow.python.keras.callbacks import Callback, ModelCheckpoint import ray.train as train import zipfile",
"ObjectPath from raypipe.core.rpipe.utils import zip_dir class TrainReportCallback(Callback): def on_epoch_end(self, epoch:int, logs=None): train.report(**logs) class",
"from raypipe.core.rpipe.utils import zip_dir class TrainReportCallback(Callback): def on_epoch_end(self, epoch:int, logs=None): train.report(**logs) class DistModelSaveCallBack(ModelCheckpoint):",
"__init__(self,save_freq:int,verbose:int): self.FILE_PATH_template=\"/tmp/training/cp-{epoch:04d}.ckpt\" super(DistModelSaveCallBack, self).__init__( filepath=self.FILE_PATH_template, save_freq=save_freq, verbose=verbose ) @staticmethod def _upload(file_path): path_segments=file_path.split(\"/\") object_path=ObjectPath()",
"zipfile from raypipe import logger from raypipe.core.distribution import object_store_impl from raypipe.core.distribution.object_store import ObjectPath",
"as f: object_store_impl.upload(object_path,f.read()) def on_train_batch_end(self, batch, logs=None): if self._should_save_on_batch(batch): self._save_model(epoch=self._current_epoch, logs=logs) file_path =",
"Object Path %s =========== \"%object_path.get_path()) zip_dir(file_path,file_path+\".zip\") with open(file_path+\".zip\",\"rb\") as f: object_store_impl.upload(object_path,f.read()) def on_train_batch_end(self,",
"logs=None): train.report(**logs) class DistModelSaveCallBack(ModelCheckpoint): def __init__(self,save_freq:int,verbose:int): self.FILE_PATH_template=\"/tmp/training/cp-{epoch:04d}.ckpt\" super(DistModelSaveCallBack, self).__init__( filepath=self.FILE_PATH_template, save_freq=save_freq, verbose=verbose )",
") @staticmethod def _upload(file_path): path_segments=file_path.split(\"/\") object_path=ObjectPath() object_path.create(\"/\".join(path_segments[:-1]),path_segments[-1]) logger.info(\"=========== Object Path %s =========== \"%object_path.get_path())",
"ray.train as train import zipfile from raypipe import logger from raypipe.core.distribution import object_store_impl",
"import ObjectPath from raypipe.core.rpipe.utils import zip_dir class TrainReportCallback(Callback): def on_epoch_end(self, epoch:int, logs=None): train.report(**logs)",
"logger.info(\"=========== Object Path %s =========== \"%object_path.get_path()) zip_dir(file_path,file_path+\".zip\") with open(file_path+\".zip\",\"rb\") as f: object_store_impl.upload(object_path,f.read()) def",
"ModelCheckpoint import ray.train as train import zipfile from raypipe import logger from raypipe.core.distribution",
"f: object_store_impl.upload(object_path,f.read()) def on_train_batch_end(self, batch, logs=None): if self._should_save_on_batch(batch): self._save_model(epoch=self._current_epoch, logs=logs) file_path = self._get_file_path(self._current_epoch,",
"from tensorflow.python.keras.callbacks import Callback, ModelCheckpoint import ray.train as train import zipfile from raypipe",
"import object_store_impl from raypipe.core.distribution.object_store import ObjectPath from raypipe.core.rpipe.utils import zip_dir class TrainReportCallback(Callback): def",
"train import zipfile from raypipe import logger from raypipe.core.distribution import object_store_impl from raypipe.core.distribution.object_store",
"_upload(file_path): path_segments=file_path.split(\"/\") object_path=ObjectPath() object_path.create(\"/\".join(path_segments[:-1]),path_segments[-1]) logger.info(\"=========== Object Path %s =========== \"%object_path.get_path()) zip_dir(file_path,file_path+\".zip\") with open(file_path+\".zip\",\"rb\")",
"as train import zipfile from raypipe import logger from raypipe.core.distribution import object_store_impl from",
"os from tensorflow.python.keras.callbacks import Callback, ModelCheckpoint import ray.train as train import zipfile from",
"verbose=verbose ) @staticmethod def _upload(file_path): path_segments=file_path.split(\"/\") object_path=ObjectPath() object_path.create(\"/\".join(path_segments[:-1]),path_segments[-1]) logger.info(\"=========== Object Path %s ===========",
"object_path.create(\"/\".join(path_segments[:-1]),path_segments[-1]) logger.info(\"=========== Object Path %s =========== \"%object_path.get_path()) zip_dir(file_path,file_path+\".zip\") with open(file_path+\".zip\",\"rb\") as f: object_store_impl.upload(object_path,f.read())",
"open(file_path+\".zip\",\"rb\") as f: object_store_impl.upload(object_path,f.read()) def on_train_batch_end(self, batch, logs=None): if self._should_save_on_batch(batch): self._save_model(epoch=self._current_epoch, logs=logs) file_path",
"on_train_batch_end(self, batch, logs=None): if self._should_save_on_batch(batch): self._save_model(epoch=self._current_epoch, logs=logs) file_path = self._get_file_path(self._current_epoch, logs) #todo distributed",
"object_store_impl.upload(object_path,f.read()) def on_train_batch_end(self, batch, logs=None): if self._should_save_on_batch(batch): self._save_model(epoch=self._current_epoch, logs=logs) file_path = self._get_file_path(self._current_epoch, logs)",
"on_epoch_end(self, epoch:int, logs=None): train.report(**logs) class DistModelSaveCallBack(ModelCheckpoint): def __init__(self,save_freq:int,verbose:int): self.FILE_PATH_template=\"/tmp/training/cp-{epoch:04d}.ckpt\" super(DistModelSaveCallBack, self).__init__( filepath=self.FILE_PATH_template, save_freq=save_freq,",
"batch, logs=None): if self._should_save_on_batch(batch): self._save_model(epoch=self._current_epoch, logs=logs) file_path = self._get_file_path(self._current_epoch, logs) #todo distributed saving",
"super(DistModelSaveCallBack, self).__init__( filepath=self.FILE_PATH_template, save_freq=save_freq, verbose=verbose ) @staticmethod def _upload(file_path): path_segments=file_path.split(\"/\") object_path=ObjectPath() object_path.create(\"/\".join(path_segments[:-1]),path_segments[-1]) logger.info(\"===========",
"from raypipe.core.distribution import object_store_impl from raypipe.core.distribution.object_store import ObjectPath from raypipe.core.rpipe.utils import zip_dir class",
"zip_dir class TrainReportCallback(Callback): def on_epoch_end(self, epoch:int, logs=None): train.report(**logs) class DistModelSaveCallBack(ModelCheckpoint): def __init__(self,save_freq:int,verbose:int): self.FILE_PATH_template=\"/tmp/training/cp-{epoch:04d}.ckpt\"",
"@staticmethod def _upload(file_path): path_segments=file_path.split(\"/\") object_path=ObjectPath() object_path.create(\"/\".join(path_segments[:-1]),path_segments[-1]) logger.info(\"=========== Object Path %s =========== \"%object_path.get_path()) zip_dir(file_path,file_path+\".zip\")",
"logs=None): if self._should_save_on_batch(batch): self._save_model(epoch=self._current_epoch, logs=logs) file_path = self._get_file_path(self._current_epoch, logs) #todo distributed saving self._upload(file_path)",
"=========== \"%object_path.get_path()) zip_dir(file_path,file_path+\".zip\") with open(file_path+\".zip\",\"rb\") as f: object_store_impl.upload(object_path,f.read()) def on_train_batch_end(self, batch, logs=None): if",
"epoch:int, logs=None): train.report(**logs) class DistModelSaveCallBack(ModelCheckpoint): def __init__(self,save_freq:int,verbose:int): self.FILE_PATH_template=\"/tmp/training/cp-{epoch:04d}.ckpt\" super(DistModelSaveCallBack, self).__init__( filepath=self.FILE_PATH_template, save_freq=save_freq, verbose=verbose",
"path_segments=file_path.split(\"/\") object_path=ObjectPath() object_path.create(\"/\".join(path_segments[:-1]),path_segments[-1]) logger.info(\"=========== Object Path %s =========== \"%object_path.get_path()) zip_dir(file_path,file_path+\".zip\") with open(file_path+\".zip\",\"rb\") as",
"from raypipe import logger from raypipe.core.distribution import object_store_impl from raypipe.core.distribution.object_store import ObjectPath from",
"TrainReportCallback(Callback): def on_epoch_end(self, epoch:int, logs=None): train.report(**logs) class DistModelSaveCallBack(ModelCheckpoint): def __init__(self,save_freq:int,verbose:int): self.FILE_PATH_template=\"/tmp/training/cp-{epoch:04d}.ckpt\" super(DistModelSaveCallBack, self).__init__(",
"import logger from raypipe.core.distribution import object_store_impl from raypipe.core.distribution.object_store import ObjectPath from raypipe.core.rpipe.utils import",
"filepath=self.FILE_PATH_template, save_freq=save_freq, verbose=verbose ) @staticmethod def _upload(file_path): path_segments=file_path.split(\"/\") object_path=ObjectPath() object_path.create(\"/\".join(path_segments[:-1]),path_segments[-1]) logger.info(\"=========== Object Path",
"raypipe.core.distribution.object_store import ObjectPath from raypipe.core.rpipe.utils import zip_dir class TrainReportCallback(Callback): def on_epoch_end(self, epoch:int, logs=None):",
"train.report(**logs) class DistModelSaveCallBack(ModelCheckpoint): def __init__(self,save_freq:int,verbose:int): self.FILE_PATH_template=\"/tmp/training/cp-{epoch:04d}.ckpt\" super(DistModelSaveCallBack, self).__init__( filepath=self.FILE_PATH_template, save_freq=save_freq, verbose=verbose ) @staticmethod",
"Path %s =========== \"%object_path.get_path()) zip_dir(file_path,file_path+\".zip\") with open(file_path+\".zip\",\"rb\") as f: object_store_impl.upload(object_path,f.read()) def on_train_batch_end(self, batch,",
"raypipe import logger from raypipe.core.distribution import object_store_impl from raypipe.core.distribution.object_store import ObjectPath from raypipe.core.rpipe.utils"
] |
[
"delay function (proof of time) developed by Chia\" + \"Networks.\", classifiers=[ 'Development Status",
"Alpha', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6',",
"Python :: 3.6', 'Programming Language :: Python :: 3.7', 'License :: OSI Approved",
"Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python",
"\"inkfish\", ], author=\"<NAME>, Inc.\", entry_points={ 'console_scripts': [ 'pot = inkfish.cmds:pot', ] }, author_email=\"<EMAIL>\",",
"Inc.\", entry_points={ 'console_scripts': [ 'pot = inkfish.cmds:pot', ] }, author_email=\"<EMAIL>\", url=\"https://github.com/Chia-Network\", license=\"https://opensource.org/licenses/Apache-2.0\", description=\"Verifiable",
":: OSI Approved :: Apache Software License', 'Topic :: Security :: Cryptography', ],)",
"Chia\" + \"Networks.\", classifiers=[ 'Development Status :: 3 - Alpha', 'Programming Language ::",
":: Python :: 3.7', 'License :: OSI Approved :: Apache Software License', 'Topic",
"function (proof of time) developed by Chia\" + \"Networks.\", classifiers=[ 'Development Status ::",
"], author=\"<NAME>, Inc.\", entry_points={ 'console_scripts': [ 'pot = inkfish.cmds:pot', ] }, author_email=\"<EMAIL>\", url=\"https://github.com/Chia-Network\",",
"[ 'pot = inkfish.cmds:pot', ] }, author_email=\"<EMAIL>\", url=\"https://github.com/Chia-Network\", license=\"https://opensource.org/licenses/Apache-2.0\", description=\"Verifiable delay function (proof",
"developed by Chia\" + \"Networks.\", classifiers=[ 'Development Status :: 3 - Alpha', 'Programming",
"'console_scripts': [ 'pot = inkfish.cmds:pot', ] }, author_email=\"<EMAIL>\", url=\"https://github.com/Chia-Network\", license=\"https://opensource.org/licenses/Apache-2.0\", description=\"Verifiable delay function",
"classifiers=[ 'Development Status :: 3 - Alpha', 'Programming Language :: Python :: 3',",
"= inkfish.cmds:pot', ] }, author_email=\"<EMAIL>\", url=\"https://github.com/Chia-Network\", license=\"https://opensource.org/licenses/Apache-2.0\", description=\"Verifiable delay function (proof of time)",
"Status :: 3 - Alpha', 'Programming Language :: Python :: 3', 'Programming Language",
":: 3.6', 'Programming Language :: Python :: 3.7', 'License :: OSI Approved ::",
"3.6', 'Programming Language :: Python :: 3.7', 'License :: OSI Approved :: Apache",
"'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming",
"author=\"<NAME>, Inc.\", entry_points={ 'console_scripts': [ 'pot = inkfish.cmds:pot', ] }, author_email=\"<EMAIL>\", url=\"https://github.com/Chia-Network\", license=\"https://opensource.org/licenses/Apache-2.0\",",
"setuptools import setup from inkfish.version import version setup( name=\"inkfish\", version=version, packages=[ \"inkfish\", ],",
"import setup from inkfish.version import version setup( name=\"inkfish\", version=version, packages=[ \"inkfish\", ], author=\"<NAME>,",
"'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'License",
"'License :: OSI Approved :: Apache Software License', 'Topic :: Security :: Cryptography',",
"<filename>setup.py #!/usr/bin/env python from setuptools import setup from inkfish.version import version setup( name=\"inkfish\",",
"version=version, packages=[ \"inkfish\", ], author=\"<NAME>, Inc.\", entry_points={ 'console_scripts': [ 'pot = inkfish.cmds:pot', ]",
"3 - Alpha', 'Programming Language :: Python :: 3', 'Programming Language :: Python",
"'Development Status :: 3 - Alpha', 'Programming Language :: Python :: 3', 'Programming",
"packages=[ \"inkfish\", ], author=\"<NAME>, Inc.\", entry_points={ 'console_scripts': [ 'pot = inkfish.cmds:pot', ] },",
"Python :: 3.7', 'License :: OSI Approved :: Apache Software License', 'Topic ::",
"from inkfish.version import version setup( name=\"inkfish\", version=version, packages=[ \"inkfish\", ], author=\"<NAME>, Inc.\", entry_points={",
"- Alpha', 'Programming Language :: Python :: 3', 'Programming Language :: Python ::",
"inkfish.version import version setup( name=\"inkfish\", version=version, packages=[ \"inkfish\", ], author=\"<NAME>, Inc.\", entry_points={ 'console_scripts':",
"author_email=\"<EMAIL>\", url=\"https://github.com/Chia-Network\", license=\"https://opensource.org/licenses/Apache-2.0\", description=\"Verifiable delay function (proof of time) developed by Chia\" +",
"Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language",
":: 3.7', 'License :: OSI Approved :: Apache Software License', 'Topic :: Security",
"3.7', 'License :: OSI Approved :: Apache Software License', 'Topic :: Security ::",
"(proof of time) developed by Chia\" + \"Networks.\", classifiers=[ 'Development Status :: 3",
"] }, author_email=\"<EMAIL>\", url=\"https://github.com/Chia-Network\", license=\"https://opensource.org/licenses/Apache-2.0\", description=\"Verifiable delay function (proof of time) developed by",
"license=\"https://opensource.org/licenses/Apache-2.0\", description=\"Verifiable delay function (proof of time) developed by Chia\" + \"Networks.\", classifiers=[",
":: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'License :: OSI",
"version setup( name=\"inkfish\", version=version, packages=[ \"inkfish\", ], author=\"<NAME>, Inc.\", entry_points={ 'console_scripts': [ 'pot",
"setup from inkfish.version import version setup( name=\"inkfish\", version=version, packages=[ \"inkfish\", ], author=\"<NAME>, Inc.\",",
"description=\"Verifiable delay function (proof of time) developed by Chia\" + \"Networks.\", classifiers=[ 'Development",
"'Programming Language :: Python :: 3.7', 'License :: OSI Approved :: Apache Software",
"of time) developed by Chia\" + \"Networks.\", classifiers=[ 'Development Status :: 3 -",
"url=\"https://github.com/Chia-Network\", license=\"https://opensource.org/licenses/Apache-2.0\", description=\"Verifiable delay function (proof of time) developed by Chia\" + \"Networks.\",",
"Language :: Python :: 3.7', 'License :: OSI Approved :: Apache Software License',",
"}, author_email=\"<EMAIL>\", url=\"https://github.com/Chia-Network\", license=\"https://opensource.org/licenses/Apache-2.0\", description=\"Verifiable delay function (proof of time) developed by Chia\"",
"'pot = inkfish.cmds:pot', ] }, author_email=\"<EMAIL>\", url=\"https://github.com/Chia-Network\", license=\"https://opensource.org/licenses/Apache-2.0\", description=\"Verifiable delay function (proof of",
"time) developed by Chia\" + \"Networks.\", classifiers=[ 'Development Status :: 3 - Alpha',",
"Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'License ::",
"by Chia\" + \"Networks.\", classifiers=[ 'Development Status :: 3 - Alpha', 'Programming Language",
"\"Networks.\", classifiers=[ 'Development Status :: 3 - Alpha', 'Programming Language :: Python ::",
"setup( name=\"inkfish\", version=version, packages=[ \"inkfish\", ], author=\"<NAME>, Inc.\", entry_points={ 'console_scripts': [ 'pot =",
"python from setuptools import setup from inkfish.version import version setup( name=\"inkfish\", version=version, packages=[",
"from setuptools import setup from inkfish.version import version setup( name=\"inkfish\", version=version, packages=[ \"inkfish\",",
"name=\"inkfish\", version=version, packages=[ \"inkfish\", ], author=\"<NAME>, Inc.\", entry_points={ 'console_scripts': [ 'pot = inkfish.cmds:pot',",
":: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python ::",
"inkfish.cmds:pot', ] }, author_email=\"<EMAIL>\", url=\"https://github.com/Chia-Network\", license=\"https://opensource.org/licenses/Apache-2.0\", description=\"Verifiable delay function (proof of time) developed",
":: 3 - Alpha', 'Programming Language :: Python :: 3', 'Programming Language ::",
"#!/usr/bin/env python from setuptools import setup from inkfish.version import version setup( name=\"inkfish\", version=version,",
"import version setup( name=\"inkfish\", version=version, packages=[ \"inkfish\", ], author=\"<NAME>, Inc.\", entry_points={ 'console_scripts': [",
":: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language ::",
"+ \"Networks.\", classifiers=[ 'Development Status :: 3 - Alpha', 'Programming Language :: Python",
"entry_points={ 'console_scripts': [ 'pot = inkfish.cmds:pot', ] }, author_email=\"<EMAIL>\", url=\"https://github.com/Chia-Network\", license=\"https://opensource.org/licenses/Apache-2.0\", description=\"Verifiable delay",
"3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7',"
] |
[
"\"--convert\", '[{\"id\": 1, \"text\": content.decode(\"utf-8\")}]', \"--id\", \"id\", ] + options, catch_exceptions=False, ) assert",
"\"Tonic 2\"}, # This line has changed from \"Rum\" to \"Rum Pony\": {\"product_id\":",
"\"-m\", \"main\"], cwd=str(repo_dir)) (repo_dir / \"items.json\").write_text( json.dumps( [ { \"product_id\": 1, \"name\": \"Gin\",",
"\"Rum\"}, ], ), ), ) def test_convert(repo, tmpdir, convert, expected_rows): runner = CliRunner()",
"namespace] if namespace else []), ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path)",
"\"--repo\", str(repo)] if namespace: options += [\"--namespace\", namespace] result = runner.invoke(cli, options) assert",
"{\"product_id\": 3, \"_version\": 1, \"name\": \"Rum\"}, ] # Now we edit, commit and",
"runner.invoke( cli, [ \"file\", db_path, str(repo / \"items.xml\"), \"--repo\", str(repo), \"--convert\", textwrap.dedent( \"\"\"",
"([\"--namespace\", namespace] if namespace else []), ) namespace = namespace or \"item\" assert",
"[hash]); CREATE TABLE [item] ( [_id] INTEGER PRIMARY KEY, [_item_id] TEXT , [_id_]",
"assert result.exit_code == 0 db = sqlite_utils.Database(db_path) item_version = [ r for r",
"item_table = namespace or \"item\" version_table = \"{}_version\".format(item_table) assert db.schema == \"\"\" CREATE",
"the view view_rows = list( db.query( \"select _version, product_id, name, _changed_columns from {}_version_detail\".format(",
"\"version\": 1, \"column_name\": \"name\"}, {\"product_id\": 2, \"version\": 1, \"column_name\": \"product_id\"}, {\"product_id\": 2, \"version\":",
"PRIMARY KEY,\\n\" \" [_item_id] TEXT\\n\" \", [product_id] INTEGER, [name] TEXT, [_commit] INTEGER);\\n\" \"CREATE",
"json.dumps( [ { \"_id_\": 1, \"_version_\": \"Gin\", } ] ), \"utf-8\", ) (repo_dir",
"[_item] INTEGER REFERENCES [item]([_id]), [_version] INTEGER, [_commit] INTEGER REFERENCES [commits]([id]), [_id_] INTEGER, [_item_]",
"db.schema == textwrap.dedent( \"\"\" CREATE TABLE [namespaces] ( [id] INTEGER PRIMARY KEY, [name]",
"db_path, str(repo / \"items.json\"), \"--repo\", str(repo), \"--convert\", convert, ], catch_exceptions=False, ) assert result.exit_code",
"version_table = \"{}_version\".format(item_table) assert db.schema == \"\"\" CREATE TABLE [namespaces] ( [id] INTEGER",
"[]), ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) item_table = namespace or",
"/ \"db.db\") with runner.isolated_filesystem(): options = [\"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo)]",
"[rowid_] INTEGER, [_commit] INTEGER); CREATE UNIQUE INDEX [idx_item__item_id] ON [item] ([_item_id]); CREATE TABLE",
"( \"CREATE TABLE [namespaces] (\\n\" \" [id] INTEGER PRIMARY KEY,\\n\" \" [name] TEXT\\n\"",
"UNIQUE INDEX [idx_commits_namespace_hash] ON [commits] ([namespace], [hash]); CREATE TABLE [{namespace}] ( [_id] INTEGER",
"= CliRunner() db_path = str(tmpdir / \"db.db\") options = [ \"file\", db_path, str(repo",
"[id] INTEGER PRIMARY KEY, [name] TEXT ); CREATE UNIQUE INDEX [idx_namespaces_name] ON [namespaces]",
"/ \"incidents.json\").write_text( json.dumps( [ { \"IncidentID\": \"abc123\", \"Location\": \"Corner of 4th and Vermont\",",
"for column in table.columns_dict: if column.startswith(\"_\") and not column.endswith(\"_\"): with_prefix.add(column) assert with_prefix ==",
"TABLE [item] (\\n [TreeID] TEXT,\\n [name] TEXT\\n)\"), (\"excel-tab\", \"CREATE TABLE [item] (\\n [TreeID,name]",
"KEY, [_item] INTEGER REFERENCES [item]([_id]), [_version] INTEGER, [_commit] INTEGER REFERENCES [commits]([id]), [TreeID] TEXT,",
"runner = CliRunner() db_path = str(tmpdir / \"reserved.db\") with runner.isolated_filesystem(): result = runner.invoke(",
"+ \"\\n\" + expected_create_view(\"item\") + \"\\nCREATE INDEX [idx_item_version__item]\\n\" \" ON [item_version] ([_item]);\" ).strip()",
"\"\"\" ), \"--import\", \"xml.etree.ElementTree\", ], catch_exceptions=False, ) assert result.exit_code == 0 db =",
"INTEGER);\\n\" \"CREATE UNIQUE INDEX [idx_{}__item_id]\\n\".format(item_table) + \" ON [{}] ([_item_id]);\\n\".format(item_table) + \"CREATE TABLE",
"db_path = str(tmpdir / \"db.db\") with runner.isolated_filesystem(): options = [\"file\", db_path, str(repo /",
"{\"product_id\": 2, \"version\": 1, \"column_name\": \"product_id\"}, {\"product_id\": 2, \"version\": 2, \"column_name\": \"name\"}, {\"product_id\":",
"\"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\": 6, }, ] ), \"utf-8\", ) (repo_dir /",
"v in r.items() if k != \"_commit\"} for r in db[\"item\"].rows] assert rows",
"\"\\n\" + expected_create_view(\"item\") + \"\\nCREATE INDEX [idx_item_version__item]\\n\" \" ON [item_version] ([_item]);\" ).strip() assert",
"\" [name] TEXT\\n\" \");\\n\" \"CREATE UNIQUE INDEX [idx_namespaces_name]\\n\" \" ON [namespaces] ([name]);\\n\" \"CREATE",
"CliRunner() db_path = str(tmpdir / \"db.db\") with runner.isolated_filesystem(): result = runner.invoke( cli, [",
"\"branch\", \"-m\", \"main\"], cwd=str(repo_dir)) (repo_dir / \"items.json\").write_text( json.dumps( [ { \"product_id\": 1, \"name\":",
"\"trees.csv\", \"trees.tsv\", \"increment.txt\", ], cwd=str(repo_dir), ) subprocess.call(git_commit + [\"-m\", \"first\"], cwd=str(repo_dir)) subprocess.call([\"git\", \"branch\",",
"INTEGER PRIMARY KEY, [_item] INTEGER REFERENCES [item]([_id]), [_version] INTEGER, [_commit] INTEGER REFERENCES [commits]([id]),",
"result = runner.invoke( cli, [ \"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo), \"--id\",",
"TEXT, [name] TEXT, [_commit] INTEGER); CREATE UNIQUE INDEX [idx_item__item_id] ON [item] ([_item_id]); CREATE",
"2\"}, {\"product_id\": 3, \"_version\": 1, \"name\": \"Rum\"}, ] changed = list( db.query( \"\"\"",
"[ \"file\", db_path, str(repo / file), \"--repo\", str(repo), \"--id\", \"TreeID\", \"--csv\", \"--full-versions\", ],",
"test --skip for i in range(2, 4): (repo_dir / \"increment.txt\").write_text(str(i), \"utf-8\") subprocess.call( git_commit",
"== [ {\"product_id\": 1, \"version\": 1, \"column_name\": \"name\"}, {\"product_id\": 1, \"version\": 1, \"column_name\":",
"result = runner.invoke( cli, [ \"file\", db_path, str(repo / \"items.xml\"), \"--repo\", str(repo), \"--convert\",",
"[item]([_id]), [_version] INTEGER, [_commit] INTEGER REFERENCES [commits]([id]), [_id_] INTEGER, [_item_] TEXT, [_version_] TEXT,",
"= [{k: v for k, v in r.items() if k != \"_commit\"} for",
"3, \"product_id\": None, \"_version\": 2, \"name\": \"Rum Pony\"}, ] def test_file_with_id_resume_two_namespaces(repo, tmpdir): #",
"[name] TEXT\\n\" \");\" ) assert db[\"commits\"].count == 2 # Should have some duplicates",
"\"name\": \"Gin\"}, {\"_item\": 2, \"product_id\": 2, \"_version\": 1, \"name\": \"Tonic\"}, {\"_item\": 2, \"product_id\":",
"\"two\", \"value\": \"2\"}, ] @pytest.mark.parametrize( \"options,expected_texts\", ( ([], [\"1\", \"2\", \"3\"]), ([\"--skip\", 0],",
"CREATE TABLE [columns] ( [id] INTEGER PRIMARY KEY, [namespace] INTEGER REFERENCES [namespaces]([id]), [name]",
"2\"}, {\"product_id\": 3, \"_version\": 1, \"name\": \"Rum\"}, ] def test_file_with_reserved_columns(repo, tmpdir): runner =",
"[name] TEXT\\n\" \");\\n\" \"CREATE UNIQUE INDEX [idx_namespaces_name]\\n\" \" ON [namespaces] ([name]);\\n\" \"CREATE TABLE",
"[ { \"_id_\": 1, \"_version_\": \"Gin\", } ] ), \"utf-8\", ) (repo_dir /",
"[ \"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo), \"--convert\", convert, ], catch_exceptions=False, )",
"from item_version\" ) ] assert item_version == [ { \"_id_\": 1, \"_item_\": \"Gin\",",
"Pony assert db[\"one_version\"].count == 5 assert db[\"two_version\"].count == 5 @pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def",
"\"_version\": 1, \"name\": \"Gin\"}, {\"product_id\": 2, \"_version\": 1, \"name\": \"Tonic\"}, # product_id is",
"runner.invoke( cli, [ \"file\", db_path, str(repo / file), \"--repo\", str(repo), \"--id\", \"TreeID\", \"--csv\",",
"KEY,\\n\" \" [_item_id] TEXT\\n\" \", [product_id] INTEGER, [name] TEXT, [_commit] INTEGER);\\n\" \"CREATE UNIQUE",
"TABLE [item] ( [_id] INTEGER PRIMARY KEY, [_item_id] TEXT , [_id_] INTEGER, [_item_]",
"with _ prefixes and no suffix db = sqlite_utils.Database(db_path) with_prefix = {\"rowid\"} for",
"namespace else []), ) namespace = namespace or \"item\" assert result.exit_code == 0",
"TEXT,\\n [name] TEXT\\n)\"), (\"excel-tab\", \"CREATE TABLE [item] (\\n [TreeID,name] TEXT\\n)\"), ), ) def",
"= [ \"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo), ] if use_wal: options.append(\"--wal\")",
"[_id] INTEGER PRIMARY KEY,\\n\" \" [_item_id] TEXT\\n\" \", [product_id] INTEGER, [name] TEXT, [_commit]",
"in tree.iter(\"item\")] \"\"\" ), \"--import\", \"xml.etree.ElementTree\", ], catch_exceptions=False, ) assert result.exit_code == 0",
"REFERENCES [{namespace}_version]([_id]), [column] INTEGER REFERENCES [columns]([id]), PRIMARY KEY ([item_version], [column]) ); {view} CREATE",
"assert db.schema == \"\"\" CREATE TABLE [namespaces] ( [id] INTEGER PRIMARY KEY, [name]",
"), ) def test_convert(repo, tmpdir, convert, expected_rows): runner = CliRunner() db_path = str(tmpdir",
"[_id] INTEGER PRIMARY KEY, [_item] INTEGER REFERENCES [{namespace}]([_id]), [_version] INTEGER, [_commit] INTEGER REFERENCES",
"[_item_full_hash] TEXT ); CREATE TABLE [columns] ( [id] INTEGER PRIMARY KEY, [namespace] INTEGER",
"subprocess.call(git_commit + [\"-a\", \"-m\", \"another\"], cwd=str(repo)) result2 = runner.invoke( cli, [ \"file\", db_path,",
"[namespaces] ( [id] INTEGER PRIMARY KEY, [name] TEXT ); CREATE UNIQUE INDEX [idx_namespaces_name]",
"TEXT\\n)\"), ), ) def test_csv_dialect(repo, tmpdir, dialect, expected_schema): runner = CliRunner() db_path =",
"assert result.exit_code == 0 db = sqlite_utils.Database(db_path) assert list(db[\"item\"].rows) == [ {\"name\": \"one\",",
"no duplicates item_version = [ r for r in db.query( \"select product_id, _version,",
"str(repo), \"--convert\", convert, ], catch_exceptions=False, ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path)",
"= namespace or \"item\" version_table = \"{}_version\".format(item_table) assert db.schema == ( \"CREATE TABLE",
"\"Tonic\", \"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\": 6, }, ] ), \"utf-8\", ) (repo_dir",
") ).strip() @pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def test_file_without_id(repo, tmpdir, namespace): runner = CliRunner() db_path",
"{namespace}_changed where item_version = {namespace}_version._id ) ) as _changed_columns from {namespace}_version join commits",
") (repo_dir / \"items-with-reserved-columns.json\").write_text( json.dumps( [ { \"_id\": 1, \"_item\": \"Gin\", \"_version\": \"v1\",",
"columns.name \"\"\".format( namespace=namespace or \"item\" ) ) ) assert changed == [ {\"product_id\":",
"\"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo), \"--id\", \"product_id\", ], ) # Find",
"\"items.json\"), \"--repo\", str(repo)] if namespace: options += [\"--namespace\", namespace] result = runner.invoke(cli, options)",
"\"items-with-reserved-columns.json\").write_text( json.dumps( [ { \"_id\": 1, \"_item\": \"Gin\", \"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\":",
"\"product_id\": 3, \"_version\": 1, \"name\": \"Rum\"}, {\"_item\": 3, \"product_id\": None, \"_version\": 2, \"name\":",
"[_commit] INTEGER);\\n\" \"CREATE UNIQUE INDEX [idx_{}__item_id]\\n\".format(item_table) + \" ON [{}] ([_item_id]);\\n\".format(item_table) + \"CREATE",
"), \"utf-8\", ) subprocess.call(git_commit + [\"-m\", \"second\", \"-a\"], cwd=str(repo_dir)) # Three more commits",
"+ \"\\nCREATE INDEX [idx_item_version__item]\\n\" \" ON [item_version] ([_item]);\" ).strip() assert db.schema == expected_schema",
"sqlite_utils.Database(db_path) expected_schema = ( textwrap.dedent( \"\"\" CREATE TABLE [namespaces] ( [id] INTEGER PRIMARY",
"def test_skip_options(repo, tmpdir, options, expected_texts): runner = CliRunner() commits = list( reversed( subprocess.check_output([\"git\",",
"\" [_item_id] TEXT\\n\" \", [product_id] INTEGER, [name] TEXT, [_commit] INTEGER);\\n\" \"CREATE UNIQUE INDEX",
"5, }, { \"_id_\": 2, \"_item_\": \"Tonic\", \"_version_\": \"v1\", \"_commit_\": \"commit1\", \"rowid_\": 6,",
"test_convert(repo, tmpdir, convert, expected_rows): runner = CliRunner() db_path = str(tmpdir / \"db.db\") with",
"catch_exceptions=False, ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) assert list(db[\"item\"].rows) == [",
"\"name\": \"Gin\", \"_changed_columns\": [\"name\", \"product_id\"], }, { \"_version\": 1, \"product_id\": 2, \"name\": \"Tonic\",",
"str(repo / \"items-with-reserved-columns.json\"), \"--repo\", str(repo), \"--id\", \"_id\", \"--full-versions\", ], catch_exceptions=False, ) assert result.exit_code",
"textwrap.dedent( \"\"\" tree = xml.etree.ElementTree.fromstring(content) return [el.attrib for el in tree.iter(\"item\")] \"\"\" ),",
"\"file\", db_path, str(repo / file), \"--repo\", str(repo), \"--id\", \"TreeID\", \"--csv\", \"--full-versions\", ], catch_exceptions=False,",
"ON [commits] ([namespace], [hash]); CREATE TABLE [{namespace}] ( [_id] INTEGER PRIMARY KEY, [_item_id]",
"assert result.exit_code == 0 db = sqlite_utils.Database(db_path) rows = [{k: v for k,",
"1, \"_version\": 1, \"name\": \"Gin\"}, {\"product_id\": 2, \"_version\": 1, \"name\": \"Tonic\"}, {\"product_id\": None,",
"1, \"name\": \"Gin\", \"_changed_columns\": [\"name\", \"product_id\"], }, { \"_version\": 1, \"product_id\": 2, \"name\":",
"== 0 db = sqlite_utils.Database(db_path) rows = [{k: v for k, v in",
"( textwrap.dedent( \"\"\" CREATE TABLE [namespaces] ( [id] INTEGER PRIMARY KEY, [name] TEXT",
"INTEGER, [name] TEXT, [_commit] INTEGER); CREATE UNIQUE INDEX [idx_{namespace}__item_id] ON [{namespace}] ([_item_id]); CREATE",
"\"_changed_columns\": [\"name\"], }, { \"_version\": 1, \"product_id\": 3, \"name\": \"Rum\", \"_changed_columns\": [\"name\", \"product_id\"],",
"str(repo / \"items.json\"), \"--repo\", str(repo), \"--convert\", convert, ], catch_exceptions=False, ) assert result.exit_code ==",
"'[{\"id\": 1, \"text\": content.decode(\"utf-8\")}]', \"--id\", \"id\", ] + options, catch_exceptions=False, ) assert result.exit_code",
"{namespace}_changed.column = columns.id join {namespace}_version on {namespace}_changed.item_version = {namespace}_version._id join {namespace} on {namespace}._id",
"\"utf-8\", ) (repo_dir / \"increment.txt\").write_text(\"1\", \"utf-8\") subprocess.call([\"git\", \"init\"], cwd=str(repo_dir)) subprocess.call( [ \"git\", \"add\",",
"([_item]); \"\"\".strip().format( namespace=namespace or \"item\", view=expected_create_view(namespace or \"item\"), ) assert db[\"commits\"].count == 2",
"{ \"_version\": 2, \"product_id\": None, \"name\": \"Tonic 2\", \"_changed_columns\": [\"name\"], }, { \"_version\":",
"INTEGER, [_commit] INTEGER REFERENCES [commits]([id]), [_id_] INTEGER, [_item_] TEXT, [_version_] TEXT, [_commit_] TEXT,",
"\"--repo\", str(repo), \"--id\", \"product_id\", \"--namespace\", namespace, ], ) assert result.exit_code == 0 for",
"result.exit_code == 0 db = sqlite_utils.Database(db_path) item_table = namespace or \"item\" version_table =",
"ON [namespaces] ([name]); CREATE TABLE [commits] ( [id] INTEGER PRIMARY KEY, [namespace] INTEGER",
"UNIQUE INDEX [idx_namespaces_name]\\n\" \" ON [namespaces] ([name]);\\n\" \"CREATE TABLE [commits] (\\n\" \" [id]",
"options = [\"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo)] if namespace: options +=",
"runner = CliRunner() db_path = str(tmpdir / \"db.db\") with runner.isolated_filesystem(): options = [\"file\",",
"\"utf-8\", ) (repo_dir / \"items-with-reserved-columns.json\").write_text( json.dumps( [ { \"_id\": 1, \"_item\": \"Gin\", \"_version\":",
"with runner.isolated_filesystem(): result = runner.invoke( cli, [ \"file\", db_path, str(repo / file), \"--repo\",",
"assert item_version == [ { \"_id_\": 1, \"_item_\": \"Gin\", \"_version_\": \"v1\", \"_commit_\": \"commit1\",",
"1, \"column_name\": \"product_id\"}, {\"product_id\": 2, \"version\": 2, \"column_name\": \"name\"}, {\"product_id\": 3, \"version\": 1,",
"([namespace], [hash]);\\n\" \"CREATE TABLE [{}] (\\n\".format(namespace or \"item\") + \" [product_id] INTEGER,\\n\" \"",
"used for the README generated by Cog: (repo_dir / \"incidents.json\").write_text( json.dumps( [ {",
"commit and run again (repo / \"items.json\").write_text( json.dumps( [ {\"product_id\": 1, \"name\": \"Gin\"},",
"Generator ( ( \"data = json.loads(content)\\n\" \"for item in data:\\n\" ' yield {\"just_name\":",
"\"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo), \"--id\", \"product_id\", ] + ([\"--namespace\", namespace]",
"[id] INTEGER PRIMARY KEY,\\n\" \" [namespace] INTEGER REFERENCES [namespaces]([id]),\\n\" \" [hash] TEXT,\\n\" \"",
"{namespace}_version._version as version, columns.name as column_name from {namespace}_changed join columns on {namespace}_changed.column =",
"TABLE [item] ( [_id] INTEGER PRIMARY KEY, [_item_id] TEXT , [TreeID] TEXT, [name]",
"\" [namespace] INTEGER REFERENCES [namespaces]([id]),\\n\" \" [hash] TEXT,\\n\" \" [commit_at] TEXT\\n\" \");\\n\" \"CREATE",
"KEY, [namespace] INTEGER REFERENCES [namespaces]([id]), [hash] TEXT, [commit_at] TEXT ); CREATE UNIQUE INDEX",
"\"CREATE TABLE [{}] (\\n\".format(version_table) + \" [_id] INTEGER PRIMARY KEY,\\n\" \" [_item] INTEGER",
"item_version2 = [ r for r in db.query( \"select _item, product_id, _version, name",
"Rewrite options to replace integers with the corresponding commit hash options = [commits[item]",
"KEY, [_item_id] TEXT , [TreeID] TEXT, [name] TEXT, [_commit] INTEGER); CREATE UNIQUE INDEX",
"TEXT\\n\" \");\\n\" + expected_create_view(namespace or \"item\") + \"\\nCREATE INDEX [idx_{}__item]\\n\".format(version_table) + \" ON",
"\"_id\", \"--full-versions\", ], catch_exceptions=False, ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) expected_schema",
"[_version] INTEGER, [_commit] INTEGER REFERENCES [commits]([id]), [TreeID] TEXT, [name] TEXT );\"\"\" ).strip() +",
") namespace = namespace or \"item\" assert result.exit_code == 0 db = sqlite_utils.Database(db_path)",
"INTEGER PRIMARY KEY,\\n\" \" [_item_id] TEXT\\n\" \", [product_id] INTEGER, [name] TEXT, [_commit] INTEGER);\\n\"",
"{\"product_id\": 1, \"name\": \"Gin\"}, {\"product_id\": 2, \"name\": \"Tonic 2\"}, # This line has",
"\"-a\"], cwd=str(repo_dir) ) return repo_dir @pytest.fixture def repo(tmpdir): return make_repo(tmpdir) def expected_create_view(namespace): return",
"expected_schema @pytest.mark.parametrize( \"convert,expected_rows\", ( ( \"json.loads(content.upper())\", [ {\"PRODUCT_ID\": 1, \"NAME\": \"GIN\"}, {\"PRODUCT_ID\": 2,",
"\"--repo\", str(repo), \"--convert\", '[{\"id\": 1, \"text\": content.decode(\"utf-8\")}]', \"--id\", \"id\", ] + options, catch_exceptions=False,",
"2\"}, {\"product_id\": 3, \"_version\": 1, \"name\": \"Rum\"}, ] # Now we edit, commit",
"\"commits\", \"one\", \"one_version\", \"columns\", \"one_changed\", \"two\", \"two_version\", \"two_changed\", } # Should be five",
"no suffix db = sqlite_utils.Database(db_path) with_prefix = {\"rowid\"} for table in itertools.chain(db.tables, db.views):",
"\"--id\", \"product_id\", \"--full-versions\", ] + ([\"--namespace\", namespace] if namespace else []), ) assert",
"\"file\", db_path, str(repo / \"trees.csv\"), \"--repo\", str(repo), \"--dialect\", dialect, ], catch_exceptions=False, ) assert",
"with_prefix == set(RESERVED) @pytest.mark.parametrize(\"use_wal\", (True, False)) def test_wal(repo, tmpdir, use_wal): runner = CliRunner()",
"expected_schema): runner = CliRunner() db_path = str(tmpdir / \"db.db\") with runner.isolated_filesystem(): result =",
"PRIMARY KEY, [namespace] INTEGER REFERENCES [namespaces]([id]), [name] TEXT ); CREATE UNIQUE INDEX [idx_columns_namespace_name]",
"INTEGER REFERENCES [commits]([id]), [product_id] INTEGER, [name] TEXT, [_item_full_hash] TEXT ); CREATE TABLE [columns]",
"INDEX [idx_item_version__item]\\n\" \" ON [item_version] ([_item]);\" ) @pytest.mark.parametrize( \"dialect,expected_schema\", ( (\"excel\", \"CREATE TABLE",
"\"_commit\": \"commit1\", \"rowid\": 5, }, { \"_id\": 2, \"_item\": \"Tonic 2\", \"_version\": \"v1\",",
"(None, \"custom\")) def test_file_with_id(repo, tmpdir, namespace): runner = CliRunner() db_path = str(tmpdir /",
"/ \"increment.txt\").write_text(str(i), \"utf-8\") subprocess.call( git_commit + [\"-m\", \"increment {}\".format(i), \"-a\"], cwd=str(repo_dir) ) return",
"str(repo), \"--id\", \"product_id\", \"--namespace\", namespace, ], ) assert result.exit_code == 0 for namespace",
"[ {\"name\": \"one\", \"value\": \"1\"}, {\"name\": \"two\", \"value\": \"2\"}, ] @pytest.mark.parametrize( \"options,expected_texts\", (",
"\"name\": \"Tonic\"}, # product_id is None because it did not change here {\"product_id\":",
"if isinstance(item, int) else item for item in options] db_path = str(tmpdir /",
"REFERENCES [commits]([id]), [_id_] INTEGER, [_item_] TEXT, [_version_] TEXT, [_commit_] TEXT, [rowid_] INTEGER );\"\"\"",
"] ), \"utf-8\", ) (repo_dir / \"items-with-reserved-columns.json\").write_text( json.dumps( [ { \"_id\": 1, \"_item\":",
"\"product_id\", ], ) # Find all columns with _ prefixes and no suffix",
"\"item\") + \" [product_id] INTEGER,\\n\" \" [name] TEXT\\n\" \");\" ) assert db[\"commits\"].count ==",
"\"rowid_\": 5, }, { \"_id_\": 2, \"_item_\": \"Tonic\", \"_version_\": \"v1\", \"_commit_\": \"commit1\", \"rowid_\":",
"3, \"version\": 1, \"column_name\": \"name\"}, {\"product_id\": 3, \"version\": 1, \"column_name\": \"product_id\"}, ] #",
"cli, [ \"file\", db_path, str(repo / \"trees.csv\"), \"--repo\", str(repo), \"--dialect\", dialect, ], catch_exceptions=False,",
"commits to test --skip for i in range(2, 4): (repo_dir / \"increment.txt\").write_text(str(i), \"utf-8\")",
"= [ r for r in db.query( \"select product_id, _version, name from {}\".format(version_table)",
"PRIMARY KEY, [_item_id] TEXT , [product_id] INTEGER, [name] TEXT, [_commit] INTEGER); CREATE UNIQUE",
"</items> \"\"\", \"utf-8\", ) subprocess.call([\"git\", \"add\", \"items.xml\"], cwd=str(repo)) subprocess.call(git_commit + [\"-m\", \"items.xml\"], cwd=str(repo))",
"2, \"_item\": \"Tonic 2\", \"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\": 6, }, { \"_id\":",
"[_commit_] TEXT, [rowid_] INTEGER );\"\"\" ) + \"\\n\" + expected_create_view(\"item\") + \"\\nCREATE INDEX",
"CREATE TABLE [{namespace}] ( [_id] INTEGER PRIMARY KEY, [_item_id] TEXT , [product_id] INTEGER,",
"\"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo), \"--id\", \"product_id\", \"--full-versions\", ] + ([\"--namespace\",",
"3, \"_item_\": \"Rum\", \"_version_\": \"v1\", \"_commit_\": \"commit1\", \"rowid_\": 7, }, ] @pytest.mark.parametrize(\"file\", (\"trees.csv\",",
"3, \"_version\": 1, \"name\": \"Rum\"}, ] def test_file_with_reserved_columns(repo, tmpdir): runner = CliRunner() db_path",
"\"trees.tsv\", \"increment.txt\", ], cwd=str(repo_dir), ) subprocess.call(git_commit + [\"-m\", \"first\"], cwd=str(repo_dir)) subprocess.call([\"git\", \"branch\", \"-m\",",
"columns.name as column_name from {namespace}_changed join columns on {namespace}_changed.column = columns.id join {namespace}_version",
"db = sqlite_utils.Database(db_path) item_table = namespace or \"item\" version_table = \"{}_version\".format(item_table) assert db.schema",
"UNIQUE INDEX [idx_namespaces_name] ON [namespaces] ([name]); CREATE TABLE [commits] ( [id] INTEGER PRIMARY",
"(repo / \"items.json\").write_text( json.dumps( [ {\"product_id\": 1, \"name\": \"Gin\"}, {\"product_id\": 2, \"name\": \"Tonic",
"[hash]); CREATE TABLE [{namespace}] ( [_id] INTEGER PRIMARY KEY, [_item_id] TEXT , [product_id]",
"tree.iter(\"item\")] \"\"\" ), \"--import\", \"xml.etree.ElementTree\", ], catch_exceptions=False, ) assert result.exit_code == 0 db",
"as _changed_columns from {namespace}_version join commits on commits.id = {namespace}_version._commit; \"\"\".format( namespace=namespace )",
"[_item_id] TEXT , [TreeID] TEXT, [name] TEXT, [_commit] INTEGER); CREATE UNIQUE INDEX [idx_item__item_id]",
"result2.exit_code == 0 item_version2 = [ r for r in db.query( \"select _item,",
"namespace, ], ) assert result.exit_code == 0 for namespace in (\"one\", \"two\"): run(namespace)",
"str(repo), \"--id\", \"_id\", \"--full-versions\", ], catch_exceptions=False, ) assert result.exit_code == 0 db =",
"changed == [ {\"product_id\": 1, \"version\": 1, \"column_name\": \"name\"}, {\"product_id\": 1, \"version\": 1,",
"changed = list( db.query( \"\"\" select {namespace}.product_id, {namespace}_version._version as version, columns.name as column_name",
"= xml.etree.ElementTree.fromstring(content) return [el.attrib for el in tree.iter(\"item\")] \"\"\" ), \"--import\", \"xml.etree.ElementTree\", ],",
"/ \"items-with-reserved-columns.json\"), \"--repo\", str(repo), \"--id\", \"_id\", \"--full-versions\", ], catch_exceptions=False, ) assert result.exit_code ==",
"def test_convert(repo, tmpdir, convert, expected_rows): runner = CliRunner() db_path = str(tmpdir / \"db.db\")",
"[idx_item_version__item]\\n\" \" ON [item_version] ([_item]);\" ).strip() assert db.schema == expected_schema item_version = [",
"\"commit1\", \"rowid_\": 7, }, ] @pytest.mark.parametrize(\"file\", (\"trees.csv\", \"trees.tsv\")) def test_csv_tsv(repo, tmpdir, file): runner",
"\"--repo\", str(repo), \"--convert\", convert, ], catch_exceptions=False, ) assert result.exit_code == 0 db =",
"tmpdir, namespace): runner = CliRunner() db_path = str(tmpdir / \"db.db\") with runner.isolated_filesystem(): result",
"Now we edit, commit and try again (repo / \"items.json\").write_text( json.dumps( [ {\"product_id\":",
"[{}] ([_item]);\".format(version_table) ) assert db[\"commits\"].count == 2 # Should have no duplicates item_version",
"\" [id] INTEGER PRIMARY KEY,\\n\" \" [namespace] INTEGER REFERENCES [namespaces]([id]),\\n\" \" [hash] TEXT,\\n\"",
"\"v1\", \"_commit\": \"commit1\", \"rowid\": 6, }, { \"_id\": 3, \"_item\": \"Rum\", \"_version\": \"v1\",",
"[\"-m\", \"first\"], cwd=str(repo_dir)) subprocess.call([\"git\", \"branch\", \"-m\", \"main\"], cwd=str(repo_dir)) (repo_dir / \"items.json\").write_text( json.dumps( [",
"); CREATE UNIQUE INDEX [idx_commits_namespace_hash] ON [commits] ([namespace], [hash]); CREATE TABLE [item] (",
"1, \"_item\": \"Gin\", \"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\": 5, }, { \"_id\": 2,",
"2, \"name\": \"Tonic 2\"}, {\"product_id\": 3, \"_version\": 1, \"name\": \"Rum\"}, ] # Now",
"[ { \"_id_\": 1, \"_item_\": \"Gin\", \"_version_\": \"v1\", \"_commit_\": \"commit1\", \"rowid_\": 5, },",
"el in tree.iter(\"item\")] \"\"\" ), \"--import\", \"xml.etree.ElementTree\", ], catch_exceptions=False, ) assert result.exit_code ==",
"ON [{namespace}_version] ([_item]); \"\"\".strip().format( namespace=namespace or \"item\", view=expected_create_view(namespace or \"item\"), ) assert db[\"commits\"].count",
"namespace else []), catch_exceptions=False, ) assert result2.exit_code == 0 item_version2 = [ r",
"[TreeID] TEXT,\\n [name] TEXT\\n)\"), (\"excel-tab\", \"CREATE TABLE [item] (\\n [TreeID,name] TEXT\\n)\"), ), )",
"REFERENCES [namespaces]([id]), [hash] TEXT, [commit_at] TEXT ); CREATE UNIQUE INDEX [idx_commits_namespace_hash] ON [commits]",
"cli, [ \"file\", db_path, str(repo / \"increment.txt\"), \"--repo\", str(repo), \"--convert\", '[{\"id\": 1, \"text\":",
"Rum -> Rum Pony assert db[\"one_version\"].count == 5 assert db[\"two_version\"].count == 5 @pytest.mark.parametrize(\"namespace\",",
"assert result.exit_code == 0 for namespace in (\"one\", \"two\"): run(namespace) # Now modify",
"2, \"name\": \"Tonic 2\"}, {\"product_id\": 3, \"_version\": 1, \"name\": \"Rum\"}, ] def test_file_with_reserved_columns(repo,",
"\"item\" ) ) ) # Sort order of _changed_columns JSON is undefined, so",
"4 # Rewrite options to replace integers with the corresponding commit hash options",
"= CliRunner() db_path = str(tmpdir / \"db.db\") with runner.isolated_filesystem(): result = runner.invoke( cli,",
"}, ] @pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def test_file_with_id_resume(repo, tmpdir, namespace): runner = CliRunner() db_path",
"\"v1\", \"_commit_\": \"commit1\", \"rowid_\": 7, }, ] @pytest.mark.parametrize(\"file\", (\"trees.csv\", \"trees.tsv\")) def test_csv_tsv(repo, tmpdir,",
"json.dumps( [ { \"_id\": 1, \"_item\": \"Gin\", \"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\": 5,",
"== 2 # Should have no duplicates item_version = [ r for r",
"options, catch_exceptions=False, ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) expected_journal_mode = \"wal\"",
"str(tmpdir / \"db.db\") result = runner.invoke( cli, [ \"file\", db_path, str(repo / \"increment.txt\"),",
"1, \"name\": \"Gin\", }, { \"product_id\": 2, \"name\": \"Tonic 2\", }, { \"product_id\":",
"= str(tmpdir / \"db.db\") runner.invoke( cli, [ \"file\", db_path, str(repo / \"items.json\"), \"--repo\",",
"[_version_] TEXT, [_commit_] TEXT, [rowid_] INTEGER );\"\"\" ) + \"\\n\" + expected_create_view(\"item\") +",
"namespace or \"item\" ) ) ) # Sort order of _changed_columns JSON is",
"\"--repo\", str(repo), \"--id\", \"product_id\", \"--full-versions\", ] + ([\"--namespace\", namespace] if namespace else []),",
"\"product_id\": 2, \"name\": \"Tonic\", }, ] ), \"utf-8\", ) (repo_dir / \"items-with-reserved-columns.json\").write_text( json.dumps(",
"2], [\"2\", \"3\"]), ([\"--start-after\", 2], [\"3\"]), ([\"--start-at\", 3], [\"3\"]), ([\"--start-after\", 3], []), ),",
"\"trees.csv\"), \"--repo\", str(repo), \"--dialect\", dialect, ], catch_exceptions=False, ) assert result.exit_code == 0 db",
"cli, [ \"file\", db_path, str(repo / \"items.xml\"), \"--repo\", str(repo), \"--convert\", textwrap.dedent( \"\"\" tree",
"{ \"IncidentID\": \"abc123\", \"Location\": \"Corner of 4th and Vermont\", \"Type\": \"fire\", }, {",
"(repo_dir / \"trees.tsv\").write_text( \"TreeID\\tname\\n1\\tSophia\\n2\\tCharlie\", \"utf-8\", ) (repo_dir / \"increment.txt\").write_text(\"1\", \"utf-8\") subprocess.call([\"git\", \"init\"], cwd=str(repo_dir))",
"namespace] if namespace else []), catch_exceptions=False, ) assert result2.exit_code == 0 item_version2 =",
"or \"item\") + \" [product_id] INTEGER,\\n\" \" [name] TEXT\\n\" \");\" ) assert db[\"commits\"].count",
") # Find all columns with _ prefixes and no suffix db =",
"[TreeID,name] TEXT\\n)\"), ), ) def test_csv_dialect(repo, tmpdir, dialect, expected_schema): runner = CliRunner() db_path",
"import textwrap git_commit = [ \"git\", \"-c\", \"user.name='Tests'\", \"-c\", \"user.email='<EMAIL>'\", \"commit\", ] def",
"result = runner.invoke( cli, [ \"file\", db_path, str(repo / \"increment.txt\"), \"--repo\", str(repo), \"--convert\",",
"\"TONIC 2\"}, {\"PRODUCT_ID\": 3, \"NAME\": \"RUM\"}, ], ), # Generator ( ( \"data",
"[ { \"product_id\": 1, \"name\": \"Gin\", }, { \"product_id\": 2, \"name\": \"Tonic 2\",",
"\"_version\": 1, \"name\": \"Gin\"}, {\"_item\": 2, \"product_id\": 2, \"_version\": 1, \"name\": \"Tonic\"}, {\"_item\":",
"= sqlite_utils.Database(db_path) item_version = [ r for r in db.query( \"select product_id, _version,",
"[id] INTEGER PRIMARY KEY, [namespace] INTEGER REFERENCES [namespaces]([id]), [name] TEXT ); CREATE UNIQUE",
"\"custom\")) def test_file_without_id(repo, tmpdir, namespace): runner = CliRunner() db_path = str(tmpdir / \"db.db\")",
"{ \"_id_\": 2, \"_item_\": \"Tonic 2\", \"_version_\": \"v1\", \"_commit_\": \"commit1\", \"rowid_\": 6, },",
"generated by Cog: (repo_dir / \"incidents.json\").write_text( json.dumps( [ { \"IncidentID\": \"abc123\", \"Location\": \"Corner",
"0 for namespace in (\"one\", \"two\"): run(namespace) # Now modify items.json, commit and",
") subprocess.call(git_commit + [\"-a\", \"-m\", \"another\"], cwd=str(repo)) result2 = runner.invoke( cli, [ \"file\",",
"# Should be five versions: Gin, Tonic -> Tonic 2, Rum -> Rum",
"result.exit_code == 0 db = sqlite_utils.Database(db_path) rows = [{k: v for k, v",
"_commit_hash, {namespace}_version.*, ( select json_group_array(name) from columns where id in ( select column",
"assert db.schema == ( \"CREATE TABLE [namespaces] (\\n\" \" [id] INTEGER PRIMARY KEY,\\n\"",
"\"items.json\"), \"--repo\", str(repo), \"--id\", \"product_id\", \"--namespace\", namespace, ], ) assert result.exit_code == 0",
"fix that for row in view_rows: row[\"_changed_columns\"] = list(sorted(json.loads(row[\"_changed_columns\"]))) assert view_rows == [",
"columns on {namespace}_changed.column = columns.id join {namespace}_version on {namespace}_changed.item_version = {namespace}_version._id join {namespace}",
"columns.id join {namespace}_version on {namespace}_changed.item_version = {namespace}_version._id join {namespace} on {namespace}._id = {namespace}_version._item",
"\"Gin\"}, {\"product_id\": 2, \"_version\": 1, \"name\": \"Tonic\"}, {\"product_id\": None, \"_version\": 2, \"name\": \"Tonic",
"[ \"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo), ] if use_wal: options.append(\"--wal\") result",
") + \"\\n\" + expected_create_view(\"item\") + \"\\nCREATE INDEX [idx_item_version__item]\\n\" \" ON [item_version] ([_item]);\"",
"{view} CREATE INDEX [idx_{namespace}_version__item] ON [{namespace}_version] ([_item]); \"\"\".strip().format( namespace=namespace or \"item\", view=expected_create_view(namespace or",
"TEXT ); CREATE TABLE [columns] ( [id] INTEGER PRIMARY KEY, [namespace] INTEGER REFERENCES",
"[column]) ); {view} CREATE INDEX [idx_{namespace}_version__item] ON [{namespace}_version] ([_item]); \"\"\".strip().format( namespace=namespace or \"item\",",
"\"Rum Pony\"}, ] def test_file_with_id_resume_two_namespaces(repo, tmpdir): # https://github.com/simonw/git-history/issues/43 runner = CliRunner() db_path =",
"\"item\"].rows] == [ (1, \"Gin\"), (2, \"Tonic\"), (1, \"Gin\"), (2, \"Tonic 2\"), (3,",
"\"Tonic 2\"}, {\"product_id\": 3, \"name\": \"Rum Pony\"}, ] ), \"utf-8\", ) subprocess.call(git_commit +",
"2], [\"3\"]), ([\"--start-at\", 3], [\"3\"]), ([\"--start-after\", 3], []), ), ) def test_skip_options(repo, tmpdir,",
"\"column_name\": \"product_id\"}, {\"product_id\": 2, \"version\": 1, \"column_name\": \"name\"}, {\"product_id\": 2, \"version\": 1, \"column_name\":",
"REFERENCES [columns]([id]), PRIMARY KEY ([item_version], [column]) ); {view} CREATE INDEX [idx_{namespace}_version__item] ON [{namespace}_version]",
"\"2\"}, ] @pytest.mark.parametrize( \"options,expected_texts\", ( ([], [\"1\", \"2\", \"3\"]), ([\"--skip\", 0], [\"2\", \"3\"]),",
"/ \"items-with-reserved-columns.json\").write_text( json.dumps( [ { \"_id\": 1, \"_item\": \"Gin\", \"_version\": \"v1\", \"_commit\": \"commit1\",",
"\"--id\", \"product_id\", ] + ([\"--namespace\", namespace] if namespace else []), ) assert result.exit_code",
"in view_rows: row[\"_changed_columns\"] = list(sorted(json.loads(row[\"_changed_columns\"]))) assert view_rows == [ { \"_version\": 1, \"product_id\":",
"{namespace}._id = {namespace}_version._item order by {namespace}.product_id, {namespace}_version._version, columns.name \"\"\".format( namespace=namespace or \"item\" )",
"0, \"--skip\", 2], [\"3\"]), ([\"--start-at\", 2], [\"2\", \"3\"]), ([\"--start-after\", 2], [\"3\"]), ([\"--start-at\", 3],",
"[\"3\"]), ([\"--start-after\", 3], []), ), ) def test_skip_options(repo, tmpdir, options, expected_texts): runner =",
"TEXT, [_version_] TEXT, [_commit_] TEXT, [rowid_] INTEGER );\"\"\" ) + \"\\n\" + expected_create_view(\"item\")",
"{\"_item\": 2, \"product_id\": None, \"_version\": 2, \"name\": \"Tonic 2\"}, {\"_item\": 3, \"product_id\": 3,",
"item in options] db_path = str(tmpdir / \"db.db\") result = runner.invoke( cli, [",
"Should have no duplicates item_version = [ r for r in db.query( \"select",
"= str(tmpdir / \"db.db\") result = runner.invoke( cli, [ \"file\", db_path, str(repo /",
"\"CREATE TABLE [item] (\\n [TreeID] TEXT,\\n [name] TEXT\\n)\"), (\"excel-tab\", \"CREATE TABLE [item] (\\n",
"\"\"\" <items> <item name=\"one\" value=\"1\" /> <item name=\"two\" value=\"2\" /> </items> \"\"\", \"utf-8\",",
"[_version] INTEGER, [_commit] INTEGER REFERENCES [commits]([id]), [_id_] INTEGER, [_item_] TEXT, [_version_] TEXT, [_commit_]",
"( (\"excel\", \"CREATE TABLE [item] (\\n [TreeID] TEXT,\\n [name] TEXT\\n)\"), (\"excel-tab\", \"CREATE TABLE",
"def test_csv_dialect(repo, tmpdir, dialect, expected_schema): runner = CliRunner() db_path = str(tmpdir / \"db.db\")",
") def test_convert(repo, tmpdir, convert, expected_rows): runner = CliRunner() db_path = str(tmpdir /",
"= {\"rowid\"} for table in itertools.chain(db.tables, db.views): for column in table.columns_dict: if column.startswith(\"_\")",
"[hash]);\\n\" \"CREATE TABLE [{}] (\\n\".format(item_table) + \" [_id] INTEGER PRIMARY KEY,\\n\" \" [_item_id]",
"in range(2, 4): (repo_dir / \"increment.txt\").write_text(str(i), \"utf-8\") subprocess.call( git_commit + [\"-m\", \"increment {}\".format(i),",
"import pytest import subprocess import sqlite_utils import textwrap git_commit = [ \"git\", \"-c\",",
"1, \"column_name\": \"name\"}, {\"product_id\": 3, \"version\": 1, \"column_name\": \"product_id\"}, ] # Test the",
"\"Gin\"}, {\"product_id\": 2, \"name\": \"Tonic 2\"}, # This line has changed from \"Rum\"",
"result.exit_code == 0 db = sqlite_utils.Database(db_path) item_version = [ r for r in",
"/ \"items.json\").write_text( json.dumps( [ { \"product_id\": 1, \"name\": \"Gin\", }, { \"product_id\": 2,",
"[ r for r in db.query( \"select product_id, _version, name from {}_version\".format(namespace) )",
"[_item_id] TEXT , [product_id] INTEGER, [name] TEXT, [_commit] INTEGER); CREATE UNIQUE INDEX [idx_{namespace}__item_id]",
"cli, [ \"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo), \"--id\", \"product_id\", \"--full-versions\", ]",
"commits.id = {namespace}_version._commit; \"\"\".format( namespace=namespace ) ).strip() @pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def test_file_without_id(repo, tmpdir,",
"assert db.schema == expected_schema item_version = [ r for r in db.query( \"select",
"[item] (\\n [TreeID] TEXT,\\n [name] TEXT\\n)\"), (\"excel-tab\", \"CREATE TABLE [item] (\\n [TreeID,name] TEXT\\n)\"),",
"\"trees.csv\").write_text( \"TreeID,name\\n1,Sophia\\n2,Charlie\", \"utf-8\", ) (repo_dir / \"trees.tsv\").write_text( \"TreeID\\tname\\n1\\tSophia\\n2\\tCharlie\", \"utf-8\", ) (repo_dir / \"increment.txt\").write_text(\"1\",",
"(2, \"Tonic 2\"), (3, \"Rum\"), ] @pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def test_file_with_id(repo, tmpdir, namespace):",
"return [el.attrib for el in tree.iter(\"item\")] \"\"\" ), \"--import\", \"xml.etree.ElementTree\", ], catch_exceptions=False, )",
"int) else item for item in options] db_path = str(tmpdir / \"db.db\") result",
"INTEGER REFERENCES [{namespace}_version]([_id]), [column] INTEGER REFERENCES [columns]([id]), PRIMARY KEY ([item_version], [column]) ); {view}",
"ON [namespaces] ([name]);\\n\" \"CREATE TABLE [commits] (\\n\" \" [id] INTEGER PRIMARY KEY,\\n\" \"",
"(repo_dir / \"items.json\").write_text( json.dumps( [ { \"product_id\": 1, \"name\": \"Gin\", }, { \"product_id\":",
"= tmpdir / \"repo\" repo_dir.mkdir() # This one is used for the README",
"db.query( \"select product_id, _version, name from {}_version\".format(namespace) ) ] assert item_version == [",
"[commits]([id]),\\n\" \" [product_id] INTEGER,\\n\" \" [name] TEXT\\n\" \");\\n\" + expected_create_view(namespace or \"item\") +",
"([\"--start-after\", 3], []), ), ) def test_skip_options(repo, tmpdir, options, expected_texts): runner = CliRunner()",
"CREATE TABLE [item] ( [_id] INTEGER PRIMARY KEY, [_item_id] TEXT , [TreeID] TEXT,",
"{}\".format(i), \"-a\"], cwd=str(repo_dir) ) return repo_dir @pytest.fixture def repo(tmpdir): return make_repo(tmpdir) def expected_create_view(namespace):",
"\"log\", \"--pretty=format:%H\"], cwd=str(repo)) .decode(\"utf-8\") .split(\"\\n\") ) ) assert len(commits) == 4 # Rewrite",
"as _commit_hash, {namespace}_version.*, ( select json_group_array(name) from columns where id in ( select",
"/ \"items.json\"), \"--repo\", str(repo), \"--convert\", convert, ], catch_exceptions=False, ) assert result.exit_code == 0",
"data:\\n\" ' yield {\"just_name\": item[\"name\"]}' ), [ {\"just_name\": \"Gin\"}, {\"just_name\": \"Tonic\"}, {\"just_name\": \"Gin\"},",
"\"namespaces\", \"commits\", \"one\", \"one_version\", \"columns\", \"one_changed\", \"two\", \"two_version\", \"two_changed\", } # Should be",
"runner.isolated_filesystem(): result = runner.invoke( cli, [ \"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo),",
"\"_version_\": \"v1\", \"_commit_\": \"commit1\", \"rowid_\": 6, }, { \"_id_\": 3, \"_item_\": \"Rum\", \"_version_\":",
"\"custom\")) def test_file_with_id_resume(repo, tmpdir, namespace): runner = CliRunner() db_path = str(tmpdir / \"db.db\")",
"[hash] TEXT,\\n\" \" [commit_at] TEXT\\n\" \");\\n\" \"CREATE UNIQUE INDEX [idx_commits_namespace_hash]\\n\" \" ON [commits]",
") assert result.exit_code == 0 db = sqlite_utils.Database(db_path) assert ( db.schema == textwrap.dedent(",
"\"Gin\", }, { \"product_id\": 2, \"name\": \"Tonic 2\", }, { \"product_id\": 3, \"name\":",
"}, ] ), \"utf-8\", ) subprocess.call(git_commit + [\"-m\", \"second\", \"-a\"], cwd=str(repo_dir)) # Three",
"undefined, so fix that for row in view_rows: row[\"_changed_columns\"] = list(sorted(json.loads(row[\"_changed_columns\"]))) assert view_rows",
"\"Tonic\"}, {\"product_id\": None, \"_version\": 2, \"name\": \"Tonic 2\"}, {\"product_id\": 3, \"_version\": 1, \"name\":",
"item_version == [ { \"_id_\": 1, \"_item_\": \"Gin\", \"_version_\": \"v1\", \"_commit_\": \"commit1\", \"rowid_\":",
"expected_create_view(\"item\") + \"\\nCREATE INDEX [idx_item_version__item]\\n\" \" ON [item_version] ([_item]);\" ) @pytest.mark.parametrize( \"dialect,expected_schema\", (",
"[\"--namespace\", namespace] result = runner.invoke(cli, options) assert result.exit_code == 0 db = sqlite_utils.Database(db_path)",
"\"GIN\"}, {\"PRODUCT_ID\": 2, \"NAME\": \"TONIC\"}, {\"PRODUCT_ID\": 1, \"NAME\": \"GIN\"}, {\"PRODUCT_ID\": 2, \"NAME\": \"TONIC",
"{ \"product_id\": 2, \"name\": \"Tonic\", }, ] ), \"utf-8\", ) (repo_dir / \"items-with-reserved-columns.json\").write_text(",
"\"json.loads(content.upper())\", [ {\"PRODUCT_ID\": 1, \"NAME\": \"GIN\"}, {\"PRODUCT_ID\": 2, \"NAME\": \"TONIC\"}, {\"PRODUCT_ID\": 1, \"NAME\":",
"{\"_item\": 3, \"product_id\": None, \"_version\": 2, \"name\": \"Rum Pony\"}, ] def test_file_with_id_resume_two_namespaces(repo, tmpdir):",
"([\"--namespace\", namespace] if namespace else []), ) assert result.exit_code == 0 db =",
"\"Gin\"), (2, \"Tonic 2\"), (3, \"Rum\"), ] @pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def test_file_with_id(repo, tmpdir,",
"\"TreeID\\tname\\n1\\tSophia\\n2\\tCharlie\", \"utf-8\", ) (repo_dir / \"increment.txt\").write_text(\"1\", \"utf-8\") subprocess.call([\"git\", \"init\"], cwd=str(repo_dir)) subprocess.call( [ \"git\",",
"db.query( \"select _version, product_id, name, _changed_columns from {}_version_detail\".format( namespace or \"item\" ) )",
"False)) def test_wal(repo, tmpdir, use_wal): runner = CliRunner() db_path = str(tmpdir / \"db.db\")",
"Pony\"}, ] ), \"utf-8\", ) subprocess.call(git_commit + [\"-a\", \"-m\", \"another\"], cwd=str(repo)) for namespace",
"runner.invoke( cli, [ \"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo), \"--id\", \"product_id\", ]",
"\"_item\": \"Rum\", \"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\": 7, }, ] ), \"utf-8\", )",
"test_file_with_id_full_versions(repo, tmpdir, namespace): runner = CliRunner() db_path = str(tmpdir / \"db.db\") with runner.isolated_filesystem():",
"[ {\"product_id\": 1, \"name\": \"Gin\"}, {\"product_id\": 2, \"name\": \"Tonic 2\"}, {\"product_id\": 3, \"name\":",
"\"Rum\", \"_version_\": \"v1\", \"_commit_\": \"commit1\", \"rowid_\": 7, }, ] @pytest.mark.parametrize(\"file\", (\"trees.csv\", \"trees.tsv\")) def",
"5, }, { \"_id\": 2, \"_item\": \"Tonic\", \"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\": 6,",
"\" [_item] INTEGER REFERENCES [{}]([_id]),\\n\".format(item_table) + \" [_version] INTEGER,\\n\" \" [_commit] INTEGER REFERENCES",
"[commits[item] if isinstance(item, int) else item for item in options] db_path = str(tmpdir",
"item for item in options] db_path = str(tmpdir / \"db.db\") result = runner.invoke(",
"namespace): runner = CliRunner() db_path = str(tmpdir / \"db.db\") with runner.isolated_filesystem(): options =",
"0 db = sqlite_utils.Database(db_path) item_version = [ r for r in db.query( \"select",
"CREATE UNIQUE INDEX [idx_item__item_id] ON [item] ([_item_id]); CREATE TABLE [item_version] ( [_id] INTEGER",
"\", [product_id] INTEGER, [name] TEXT, [_commit] INTEGER);\\n\" \"CREATE UNIQUE INDEX [idx_{}__item_id]\\n\".format(item_table) + \"",
") (repo_dir / \"trees.tsv\").write_text( \"TreeID\\tname\\n1\\tSophia\\n2\\tCharlie\", \"utf-8\", ) (repo_dir / \"increment.txt\").write_text(\"1\", \"utf-8\") subprocess.call([\"git\", \"init\"],",
"\"Tonic\", \"_changed_columns\": [\"name\", \"product_id\"], }, { \"_version\": 2, \"product_id\": None, \"name\": \"Tonic 2\",",
"\"select product_id, _version, name from {}_version\".format(namespace) ) ] assert item_version == [ {\"product_id\":",
") as _changed_columns from {namespace}_version join commits on commits.id = {namespace}_version._commit; \"\"\".format( namespace=namespace",
"sqlite_utils.Database(db_path) assert db[\"item\"].schema == expected_schema @pytest.mark.parametrize( \"convert,expected_rows\", ( ( \"json.loads(content.upper())\", [ {\"PRODUCT_ID\": 1,",
"in (\"one\", \"two\"): run(namespace) # Now modify items.json, commit and run again (repo",
"db_path = str(tmpdir / \"db.db\") def run(namespace): result = runner.invoke( cli, [ \"file\",",
"db = sqlite_utils.Database(db_path) assert db.schema == ( \"CREATE TABLE [namespaces] (\\n\" \" [id]",
"[_version_] TEXT, [_commit_] TEXT, [rowid_] INTEGER, [_commit] INTEGER); CREATE UNIQUE INDEX [idx_item__item_id] ON",
"\"NAME\": \"TONIC 2\"}, {\"PRODUCT_ID\": 3, \"NAME\": \"RUM\"}, ], ), # Generator ( (",
"ON [item] ([_item_id]); CREATE TABLE [item_version] ( [_id] INTEGER PRIMARY KEY, [_item] INTEGER",
"str(repo / \"items.json\"), \"--repo\", str(repo), ] if use_wal: options.append(\"--wal\") result = runner.invoke( cli,",
"db_path, str(repo / \"trees.csv\"), \"--repo\", str(repo), \"--dialect\", dialect, ], catch_exceptions=False, ) assert result.exit_code",
"= sqlite_utils.Database(db_path) assert db[\"item\"].schema == expected_schema @pytest.mark.parametrize( \"convert,expected_rows\", ( ( \"json.loads(content.upper())\", [ {\"PRODUCT_ID\":",
"KEY, [_item] INTEGER REFERENCES [item]([_id]), [_version] INTEGER, [_commit] INTEGER REFERENCES [commits]([id]), [_id_] INTEGER,",
"\"CREATE TABLE [item] (\\n [TreeID,name] TEXT\\n)\"), ), ) def test_csv_dialect(repo, tmpdir, dialect, expected_schema):",
"\"NAME\": \"GIN\"}, {\"PRODUCT_ID\": 2, \"NAME\": \"TONIC 2\"}, {\"PRODUCT_ID\": 3, \"NAME\": \"RUM\"}, ], ),",
"[_id_] INTEGER, [_item_] TEXT, [_version_] TEXT, [_commit_] TEXT, [rowid_] INTEGER );\"\"\" ) +",
"\" ON [item_version] ([_item]);\" ).strip() assert db.schema == expected_schema item_version = [ r",
"db = sqlite_utils.Database(db_path) assert db[\"item\"].schema == expected_schema @pytest.mark.parametrize( \"convert,expected_rows\", ( ( \"json.loads(content.upper())\", [",
"1, \"name\": \"Gin\", }, { \"product_id\": 2, \"name\": \"Tonic\", }, ] ), \"utf-8\",",
"([\"--skip\", 0, \"--skip\", 2], [\"3\"]), ([\"--start-at\", 2], [\"2\", \"3\"]), ([\"--start-after\", 2], [\"3\"]), ([\"--start-at\",",
"] @pytest.mark.parametrize( \"options,expected_texts\", ( ([], [\"1\", \"2\", \"3\"]), ([\"--skip\", 0], [\"2\", \"3\"]), ([\"--skip\",",
"{\"_item\": 2, \"product_id\": 2, \"_version\": 1, \"name\": \"Tonic\"}, {\"_item\": 2, \"product_id\": None, \"_version\":",
"\"--full-versions\", ], catch_exceptions=False, ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) expected_schema =",
"== 0 db = sqlite_utils.Database(db_path) item_version = [ r for r in db.query(",
"[idx_commits_namespace_hash]\\n\" \" ON [commits] ([namespace], [hash]);\\n\" \"CREATE TABLE [{}] (\\n\".format(item_table) + \" [_id]",
"product_id is None because it did not change here {\"product_id\": None, \"_version\": 2,",
"assert item_version == [ {\"product_id\": 1, \"_version\": 1, \"name\": \"Gin\"}, {\"product_id\": 2, \"_version\":",
"\" [_commit] INTEGER REFERENCES [commits]([id]),\\n\" \" [product_id] INTEGER,\\n\" \" [name] TEXT\\n\" \");\\n\" +",
"corresponding commit hash options = [commits[item] if isinstance(item, int) else item for item",
"\"Gin\", }, { \"product_id\": 2, \"name\": \"Tonic\", }, ] ), \"utf-8\", ) (repo_dir",
"\");\\n\" \"CREATE UNIQUE INDEX [idx_commits_namespace_hash]\\n\" \" ON [commits] ([namespace], [hash]);\\n\" \"CREATE TABLE [{}]",
"Cog: (repo_dir / \"incidents.json\").write_text( json.dumps( [ { \"IncidentID\": \"abc123\", \"Location\": \"Corner of 4th",
"\"commit1\", \"rowid\": 6, }, ] ), \"utf-8\", ) (repo_dir / \"items-with-banned-columns.json\").write_text( json.dumps( [",
"}, { \"_version\": 1, \"product_id\": 2, \"name\": \"Tonic\", \"_changed_columns\": [\"name\", \"product_id\"], }, {",
"[idx_commits_namespace_hash] ON [commits] ([namespace], [hash]); CREATE TABLE [item] ( [_id] INTEGER PRIMARY KEY,",
") subprocess.call(git_commit + [\"-m\", \"second\", \"-a\"], cwd=str(repo_dir)) # Three more commits to test",
"2 # Should have some duplicates assert [(r[\"product_id\"], r[\"name\"]) for r in db[namespace",
"KEY,\\n\" \" [namespace] INTEGER REFERENCES [namespaces]([id]),\\n\" \" [hash] TEXT,\\n\" \" [commit_at] TEXT\\n\" \");\\n\"",
"[ {\"product_id\": 1, \"_version\": 1, \"name\": \"Gin\"}, {\"product_id\": 2, \"_version\": 1, \"name\": \"Tonic\"},",
"2, \"_item_\": \"Tonic 2\", \"_version_\": \"v1\", \"_commit_\": \"commit1\", \"rowid_\": 6, }, { \"_id_\":",
"result.exit_code == 0 db = sqlite_utils.Database(db_path) assert ( db.schema == textwrap.dedent( \"\"\" CREATE",
"+ [\"-m\", \"increment {}\".format(i), \"-a\"], cwd=str(repo_dir) ) return repo_dir @pytest.fixture def repo(tmpdir): return",
"\"_commit\": \"commit1\", \"rowid\": 6, }, ] ), \"utf-8\", ) (repo_dir / \"items-with-banned-columns.json\").write_text( json.dumps(",
"{namespace}_version_detail AS select commits.commit_at as _commit_at, commits.hash as _commit_hash, {namespace}_version.*, ( select json_group_array(name)",
"1, \"name\": \"Gin\"}, {\"product_id\": 2, \"_version\": 1, \"name\": \"Tonic\"}, {\"product_id\": None, \"_version\": 2,",
"1, \"name\": \"Gin\"}, {\"product_id\": 2, \"_version\": 1, \"name\": \"Tonic\"}, # product_id is None",
"[{}] (\\n\".format(version_table) + \" [_id] INTEGER PRIMARY KEY,\\n\" \" [_item] INTEGER REFERENCES [{}]([_id]),\\n\".format(item_table)",
"\"2\", \"3\"]), ([\"--skip\", 0], [\"2\", \"3\"]), ([\"--skip\", 0, \"--skip\", 2], [\"3\"]), ([\"--start-at\", 2],",
"(\"one\", \"two\"): run(namespace) # Now modify items.json, commit and run again (repo /",
"== ( \"CREATE TABLE [namespaces] (\\n\" \" [id] INTEGER PRIMARY KEY,\\n\" \" [name]",
"\"two_version\", \"two_changed\", } # Should be five versions: Gin, Tonic -> Tonic 2,",
"catch_exceptions=False, ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) expected_schema = ( textwrap.dedent(",
"from {namespace}_version join commits on commits.id = {namespace}_version._commit; \"\"\".format( namespace=namespace ) ).strip() @pytest.mark.parametrize(\"namespace\",",
"\"Gin\"}, {\"just_name\": \"Tonic\"}, {\"just_name\": \"Gin\"}, {\"just_name\": \"<NAME>\"}, {\"just_name\": \"Rum\"}, ], ), ), )",
"+ \" ON [{}] ([_item]);\".format(version_table) ) assert db[\"commits\"].count == 2 # Should have",
"[namespace] INTEGER REFERENCES [namespaces]([id]),\\n\" \" [hash] TEXT,\\n\" \" [commit_at] TEXT\\n\" \");\\n\" \"CREATE UNIQUE",
"= [commits[item] if isinstance(item, int) else item for item in options] db_path =",
"UNIQUE INDEX [idx_commits_namespace_hash] ON [commits] ([namespace], [hash]); CREATE TABLE [item] ( [_id] INTEGER",
"\"3\"]), ([\"--start-after\", 2], [\"3\"]), ([\"--start-at\", 3], [\"3\"]), ([\"--start-after\", 3], []), ), ) def",
"\"rowid_\": 6, }, { \"_id_\": 3, \"_item_\": \"Rum\", \"_version_\": \"v1\", \"_commit_\": \"commit1\", \"rowid_\":",
"\"_version\": 1, \"name\": \"Tonic\"}, {\"product_id\": None, \"_version\": 2, \"name\": \"Tonic 2\"}, {\"product_id\": 3,",
"/ \"db.db\") with runner.isolated_filesystem(): result = runner.invoke( cli, [ \"file\", db_path, str(repo /",
"with runner.isolated_filesystem(): result = runner.invoke( cli, [ \"file\", db_path, str(repo / \"items-with-reserved-columns.json\"), \"--repo\",",
"\"user.email='<EMAIL>'\", \"commit\", ] def make_repo(tmpdir): repo_dir = tmpdir / \"repo\" repo_dir.mkdir() # This",
"product_id, _version, name from {}_version order by _item, _version\".format( namespace ) ) ]",
"([], [\"1\", \"2\", \"3\"]), ([\"--skip\", 0], [\"2\", \"3\"]), ([\"--skip\", 0, \"--skip\", 2], [\"3\"]),",
"runner.isolated_filesystem(): options = [\"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo)] if namespace: options",
"] ), \"utf-8\", ) subprocess.call(git_commit + [\"-a\", \"-m\", \"another\"], cwd=str(repo)) for namespace in",
"cwd=str(repo_dir)) subprocess.call([\"git\", \"branch\", \"-m\", \"main\"], cwd=str(repo_dir)) (repo_dir / \"items.json\").write_text( json.dumps( [ { \"product_id\":",
"result = runner.invoke( cli, options, catch_exceptions=False, ) assert result.exit_code == 0 db =",
"db = sqlite_utils.Database(db_path) expected_journal_mode = \"wal\" if use_wal else \"delete\" assert db.journal_mode ==",
"name=\"one\" value=\"1\" /> <item name=\"two\" value=\"2\" /> </items> \"\"\", \"utf-8\", ) subprocess.call([\"git\", \"add\",",
"item_version2 == [ {\"_item\": 1, \"product_id\": 1, \"_version\": 1, \"name\": \"Gin\"}, {\"_item\": 2,",
"json import pytest import subprocess import sqlite_utils import textwrap git_commit = [ \"git\",",
"str(repo / \"items.json\"), \"--repo\", str(repo)] if namespace: options += [\"--namespace\", namespace] result =",
"db_path, str(repo / \"items.json\"), \"--repo\", str(repo), \"--id\", \"product_id\", \"--namespace\", namespace, ], ) assert",
"\"Tonic 2\"), (3, \"Rum\"), ] @pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def test_file_with_id(repo, tmpdir, namespace): runner",
"\"{}_version\".format(item_table) assert db.schema == ( \"CREATE TABLE [namespaces] (\\n\" \" [id] INTEGER PRIMARY",
"db = sqlite_utils.Database(db_path) actual_text = [r[\"text\"] for r in db[\"item_version\"].rows] assert actual_text ==",
"and Vermont\", \"Type\": \"fire\", }, { \"IncidentID\": \"cde448\", \"Location\": \"555 West Example Drive\",",
"json.dumps( [ { \"IncidentID\": \"abc123\", \"Location\": \"Corner of 4th and Vermont\", \"Type\": \"fire\",",
"db_path = str(tmpdir / \"db.db\") with runner.isolated_filesystem(): result = runner.invoke( cli, [ \"file\",",
"on {namespace}_changed.column = columns.id join {namespace}_version on {namespace}_changed.item_version = {namespace}_version._id join {namespace} on",
"TABLE [{}] (\\n\".format(version_table) + \" [_id] INTEGER PRIMARY KEY,\\n\" \" [_item] INTEGER REFERENCES",
"runner = CliRunner() db_path = str(tmpdir / \"db.db\") options = [ \"file\", db_path,",
"INDEX [idx_{}__item_id]\\n\".format(item_table) + \" ON [{}] ([_item_id]);\\n\".format(item_table) + \"CREATE TABLE [{}] (\\n\".format(version_table) +",
"tmpdir, file): runner = CliRunner() db_path = str(tmpdir / \"db.db\") with runner.isolated_filesystem(): result",
"{\"product_id\": 1, \"name\": \"Gin\"}, {\"product_id\": 2, \"name\": \"Tonic 2\"}, {\"product_id\": 3, \"name\": \"Rum",
") (repo_dir / \"items.json\").write_text( json.dumps( [ { \"product_id\": 1, \"name\": \"Gin\", }, {",
"1, \"version\": 1, \"column_name\": \"product_id\"}, {\"product_id\": 2, \"version\": 1, \"column_name\": \"name\"}, {\"product_id\": 2,",
"= [ r for r in db.query( \"select _id_, _item_, _version_, _commit_, rowid_",
"cli, [ \"file\", db_path, str(repo / file), \"--repo\", str(repo), \"--id\", \"TreeID\", \"--csv\", \"--full-versions\",",
"\"file\", db_path, str(repo / \"items.xml\"), \"--repo\", str(repo), \"--convert\", textwrap.dedent( \"\"\" tree = xml.etree.ElementTree.fromstring(content)",
"db[\"two_version\"].count == 5 @pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def test_file_with_id_full_versions(repo, tmpdir, namespace): runner = CliRunner()",
"3], []), ), ) def test_skip_options(repo, tmpdir, options, expected_texts): runner = CliRunner() commits",
"{\"product_id\": 1, \"version\": 1, \"column_name\": \"name\"}, {\"product_id\": 1, \"version\": 1, \"column_name\": \"product_id\"}, {\"product_id\":",
"= list( db.query( \"\"\" select {namespace}.product_id, {namespace}_version._version as version, columns.name as column_name from",
"import CliRunner from git_history.cli import cli from git_history.utils import RESERVED import itertools import",
"\"columns\", \"one_changed\", \"two\", \"two_version\", \"two_changed\", } # Should be five versions: Gin, Tonic",
"{\"_item\": 3, \"product_id\": 3, \"_version\": 1, \"name\": \"Rum\"}, {\"_item\": 3, \"product_id\": None, \"_version\":",
"_item, product_id, _version, name from {}_version order by _item, _version\".format( namespace ) )",
"[\"name\", \"product_id\"], }, { \"_version\": 1, \"product_id\": 2, \"name\": \"Tonic\", \"_changed_columns\": [\"name\", \"product_id\"],",
"Pony\": {\"product_id\": 3, \"name\": \"Rum Pony\"}, ] ), \"utf-8\", ) subprocess.call(git_commit + [\"-a\",",
"db.schema == ( \"CREATE TABLE [namespaces] (\\n\" \" [id] INTEGER PRIMARY KEY,\\n\" \"",
"\"product_id\": None, \"name\": \"Tonic 2\", \"_changed_columns\": [\"name\"], }, { \"_version\": 1, \"product_id\": 3,",
"r for r in db.query( \"select _item, product_id, _version, name from {}_version order",
"for the README generated by Cog: (repo_dir / \"incidents.json\").write_text( json.dumps( [ { \"IncidentID\":",
"ON [commits] ([namespace], [hash]); CREATE TABLE [item] ( [_id] INTEGER PRIMARY KEY, [_item_id]",
"[name] TEXT\\n)\"), (\"excel-tab\", \"CREATE TABLE [item] (\\n [TreeID,name] TEXT\\n)\"), ), ) def test_csv_dialect(repo,",
"{ \"_id_\": 3, \"_item_\": \"Rum\", \"_version_\": \"v1\", \"_commit_\": \"commit1\", \"rowid_\": 7, }, ]",
"join {namespace} on {namespace}._id = {namespace}_version._item order by {namespace}.product_id, {namespace}_version._version, columns.name \"\"\".format( namespace=namespace",
"], catch_exceptions=False, ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) assert list(db[\"item\"].rows) ==",
"catch_exceptions=False, ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) actual_text = [r[\"text\"] for",
"r in db.query( \"select product_id, _version, name from {}\".format(version_table) ) ] assert item_version",
"{ \"product_id\": 1, \"name\": \"Gin\", }, { \"product_id\": 2, \"name\": \"Tonic 2\", },",
"/ \"items.json\"), \"--repo\", str(repo), \"--id\", \"product_id\", \"--full-versions\", ] + ([\"--namespace\", namespace] if namespace",
"[ \"git\", \"-c\", \"user.name='Tests'\", \"-c\", \"user.email='<EMAIL>'\", \"commit\", ] def make_repo(tmpdir): repo_dir = tmpdir",
"TEXT, [_version_] TEXT, [_commit_] TEXT, [rowid_] INTEGER, [_commit] INTEGER); CREATE UNIQUE INDEX [idx_item__item_id]",
"TEXT, [_commit_] TEXT, [rowid_] INTEGER, [_commit] INTEGER); CREATE UNIQUE INDEX [idx_item__item_id] ON [item]",
"= sqlite_utils.Database(db_path) rows = [{k: v for k, v in r.items() if k",
"[_item] INTEGER REFERENCES [{}]([_id]),\\n\".format(item_table) + \" [_version] INTEGER,\\n\" \" [_commit] INTEGER REFERENCES [commits]([id]),\\n\"",
"== { \"namespaces\", \"commits\", \"one\", \"one_version\", \"columns\", \"one_changed\", \"two\", \"two_version\", \"two_changed\", } #",
"\"db.db\") with runner.isolated_filesystem(): result = runner.invoke( cli, [ \"file\", db_path, str(repo / \"trees.csv\"),",
"\"items.json\"), \"--repo\", str(repo), \"--id\", \"product_id\", ] + ([\"--namespace\", namespace] if namespace else []),",
"import itertools import json import pytest import subprocess import sqlite_utils import textwrap git_commit",
"1, \"name\": \"Tonic\"}, # product_id is None because it did not change here",
"\"db.db\") runner.invoke( cli, [ \"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo), \"--id\", \"product_id\",",
"PRIMARY KEY,\\n\" \" [name] TEXT\\n\" \");\\n\" \"CREATE UNIQUE INDEX [idx_namespaces_name]\\n\" \" ON [namespaces]",
"CREATE UNIQUE INDEX [idx_{namespace}__item_id] ON [{namespace}] ([_item_id]); CREATE TABLE [{namespace}_version] ( [_id] INTEGER",
"for namespace in (\"one\", \"two\"): run(namespace) db = sqlite_utils.Database(db_path) assert set(db.table_names()) == {",
"in db[namespace or \"item\"].rows] == [ (1, \"Gin\"), (2, \"Tonic\"), (1, \"Gin\"), (2,",
"order of _changed_columns JSON is undefined, so fix that for row in view_rows:",
"] assert item_version == [ { \"_id_\": 1, \"_item_\": \"Gin\", \"_version_\": \"v1\", \"_commit_\":",
"runner.invoke( cli, [ \"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo), \"--id\", \"product_id\", ],",
"1, \"name\": \"Gin\"}, {\"product_id\": 2, \"_version\": 1, \"name\": \"Tonic\"}, {\"product_id\": 2, \"_version\": 2,",
"[namespaces] (\\n\" \" [id] INTEGER PRIMARY KEY,\\n\" \" [name] TEXT\\n\" \");\\n\" \"CREATE UNIQUE",
"TEXT, [_commit] INTEGER);\\n\" \"CREATE UNIQUE INDEX [idx_{}__item_id]\\n\".format(item_table) + \" ON [{}] ([_item_id]);\\n\".format(item_table) +",
"\"version\": 1, \"column_name\": \"name\"}, {\"product_id\": 1, \"version\": 1, \"column_name\": \"product_id\"}, {\"product_id\": 2, \"version\":",
"item_version = {namespace}_version._id ) ) as _changed_columns from {namespace}_version join commits on commits.id",
"([_item]);\".format(version_table) ) assert db[\"commits\"].count == 2 # Should have no duplicates item_version =",
"commits.hash as _commit_hash, {namespace}_version.*, ( select json_group_array(name) from columns where id in (",
"2, Rum -> Rum Pony assert db[\"one_version\"].count == 5 assert db[\"two_version\"].count == 5",
"[ \"file\", db_path, str(repo / \"increment.txt\"), \"--repo\", str(repo), \"--convert\", '[{\"id\": 1, \"text\": content.decode(\"utf-8\")}]',",
"INDEX [idx_item_version__item]\\n\" \" ON [item_version] ([_item]);\" ).strip() assert db.schema == expected_schema item_version =",
"result2 = runner.invoke( cli, [ \"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo), \"--id\",",
"\"product_id\": 1, \"name\": \"Gin\", \"_changed_columns\": [\"name\", \"product_id\"], }, { \"_version\": 1, \"product_id\": 2,",
"assert result.exit_code == 0 db = sqlite_utils.Database(db_path) assert db[\"item\"].schema == expected_schema @pytest.mark.parametrize( \"convert,expected_rows\",",
"_version, name from {}\".format(version_table) ) ] assert item_version == [ {\"product_id\": 1, \"_version\":",
"\"db.db\") with runner.isolated_filesystem(): result = runner.invoke( cli, [ \"file\", db_path, str(repo / \"items.json\"),",
"{ \"_version\": 1, \"product_id\": 2, \"name\": \"Tonic\", \"_changed_columns\": [\"name\", \"product_id\"], }, { \"_version\":",
"_version_, _commit_, rowid_ from item_version\" ) ] assert item_version == [ { \"_id_\":",
"\"Gin\"}, {\"product_id\": 2, \"_version\": 1, \"name\": \"Tonic\"}, {\"product_id\": 2, \"_version\": 2, \"name\": \"Tonic",
"\"product_id\", ] + ([\"--namespace\", namespace] if namespace else []), ) namespace = namespace",
"}, { \"IncidentID\": \"cde448\", \"Location\": \"555 West Example Drive\", \"Type\": \"medical\", }, ]",
"\" ON [item_version] ([_item]);\" ) @pytest.mark.parametrize( \"dialect,expected_schema\", ( (\"excel\", \"CREATE TABLE [item] (\\n",
"= str(tmpdir / \"db.db\") options = [ \"file\", db_path, str(repo / \"items.json\"), \"--repo\",",
"\"TreeID,name\\n1,Sophia\\n2,Charlie\", \"utf-8\", ) (repo_dir / \"trees.tsv\").write_text( \"TreeID\\tname\\n1\\tSophia\\n2\\tCharlie\", \"utf-8\", ) (repo_dir / \"increment.txt\").write_text(\"1\", \"utf-8\")",
"/ \"items.xml\").write_text( \"\"\" <items> <item name=\"one\" value=\"1\" /> <item name=\"two\" value=\"2\" /> </items>",
"\" ON [commits] ([namespace], [hash]);\\n\" \"CREATE TABLE [{}] (\\n\".format(namespace or \"item\") + \"",
"2, \"_item_\": \"Tonic\", \"_version_\": \"v1\", \"_commit_\": \"commit1\", \"rowid_\": 6, }, { \"_id_\": 2,",
"= str(tmpdir / \"db.db\") with runner.isolated_filesystem(): options = [\"file\", db_path, str(repo / \"items.json\"),",
"[\"-a\", \"-m\", \"another\"], cwd=str(repo)) for namespace in (\"one\", \"two\"): run(namespace) db = sqlite_utils.Database(db_path)",
"INTEGER REFERENCES [item]([_id]), [_version] INTEGER, [_commit] INTEGER REFERENCES [commits]([id]), [_id_] INTEGER, [_item_] TEXT,",
"UNIQUE INDEX [idx_commits_namespace_hash]\\n\" \" ON [commits] ([namespace], [hash]);\\n\" \"CREATE TABLE [{}] (\\n\".format(namespace or",
"2, \"_version\": 1, \"name\": \"Tonic\"}, {\"product_id\": None, \"_version\": 2, \"name\": \"Tonic 2\"}, {\"product_id\":",
"/ \"items.xml\"), \"--repo\", str(repo), \"--convert\", textwrap.dedent( \"\"\" tree = xml.etree.ElementTree.fromstring(content) return [el.attrib for",
"= namespace or \"item\" assert result.exit_code == 0 db = sqlite_utils.Database(db_path) item_version =",
"repo_dir @pytest.fixture def repo(tmpdir): return make_repo(tmpdir) def expected_create_view(namespace): return textwrap.dedent( \"\"\" CREATE VIEW",
"1, \"name\": \"Rum\"}, ] changed = list( db.query( \"\"\" select {namespace}.product_id, {namespace}_version._version as",
"join {namespace}_version on {namespace}_changed.item_version = {namespace}_version._id join {namespace} on {namespace}._id = {namespace}_version._item order",
"1, \"name\": \"Gin\"}, {\"product_id\": 2, \"name\": \"Tonic 2\"}, {\"product_id\": 3, \"name\": \"Rum Pony\"},",
"tmpdir, use_wal): runner = CliRunner() db_path = str(tmpdir / \"db.db\") options = [",
"INTEGER REFERENCES [commits]([id]), [TreeID] TEXT, [name] TEXT );\"\"\" ).strip() + \"\\n\" + expected_create_view(\"item\")",
"cli, [ \"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo), \"--id\", \"product_id\", ] +",
"INTEGER); CREATE UNIQUE INDEX [idx_item__item_id] ON [item] ([_item_id]); CREATE TABLE [item_version] ( [_id]",
"TEXT ); CREATE UNIQUE INDEX [idx_commits_namespace_hash] ON [commits] ([namespace], [hash]); CREATE TABLE [{namespace}]",
"[idx_commits_namespace_hash] ON [commits] ([namespace], [hash]); CREATE TABLE [{namespace}] ( [_id] INTEGER PRIMARY KEY,",
"[\"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo)] if namespace: options += [\"--namespace\", namespace]",
"UNIQUE INDEX [idx_commits_namespace_hash]\\n\" \" ON [commits] ([namespace], [hash]);\\n\" \"CREATE TABLE [{}] (\\n\".format(item_table) +",
"json.dumps( [ {\"product_id\": 1, \"name\": \"Gin\"}, {\"product_id\": 2, \"name\": \"Tonic 2\"}, {\"product_id\": 3,",
"\"Gin\"}, {\"product_id\": 2, \"_version\": 1, \"name\": \"Tonic\"}, # product_id is None because it",
"] @pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def test_file_with_id_resume(repo, tmpdir, namespace): runner = CliRunner() db_path =",
"# Find all columns with _ prefixes and no suffix db = sqlite_utils.Database(db_path)",
") ) ) assert changed == [ {\"product_id\": 1, \"version\": 1, \"column_name\": \"name\"},",
"INTEGER, [_commit] INTEGER REFERENCES [commits]([id]), [product_id] INTEGER, [name] TEXT, [_item_full_hash] TEXT ); CREATE",
"[item] ( [_id] INTEGER PRIMARY KEY, [_item_id] TEXT , [_id_] INTEGER, [_item_] TEXT,",
"the corresponding commit hash options = [commits[item] if isinstance(item, int) else item for",
"CREATE TABLE [item] ( [_id] INTEGER PRIMARY KEY, [_item_id] TEXT , [_id_] INTEGER,",
"2\", \"_changed_columns\": [\"name\"], }, { \"_version\": 1, \"product_id\": 3, \"name\": \"Rum\", \"_changed_columns\": [\"name\",",
"= runner.invoke( cli, options, catch_exceptions=False, ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path)",
"suffix db = sqlite_utils.Database(db_path) with_prefix = {\"rowid\"} for table in itertools.chain(db.tables, db.views): for",
"tmpdir, options, expected_texts): runner = CliRunner() commits = list( reversed( subprocess.check_output([\"git\", \"log\", \"--pretty=format:%H\"],",
"list(sorted(json.loads(row[\"_changed_columns\"]))) assert view_rows == [ { \"_version\": 1, \"product_id\": 1, \"name\": \"Gin\", \"_changed_columns\":",
"cwd=str(repo)) for namespace in (\"one\", \"two\"): run(namespace) db = sqlite_utils.Database(db_path) assert set(db.table_names()) ==",
"Tonic -> Tonic 2, Rum -> Rum Pony assert db[\"one_version\"].count == 5 assert",
"in db[\"item_version\"].rows] assert actual_text == expected_texts def test_reserved_columns_are_reserved(tmpdir, repo): runner = CliRunner() db_path",
"commits.commit_at as _commit_at, commits.hash as _commit_hash, {namespace}_version.*, ( select json_group_array(name) from columns where",
"{\"name\": \"two\", \"value\": \"2\"}, ] @pytest.mark.parametrize( \"options,expected_texts\", ( ([], [\"1\", \"2\", \"3\"]), ([\"--skip\",",
"json.dumps( [ { \"product_id\": 1, \"name\": \"Gin\", }, { \"product_id\": 2, \"name\": \"Tonic\",",
"to \"Rum Pony\": {\"product_id\": 3, \"name\": \"Rum Pony\"}, ] ), \"utf-8\", ) subprocess.call(git_commit",
"README generated by Cog: (repo_dir / \"incidents.json\").write_text( json.dumps( [ { \"IncidentID\": \"abc123\", \"Location\":",
"[ r for r in db.query( \"select _item, product_id, _version, name from {}_version",
"options += [\"--namespace\", namespace] result = runner.invoke(cli, options) assert result.exit_code == 0 db",
"table in itertools.chain(db.tables, db.views): for column in table.columns_dict: if column.startswith(\"_\") and not column.endswith(\"_\"):",
"\"db.db\") with runner.isolated_filesystem(): result = runner.invoke( cli, [ \"file\", db_path, str(repo / file),",
"\"product_id\": 1, \"_version\": 1, \"name\": \"Gin\"}, {\"_item\": 2, \"product_id\": 2, \"_version\": 1, \"name\":",
"{namespace}_version._version, columns.name \"\"\".format( namespace=namespace or \"item\" ) ) ) assert changed == [",
"range(2, 4): (repo_dir / \"increment.txt\").write_text(str(i), \"utf-8\") subprocess.call( git_commit + [\"-m\", \"increment {}\".format(i), \"-a\"],",
"i in range(2, 4): (repo_dir / \"increment.txt\").write_text(str(i), \"utf-8\") subprocess.call( git_commit + [\"-m\", \"increment",
"\"file\", db_path, str(repo / \"increment.txt\"), \"--repo\", str(repo), \"--convert\", '[{\"id\": 1, \"text\": content.decode(\"utf-8\")}]', \"--id\",",
"cwd=str(repo)) subprocess.call(git_commit + [\"-m\", \"items.xml\"], cwd=str(repo)) db_path = str(tmpdir / \"db.db\") result =",
"Should be five versions: Gin, Tonic -> Tonic 2, Rum -> Rum Pony",
"[columns] ([namespace], [name]); CREATE TABLE [{namespace}_changed] ( [item_version] INTEGER REFERENCES [{namespace}_version]([_id]), [column] INTEGER",
"INDEX [idx_item__item_id] ON [item] ([_item_id]); CREATE TABLE [item_version] ( [_id] INTEGER PRIMARY KEY,",
"\"product_id\"], }, ] @pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def test_file_with_id_resume(repo, tmpdir, namespace): runner = CliRunner()",
"\"product_id\": 2, \"name\": \"Tonic 2\", }, { \"product_id\": 3, \"name\": \"Rum\", }, ]",
"\"_changed_columns\": [\"name\", \"product_id\"], }, { \"_version\": 1, \"product_id\": 2, \"name\": \"Tonic\", \"_changed_columns\": [\"name\",",
"{namespace}_changed join columns on {namespace}_changed.column = columns.id join {namespace}_version on {namespace}_changed.item_version = {namespace}_version._id",
"= columns.id join {namespace}_version on {namespace}_changed.item_version = {namespace}_version._id join {namespace} on {namespace}._id =",
"ON [item_version] ([_item]);\" ) @pytest.mark.parametrize( \"dialect,expected_schema\", ( (\"excel\", \"CREATE TABLE [item] (\\n [TreeID]",
"[ r for r in db.query( \"select product_id, _version, name from {}\".format(version_table) )",
"CliRunner() db_path = str(tmpdir / \"db.db\") def run(namespace): result = runner.invoke( cli, [",
"textwrap.dedent( \"\"\" CREATE VIEW {namespace}_version_detail AS select commits.commit_at as _commit_at, commits.hash as _commit_hash,",
"\"_item\": \"Gin\", \"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\": 5, }, { \"_id\": 2, \"_item\":",
"INDEX [idx_{namespace}__item_id] ON [{namespace}] ([_item_id]); CREATE TABLE [{namespace}_version] ( [_id] INTEGER PRIMARY KEY,",
"sqlite_utils.Database(db_path) with_prefix = {\"rowid\"} for table in itertools.chain(db.tables, db.views): for column in table.columns_dict:",
"\"commit1\", \"rowid\": 5, }, { \"_id\": 2, \"_item\": \"Tonic 2\", \"_version\": \"v1\", \"_commit\":",
"\"_id\": 1, \"_item\": \"Gin\", \"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\": 5, }, { \"_id\":",
"0 db = sqlite_utils.Database(db_path) actual_text = [r[\"text\"] for r in db[\"item_version\"].rows] assert actual_text",
"\"name\": \"Gin\", }, { \"product_id\": 2, \"name\": \"Tonic\", }, ] ), \"utf-8\", )",
"INTEGER,\\n\" \" [name] TEXT\\n\" \");\\n\" + expected_create_view(namespace or \"item\") + \"\\nCREATE INDEX [idx_{}__item]\\n\".format(version_table)",
"\"--id\", \"_id\", \"--full-versions\", ], catch_exceptions=False, ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path)",
"db[\"item\"].schema == expected_schema @pytest.mark.parametrize( \"convert,expected_rows\", ( ( \"json.loads(content.upper())\", [ {\"PRODUCT_ID\": 1, \"NAME\": \"GIN\"},",
"result.exit_code == 0 db = sqlite_utils.Database(db_path) expected_schema = ( textwrap.dedent( \"\"\" CREATE TABLE",
"\"--convert\", convert, ], catch_exceptions=False, ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) rows",
"\"repo\" repo_dir.mkdir() # This one is used for the README generated by Cog:",
"[ \"file\", db_path, str(repo / \"items-with-reserved-columns.json\"), \"--repo\", str(repo), \"--id\", \"_id\", \"--full-versions\", ], catch_exceptions=False,",
"\"Tonic\"), (1, \"Gin\"), (2, \"Tonic 2\"), (3, \"Rum\"), ] @pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def",
"versions: Gin, Tonic -> Tonic 2, Rum -> Rum Pony assert db[\"one_version\"].count ==",
"TABLE [commits] (\\n\" \" [id] INTEGER PRIMARY KEY,\\n\" \" [namespace] INTEGER REFERENCES [namespaces]([id]),\\n\"",
"== 0 db = sqlite_utils.Database(db_path) assert db.schema == ( \"CREATE TABLE [namespaces] (\\n\"",
"([_item]);\" ).strip() assert db.schema == expected_schema item_version = [ r for r in",
"(\\n [TreeID] TEXT,\\n [name] TEXT\\n)\"), (\"excel-tab\", \"CREATE TABLE [item] (\\n [TreeID,name] TEXT\\n)\"), ),",
"}, { \"_id_\": 3, \"_item_\": \"Rum\", \"_version_\": \"v1\", \"_commit_\": \"commit1\", \"rowid_\": 7, },",
"/ \"trees.tsv\").write_text( \"TreeID\\tname\\n1\\tSophia\\n2\\tCharlie\", \"utf-8\", ) (repo_dir / \"increment.txt\").write_text(\"1\", \"utf-8\") subprocess.call([\"git\", \"init\"], cwd=str(repo_dir)) subprocess.call(",
"CREATE UNIQUE INDEX [idx_commits_namespace_hash] ON [commits] ([namespace], [hash]); CREATE TABLE [{namespace}] ( [_id]",
"test_csv_dialect(repo, tmpdir, dialect, expected_schema): runner = CliRunner() db_path = str(tmpdir / \"db.db\") with",
"(repo_dir / \"increment.txt\").write_text(str(i), \"utf-8\") subprocess.call( git_commit + [\"-m\", \"increment {}\".format(i), \"-a\"], cwd=str(repo_dir) )",
"TABLE [{}] (\\n\".format(item_table) + \" [_id] INTEGER PRIMARY KEY,\\n\" \" [_item_id] TEXT\\n\" \",",
"\"-c\", \"user.name='Tests'\", \"-c\", \"user.email='<EMAIL>'\", \"commit\", ] def make_repo(tmpdir): repo_dir = tmpdir / \"repo\"",
"), \"utf-8\", ) (repo_dir / \"trees.csv\").write_text( \"TreeID,name\\n1,Sophia\\n2,Charlie\", \"utf-8\", ) (repo_dir / \"trees.tsv\").write_text( \"TreeID\\tname\\n1\\tSophia\\n2\\tCharlie\",",
"1, \"_version\": 1, \"name\": \"Gin\"}, {\"product_id\": 2, \"_version\": 1, \"name\": \"Tonic\"}, # product_id",
"list( db.query( \"select _version, product_id, name, _changed_columns from {}_version_detail\".format( namespace or \"item\" )",
"[ {\"_item\": 1, \"product_id\": 1, \"_version\": 1, \"name\": \"Gin\"}, {\"_item\": 2, \"product_id\": 2,",
"\"\"\".strip().format( namespace=namespace or \"item\", view=expected_create_view(namespace or \"item\"), ) assert db[\"commits\"].count == 2 #",
"name=\"two\" value=\"2\" /> </items> \"\"\", \"utf-8\", ) subprocess.call([\"git\", \"add\", \"items.xml\"], cwd=str(repo)) subprocess.call(git_commit +",
"\"_version_\": \"Gin\", } ] ), \"utf-8\", ) (repo_dir / \"trees.csv\").write_text( \"TreeID,name\\n1,Sophia\\n2,Charlie\", \"utf-8\", )",
"dialect, expected_schema): runner = CliRunner() db_path = str(tmpdir / \"db.db\") with runner.isolated_filesystem(): result",
"= runner.invoke( cli, [ \"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo), \"--id\", \"product_id\",",
"{ \"product_id\": 1, \"name\": \"Gin\", }, { \"product_id\": 2, \"name\": \"Tonic\", }, ]",
"if namespace else []), catch_exceptions=False, ) assert result2.exit_code == 0 item_version2 = [",
"column in table.columns_dict: if column.startswith(\"_\") and not column.endswith(\"_\"): with_prefix.add(column) assert with_prefix == set(RESERVED)",
"\"name\": \"Rum\", \"_changed_columns\": [\"name\", \"product_id\"], }, ] @pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def test_file_with_id_resume(repo, tmpdir,",
"] def test_file_with_id_resume_two_namespaces(repo, tmpdir): # https://github.com/simonw/git-history/issues/43 runner = CliRunner() db_path = str(tmpdir /",
"}, { \"_id_\": 2, \"_item_\": \"Tonic 2\", \"_version_\": \"v1\", \"_commit_\": \"commit1\", \"rowid_\": 6,",
"([namespace], [hash]);\\n\" \"CREATE TABLE [{}] (\\n\".format(item_table) + \" [_id] INTEGER PRIMARY KEY,\\n\" \"",
"subprocess import sqlite_utils import textwrap git_commit = [ \"git\", \"-c\", \"user.name='Tests'\", \"-c\", \"user.email='<EMAIL>'\",",
"1, \"name\": \"Gin\"}, {\"_item\": 2, \"product_id\": 2, \"_version\": 1, \"name\": \"Tonic\"}, {\"_item\": 2,",
"{namespace}.product_id, {namespace}_version._version, columns.name \"\"\".format( namespace=namespace or \"item\" ) ) ) assert changed ==",
"product_id, name, _changed_columns from {}_version_detail\".format( namespace or \"item\" ) ) ) # Sort",
"+ \" [_id] INTEGER PRIMARY KEY,\\n\" \" [_item] INTEGER REFERENCES [{}]([_id]),\\n\".format(item_table) + \"",
"KEY, [name] TEXT ); CREATE UNIQUE INDEX [idx_namespaces_name] ON [namespaces] ([name]); CREATE TABLE",
"2, \"column_name\": \"name\"}, {\"product_id\": 3, \"version\": 1, \"column_name\": \"name\"}, {\"product_id\": 3, \"version\": 1,",
"[\"3\"]), ([\"--start-at\", 2], [\"2\", \"3\"]), ([\"--start-after\", 2], [\"3\"]), ([\"--start-at\", 3], [\"3\"]), ([\"--start-after\", 3],",
"item in data:\\n\" ' yield {\"just_name\": item[\"name\"]}' ), [ {\"just_name\": \"Gin\"}, {\"just_name\": \"Tonic\"},",
"for row in view_rows: row[\"_changed_columns\"] = list(sorted(json.loads(row[\"_changed_columns\"]))) assert view_rows == [ { \"_version\":",
"{namespace}.product_id, {namespace}_version._version as version, columns.name as column_name from {namespace}_changed join columns on {namespace}_changed.column",
"\"utf-8\", ) subprocess.call([\"git\", \"add\", \"items.xml\"], cwd=str(repo)) subprocess.call(git_commit + [\"-m\", \"items.xml\"], cwd=str(repo)) db_path =",
"( \"data = json.loads(content)\\n\" \"for item in data:\\n\" ' yield {\"just_name\": item[\"name\"]}' ),",
"have some duplicates assert [(r[\"product_id\"], r[\"name\"]) for r in db[namespace or \"item\"].rows] ==",
"{}_version_detail\".format( namespace or \"item\" ) ) ) # Sort order of _changed_columns JSON",
"\"commit1\", \"rowid_\": 6, }, { \"_id_\": 2, \"_item_\": \"Tonic 2\", \"_version_\": \"v1\", \"_commit_\":",
"cli, [ \"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo), \"--id\", \"product_id\", \"--namespace\", namespace,",
"assert actual_text == expected_texts def test_reserved_columns_are_reserved(tmpdir, repo): runner = CliRunner() db_path = str(tmpdir",
"[(r[\"product_id\"], r[\"name\"]) for r in db[namespace or \"item\"].rows] == [ (1, \"Gin\"), (2,",
"}, { \"_version\": 2, \"product_id\": None, \"name\": \"Tonic 2\", \"_changed_columns\": [\"name\"], }, {",
"import json import pytest import subprocess import sqlite_utils import textwrap git_commit = [",
"from git_history.cli import cli from git_history.utils import RESERVED import itertools import json import",
"assert result2.exit_code == 0 item_version2 = [ r for r in db.query( \"select",
"namespace ) ) ] assert item_version2 == [ {\"_item\": 1, \"product_id\": 1, \"_version\":",
"}, { \"product_id\": 3, \"name\": \"Rum\", }, ] ), \"utf-8\", ) (repo_dir /",
"\"another\"], cwd=str(repo)) result2 = runner.invoke( cli, [ \"file\", db_path, str(repo / \"items.json\"), \"--repo\",",
"] + options, catch_exceptions=False, ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) actual_text",
") assert result.exit_code == 0 db = sqlite_utils.Database(db_path) assert db[\"item\"].schema == expected_schema @pytest.mark.parametrize(",
"[idx_item_version__item]\\n\" \" ON [item_version] ([_item]);\" ) @pytest.mark.parametrize( \"dialect,expected_schema\", ( (\"excel\", \"CREATE TABLE [item]",
"db = sqlite_utils.Database(db_path) assert list(db[\"item\"].rows) == [ {\"name\": \"one\", \"value\": \"1\"}, {\"name\": \"two\",",
"\"column_name\": \"name\"}, {\"product_id\": 3, \"version\": 1, \"column_name\": \"name\"}, {\"product_id\": 3, \"version\": 1, \"column_name\":",
"assert len(commits) == 4 # Rewrite options to replace integers with the corresponding",
"on commits.id = {namespace}_version._commit; \"\"\".format( namespace=namespace ) ).strip() @pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def test_file_without_id(repo,",
"([\"--start-after\", 2], [\"3\"]), ([\"--start-at\", 3], [\"3\"]), ([\"--start-after\", 3], []), ), ) def test_skip_options(repo,",
"\"_version\": 2, \"name\": \"Tonic 2\"}, {\"product_id\": 3, \"_version\": 1, \"name\": \"Rum\"}, ] changed",
"view_rows: row[\"_changed_columns\"] = list(sorted(json.loads(row[\"_changed_columns\"]))) assert view_rows == [ { \"_version\": 1, \"product_id\": 1,",
"for namespace in (\"one\", \"two\"): run(namespace) # Now modify items.json, commit and run",
"1, \"_version\": 1, \"name\": \"Gin\"}, {\"_item\": 2, \"product_id\": 2, \"_version\": 1, \"name\": \"Tonic\"},",
"\" ON [{}] ([_item]);\".format(version_table) ) assert db[\"commits\"].count == 2 # Should have no",
"}, { \"product_id\": 2, \"name\": \"Tonic 2\", }, { \"product_id\": 3, \"name\": \"Rum\",",
"db = sqlite_utils.Database(db_path) assert ( db.schema == textwrap.dedent( \"\"\" CREATE TABLE [namespaces] (",
"None, \"_version\": 2, \"name\": \"Tonic 2\"}, {\"_item\": 3, \"product_id\": 3, \"_version\": 1, \"name\":",
"or \"item\" ) ) ) # Sort order of _changed_columns JSON is undefined,",
"in itertools.chain(db.tables, db.views): for column in table.columns_dict: if column.startswith(\"_\") and not column.endswith(\"_\"): with_prefix.add(column)",
"+ \"\\nCREATE INDEX [idx_{}__item]\\n\".format(version_table) + \" ON [{}] ([_item]);\".format(version_table) ) assert db[\"commits\"].count ==",
"[id] INTEGER PRIMARY KEY, [namespace] INTEGER REFERENCES [namespaces]([id]), [hash] TEXT, [commit_at] TEXT );",
"# Test the view view_rows = list( db.query( \"select _version, product_id, name, _changed_columns",
"0 db = sqlite_utils.Database(db_path) assert list(db[\"item\"].rows) == [ {\"name\": \"one\", \"value\": \"1\"}, {\"name\":",
"2, \"NAME\": \"TONIC\"}, {\"PRODUCT_ID\": 1, \"NAME\": \"GIN\"}, {\"PRODUCT_ID\": 2, \"NAME\": \"TONIC 2\"}, {\"PRODUCT_ID\":",
"\"_version\": 1, \"product_id\": 3, \"name\": \"Rum\", \"_changed_columns\": [\"name\", \"product_id\"], }, ] @pytest.mark.parametrize(\"namespace\", (None,",
"result = runner.invoke( cli, [ \"file\", db_path, str(repo / \"items-with-reserved-columns.json\"), \"--repo\", str(repo), \"--id\",",
"catch_exceptions=False, ) assert result2.exit_code == 0 item_version2 = [ r for r in",
"for i in range(2, 4): (repo_dir / \"increment.txt\").write_text(str(i), \"utf-8\") subprocess.call( git_commit + [\"-m\",",
"actual_text == expected_texts def test_reserved_columns_are_reserved(tmpdir, repo): runner = CliRunner() db_path = str(tmpdir /",
"result = runner.invoke( cli, [ \"file\", db_path, str(repo / \"trees.csv\"), \"--repo\", str(repo), \"--dialect\",",
"= \"{}_version\".format(item_table) assert db.schema == ( \"CREATE TABLE [namespaces] (\\n\" \" [id] INTEGER",
"); {view} CREATE INDEX [idx_{namespace}_version__item] ON [{namespace}_version] ([_item]); \"\"\".strip().format( namespace=namespace or \"item\", view=expected_create_view(namespace",
"([\"--namespace\", namespace] if namespace else []), catch_exceptions=False, ) assert result2.exit_code == 0 item_version2",
"name from {}_version\".format(namespace) ) ] assert item_version == [ {\"product_id\": 1, \"_version\": 1,",
"+ [\"-m\", \"second\", \"-a\"], cwd=str(repo_dir)) # Three more commits to test --skip for",
"pytest import subprocess import sqlite_utils import textwrap git_commit = [ \"git\", \"-c\", \"user.name='Tests'\",",
"item_version == [ {\"product_id\": 1, \"_version\": 1, \"name\": \"Gin\"}, {\"product_id\": 2, \"_version\": 1,",
"[ { \"_version\": 1, \"product_id\": 1, \"name\": \"Gin\", \"_changed_columns\": [\"name\", \"product_id\"], }, {",
"sqlite_utils.Database(db_path) assert ( db.schema == textwrap.dedent( \"\"\" CREATE TABLE [namespaces] ( [id] INTEGER",
"\"name\": \"Rum\"}, ] def test_file_with_reserved_columns(repo, tmpdir): runner = CliRunner() db_path = str(tmpdir /",
"\" [name] TEXT\\n\" \");\" ) assert db[\"commits\"].count == 2 # Should have some",
"run again (repo / \"items.json\").write_text( json.dumps( [ {\"product_id\": 1, \"name\": \"Gin\"}, {\"product_id\": 2,",
"ON [{}] ([_item]);\".format(version_table) ) assert db[\"commits\"].count == 2 # Should have no duplicates",
"runner = CliRunner() db_path = str(tmpdir / \"db.db\") with runner.isolated_filesystem(): result = runner.invoke(",
"\"item\" version_table = \"{}_version\".format(item_table) assert db.schema == ( \"CREATE TABLE [namespaces] (\\n\" \"",
"West Example Drive\", \"Type\": \"medical\", }, ] ), \"utf-8\", ) (repo_dir / \"items.json\").write_text(",
"assert result.exit_code == 0 db = sqlite_utils.Database(db_path) item_table = namespace or \"item\" version_table",
"@pytest.fixture def repo(tmpdir): return make_repo(tmpdir) def expected_create_view(namespace): return textwrap.dedent( \"\"\" CREATE VIEW {namespace}_version_detail",
"to test --skip for i in range(2, 4): (repo_dir / \"increment.txt\").write_text(str(i), \"utf-8\") subprocess.call(",
"\"product_id\"], }, { \"_version\": 1, \"product_id\": 2, \"name\": \"Tonic\", \"_changed_columns\": [\"name\", \"product_id\"], },",
"\"one_version\", \"columns\", \"one_changed\", \"two\", \"two_version\", \"two_changed\", } # Should be five versions: Gin,",
"/ \"db.db\") result = runner.invoke( cli, [ \"file\", db_path, str(repo / \"items.xml\"), \"--repo\",",
"\"reserved.db\") with runner.isolated_filesystem(): result = runner.invoke( cli, [ \"file\", db_path, str(repo / \"items-with-reserved-columns.json\"),",
"\"items.json\"), \"--repo\", str(repo), \"--id\", \"product_id\", ], ) # Find all columns with _",
"] ), \"utf-8\", ) (repo_dir / \"items.json\").write_text( json.dumps( [ { \"product_id\": 1, \"name\":",
"TEXT , [_id_] INTEGER, [_item_] TEXT, [_version_] TEXT, [_commit_] TEXT, [rowid_] INTEGER, [_commit]",
"itertools.chain(db.tables, db.views): for column in table.columns_dict: if column.startswith(\"_\") and not column.endswith(\"_\"): with_prefix.add(column) assert",
"Example Drive\", \"Type\": \"medical\", }, ] ), \"utf-8\", ) (repo_dir / \"items.json\").write_text( json.dumps(",
"assert ( db.schema == textwrap.dedent( \"\"\" CREATE TABLE [namespaces] ( [id] INTEGER PRIMARY",
"def test_file_with_id(repo, tmpdir, namespace): runner = CliRunner() db_path = str(tmpdir / \"db.db\") with",
"\"v1\", \"_commit_\": \"commit1\", \"rowid_\": 5, }, { \"_id_\": 2, \"_item_\": \"Tonic\", \"_version_\": \"v1\",",
"file): runner = CliRunner() db_path = str(tmpdir / \"db.db\") with runner.isolated_filesystem(): result =",
"\"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo), \"--id\", \"product_id\", \"--namespace\", namespace, ], )",
"\"git\", \"-c\", \"user.name='Tests'\", \"-c\", \"user.email='<EMAIL>'\", \"commit\", ] def make_repo(tmpdir): repo_dir = tmpdir /",
"Should have some duplicates assert [(r[\"product_id\"], r[\"name\"]) for r in db[namespace or \"item\"].rows]",
"\"db.db\") def run(namespace): result = runner.invoke( cli, [ \"file\", db_path, str(repo / \"items.json\"),",
"{\"product_id\": 2, \"version\": 2, \"column_name\": \"name\"}, {\"product_id\": 3, \"version\": 1, \"column_name\": \"name\"}, {\"product_id\":",
"\"Gin\", \"_changed_columns\": [\"name\", \"product_id\"], }, { \"_version\": 1, \"product_id\": 2, \"name\": \"Tonic\", \"_changed_columns\":",
"[_version] INTEGER,\\n\" \" [_commit] INTEGER REFERENCES [commits]([id]),\\n\" \" [product_id] INTEGER,\\n\" \" [name] TEXT\\n\"",
"\"--repo\", str(repo), ] if use_wal: options.append(\"--wal\") result = runner.invoke( cli, options, catch_exceptions=False, )",
"json.dumps( [ {\"product_id\": 1, \"name\": \"Gin\"}, {\"product_id\": 2, \"name\": \"Tonic 2\"}, # This",
"\"--full-versions\", ] + ([\"--namespace\", namespace] if namespace else []), ) assert result.exit_code ==",
"' yield {\"just_name\": item[\"name\"]}' ), [ {\"just_name\": \"Gin\"}, {\"just_name\": \"Tonic\"}, {\"just_name\": \"Gin\"}, {\"just_name\":",
"(1, \"Gin\"), (2, \"Tonic 2\"), (3, \"Rum\"), ] @pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def test_file_with_id(repo,",
"tmpdir): runner = CliRunner() (repo / \"items.xml\").write_text( \"\"\" <items> <item name=\"one\" value=\"1\" />",
"\"Location\": \"Corner of 4th and Vermont\", \"Type\": \"fire\", }, { \"IncidentID\": \"cde448\", \"Location\":",
"3, \"NAME\": \"RUM\"}, ], ), # Generator ( ( \"data = json.loads(content)\\n\" \"for",
"db_path, str(repo / \"items.xml\"), \"--repo\", str(repo), \"--convert\", textwrap.dedent( \"\"\" tree = xml.etree.ElementTree.fromstring(content) return",
"] @pytest.mark.parametrize(\"file\", (\"trees.csv\", \"trees.tsv\")) def test_csv_tsv(repo, tmpdir, file): runner = CliRunner() db_path =",
"-> Tonic 2, Rum -> Rum Pony assert db[\"one_version\"].count == 5 assert db[\"two_version\"].count",
"modify items.json, commit and run again (repo / \"items.json\").write_text( json.dumps( [ {\"product_id\": 1,",
"product_id, _version, name from {}_version\".format(namespace) ) ] assert item_version == [ {\"product_id\": 1,",
"in data:\\n\" ' yield {\"just_name\": item[\"name\"]}' ), [ {\"just_name\": \"Gin\"}, {\"just_name\": \"Tonic\"}, {\"just_name\":",
"[product_id] INTEGER, [name] TEXT, [_item_full_hash] TEXT ); CREATE TABLE [columns] ( [id] INTEGER",
"(repo_dir / \"items-with-reserved-columns.json\").write_text( json.dumps( [ { \"_id\": 1, \"_item\": \"Gin\", \"_version\": \"v1\", \"_commit\":",
"[_commit] INTEGER); CREATE UNIQUE INDEX [idx_{namespace}__item_id] ON [{namespace}] ([_item_id]); CREATE TABLE [{namespace}_version] (",
"[ {\"just_name\": \"Gin\"}, {\"just_name\": \"Tonic\"}, {\"just_name\": \"Gin\"}, {\"just_name\": \"<NAME>\"}, {\"just_name\": \"Rum\"}, ], ),",
") assert result.exit_code == 0 db = sqlite_utils.Database(db_path) assert list(db[\"item\"].rows) == [ {\"name\":",
"= sqlite_utils.Database(db_path) assert db.schema == ( \"CREATE TABLE [namespaces] (\\n\" \" [id] INTEGER",
"[idx_{}__item]\\n\".format(version_table) + \" ON [{}] ([_item]);\".format(version_table) ) assert db[\"commits\"].count == 2 # Should",
"INTEGER PRIMARY KEY, [_item_id] TEXT , [_id_] INTEGER, [_item_] TEXT, [_version_] TEXT, [_commit_]",
"[{namespace}_version] ([_item]); \"\"\".strip().format( namespace=namespace or \"item\", view=expected_create_view(namespace or \"item\"), ) assert db[\"commits\"].count ==",
"\"items.json\"), \"--repo\", str(repo), \"--convert\", convert, ], catch_exceptions=False, ) assert result.exit_code == 0 db",
"\"add\", \"items.xml\"], cwd=str(repo)) subprocess.call(git_commit + [\"-m\", \"items.xml\"], cwd=str(repo)) db_path = str(tmpdir / \"db.db\")",
"\"xml.etree.ElementTree\", ], catch_exceptions=False, ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) assert list(db[\"item\"].rows)",
"\");\\n\" + expected_create_view(namespace or \"item\") + \"\\nCREATE INDEX [idx_{}__item]\\n\".format(version_table) + \" ON [{}]",
"TEXT\\n\" \");\\n\" \"CREATE UNIQUE INDEX [idx_commits_namespace_hash]\\n\" \" ON [commits] ([namespace], [hash]);\\n\" \"CREATE TABLE",
"[_item_id] TEXT\\n\" \", [product_id] INTEGER, [name] TEXT, [_commit] INTEGER);\\n\" \"CREATE UNIQUE INDEX [idx_{}__item_id]\\n\".format(item_table)",
"== 0 db = sqlite_utils.Database(db_path) assert ( db.schema == textwrap.dedent( \"\"\" CREATE TABLE",
"[\"2\", \"3\"]), ([\"--skip\", 0, \"--skip\", 2], [\"3\"]), ([\"--start-at\", 2], [\"2\", \"3\"]), ([\"--start-after\", 2],",
"= runner.invoke( cli, [ \"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo), \"--convert\", convert,",
"\"--id\", \"id\", ] + options, catch_exceptions=False, ) assert result.exit_code == 0 db =",
"[id] INTEGER PRIMARY KEY,\\n\" \" [name] TEXT\\n\" \");\\n\" \"CREATE UNIQUE INDEX [idx_namespaces_name]\\n\" \"",
"== expected_schema @pytest.mark.parametrize( \"convert,expected_rows\", ( ( \"json.loads(content.upper())\", [ {\"PRODUCT_ID\": 1, \"NAME\": \"GIN\"}, {\"PRODUCT_ID\":",
"k, v in r.items() if k != \"_commit\"} for r in db[\"item\"].rows] assert",
"\"--repo\", str(repo), \"--id\", \"product_id\", ], ) # Find all columns with _ prefixes",
"\"_version\": 1, \"product_id\": 1, \"name\": \"Gin\", \"_changed_columns\": [\"name\", \"product_id\"], }, { \"_version\": 1,",
"= runner.invoke( cli, [ \"file\", db_path, str(repo / \"items-with-reserved-columns.json\"), \"--repo\", str(repo), \"--id\", \"_id\",",
"name from {}_version order by _item, _version\".format( namespace ) ) ] assert item_version2",
"else item for item in options] db_path = str(tmpdir / \"db.db\") result =",
"PRIMARY KEY, [_item] INTEGER REFERENCES [item]([_id]), [_version] INTEGER, [_commit] INTEGER REFERENCES [commits]([id]), [_id_]",
"\"-c\", \"user.email='<EMAIL>'\", \"commit\", ] def make_repo(tmpdir): repo_dir = tmpdir / \"repo\" repo_dir.mkdir() #",
"[{k: v for k, v in r.items() if k != \"_commit\"} for r",
"where item_version = {namespace}_version._id ) ) as _changed_columns from {namespace}_version join commits on",
"if namespace else []), ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) item_table",
"assert list(db[\"item\"].rows) == [ {\"name\": \"one\", \"value\": \"1\"}, {\"name\": \"two\", \"value\": \"2\"}, ]",
"\"_id_\": 1, \"_version_\": \"Gin\", } ] ), \"utf-8\", ) (repo_dir / \"trees.csv\").write_text( \"TreeID,name\\n1,Sophia\\n2,Charlie\",",
"{\"_item\": 1, \"product_id\": 1, \"_version\": 1, \"name\": \"Gin\"}, {\"_item\": 2, \"product_id\": 2, \"_version\":",
"\"_id_\": 3, \"_item_\": \"Rum\", \"_version_\": \"v1\", \"_commit_\": \"commit1\", \"rowid_\": 7, }, ] @pytest.mark.parametrize(\"file\",",
"\"--repo\", str(repo), \"--id\", \"product_id\", ] + ([\"--namespace\", namespace] if namespace else []), )",
"2\", \"_version_\": \"v1\", \"_commit_\": \"commit1\", \"rowid_\": 6, }, { \"_id_\": 3, \"_item_\": \"Rum\",",
"[commit_at] TEXT ); CREATE UNIQUE INDEX [idx_commits_namespace_hash] ON [commits] ([namespace], [hash]); CREATE TABLE",
"\"Rum Pony\"}, ] ), \"utf-8\", ) subprocess.call(git_commit + [\"-a\", \"-m\", \"another\"], cwd=str(repo)) for",
"test_file_with_id_resume_two_namespaces(repo, tmpdir): # https://github.com/simonw/git-history/issues/43 runner = CliRunner() db_path = str(tmpdir / \"db.db\") def",
"(\\n\".format(namespace or \"item\") + \" [product_id] INTEGER,\\n\" \" [name] TEXT\\n\" \");\" ) assert",
"str(tmpdir / \"db.db\") result = runner.invoke( cli, [ \"file\", db_path, str(repo / \"items.json\"),",
"3, \"name\": \"Rum\", \"_changed_columns\": [\"name\", \"product_id\"], }, ] @pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def test_file_with_id_resume(repo,",
"r in db[\"item_version\"].rows] assert actual_text == expected_texts def test_reserved_columns_are_reserved(tmpdir, repo): runner = CliRunner()",
") assert result.exit_code == 0 db = sqlite_utils.Database(db_path) actual_text = [r[\"text\"] for r",
"] + ([\"--namespace\", namespace] if namespace else []), ) namespace = namespace or",
"\"text\": content.decode(\"utf-8\")}]', \"--id\", \"id\", ] + options, catch_exceptions=False, ) assert result.exit_code == 0",
"[hash]);\\n\" \"CREATE TABLE [{}] (\\n\".format(namespace or \"item\") + \" [product_id] INTEGER,\\n\" \" [name]",
"[_commit] INTEGER); CREATE UNIQUE INDEX [idx_item__item_id] ON [item] ([_item_id]); CREATE TABLE [item_version] (",
"test_wal(repo, tmpdir, use_wal): runner = CliRunner() db_path = str(tmpdir / \"db.db\") options =",
"\"version\": 1, \"column_name\": \"name\"}, {\"product_id\": 3, \"version\": 1, \"column_name\": \"product_id\"}, ] # Test",
"TEXT ); CREATE UNIQUE INDEX [idx_columns_namespace_name] ON [columns] ([namespace], [name]); CREATE TABLE [{namespace}_changed]",
"INTEGER,\\n\" \" [_commit] INTEGER REFERENCES [commits]([id]),\\n\" \" [product_id] INTEGER,\\n\" \" [name] TEXT\\n\" \");\\n\"",
"runner.invoke( cli, [ \"file\", db_path, str(repo / \"items-with-reserved-columns.json\"), \"--repo\", str(repo), \"--id\", \"_id\", \"--full-versions\",",
"CREATE TABLE [commits] ( [id] INTEGER PRIMARY KEY, [namespace] INTEGER REFERENCES [namespaces]([id]), [hash]",
"[commits] (\\n\" \" [id] INTEGER PRIMARY KEY,\\n\" \" [namespace] INTEGER REFERENCES [namespaces]([id]),\\n\" \"",
"[_item] INTEGER REFERENCES [{namespace}]([_id]), [_version] INTEGER, [_commit] INTEGER REFERENCES [commits]([id]), [product_id] INTEGER, [name]",
"options = [commits[item] if isinstance(item, int) else item for item in options] db_path",
"4): (repo_dir / \"increment.txt\").write_text(str(i), \"utf-8\") subprocess.call( git_commit + [\"-m\", \"increment {}\".format(i), \"-a\"], cwd=str(repo_dir)",
"\"utf-8\", ) subprocess.call(git_commit + [\"-a\", \"-m\", \"another\"], cwd=str(repo)) for namespace in (\"one\", \"two\"):",
"str(repo / \"items.xml\"), \"--repo\", str(repo), \"--convert\", textwrap.dedent( \"\"\" tree = xml.etree.ElementTree.fromstring(content) return [el.attrib",
"duplicates assert [(r[\"product_id\"], r[\"name\"]) for r in db[namespace or \"item\"].rows] == [ (1,",
"column.endswith(\"_\"): with_prefix.add(column) assert with_prefix == set(RESERVED) @pytest.mark.parametrize(\"use_wal\", (True, False)) def test_wal(repo, tmpdir, use_wal):",
"\"id\", ] + options, catch_exceptions=False, ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path)",
"{namespace}_version._commit; \"\"\".format( namespace=namespace ) ).strip() @pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def test_file_without_id(repo, tmpdir, namespace): runner",
"\"for item in data:\\n\" ' yield {\"just_name\": item[\"name\"]}' ), [ {\"just_name\": \"Gin\"}, {\"just_name\":",
"{\"product_id\": 2, \"name\": \"Tonic 2\"}, {\"product_id\": 3, \"name\": \"Rum Pony\"}, ] ), \"utf-8\",",
"\"\"\".format( namespace=namespace or \"item\" ) ) ) assert changed == [ {\"product_id\": 1,",
"5, }, { \"_id\": 2, \"_item\": \"Tonic 2\", \"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\":",
") ) assert changed == [ {\"product_id\": 1, \"version\": 1, \"column_name\": \"name\"}, {\"product_id\":",
"TEXT\\n\" \");\\n\" \"CREATE UNIQUE INDEX [idx_namespaces_name]\\n\" \" ON [namespaces] ([name]);\\n\" \"CREATE TABLE [commits]",
"db_path = str(tmpdir / \"db.db\") result = runner.invoke( cli, [ \"file\", db_path, str(repo",
"\"Gin\", \"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\": 5, }, { \"_id\": 2, \"_item\": \"Tonic\",",
"str(repo), \"--id\", \"product_id\", ] + ([\"--namespace\", namespace] if namespace else []), ) assert",
"tmpdir, namespace): runner = CliRunner() db_path = str(tmpdir / \"db.db\") with runner.isolated_filesystem(): options",
"] ), \"utf-8\", ) subprocess.call(git_commit + [\"-a\", \"-m\", \"another\"], cwd=str(repo)) result2 = runner.invoke(",
"assert db[\"item\"].schema == expected_schema @pytest.mark.parametrize( \"convert,expected_rows\", ( ( \"json.loads(content.upper())\", [ {\"PRODUCT_ID\": 1, \"NAME\":",
"test_file_without_id(repo, tmpdir, namespace): runner = CliRunner() db_path = str(tmpdir / \"db.db\") with runner.isolated_filesystem():",
"= CliRunner() db_path = str(tmpdir / \"db.db\") with runner.isolated_filesystem(): options = [\"file\", db_path,",
"3, \"_version\": 1, \"name\": \"Rum\"}, {\"_item\": 3, \"product_id\": None, \"_version\": 2, \"name\": \"Rum",
"\"product_id\"], }, { \"_version\": 2, \"product_id\": None, \"name\": \"Tonic 2\", \"_changed_columns\": [\"name\"], },",
"options] db_path = str(tmpdir / \"db.db\") result = runner.invoke( cli, [ \"file\", db_path,",
"{\"product_id\": 3, \"version\": 1, \"column_name\": \"name\"}, {\"product_id\": 3, \"version\": 1, \"column_name\": \"product_id\"}, ]",
"\"fire\", }, { \"IncidentID\": \"cde448\", \"Location\": \"555 West Example Drive\", \"Type\": \"medical\", },",
"[_commit_] TEXT, [rowid_] INTEGER, [_commit] INTEGER); CREATE UNIQUE INDEX [idx_item__item_id] ON [item] ([_item_id]);",
"TEXT\\n\" \");\" ) assert db[\"commits\"].count == 2 # Should have some duplicates assert",
"= CliRunner() db_path = str(tmpdir / \"db.db\") runner.invoke( cli, [ \"file\", db_path, str(repo",
"\"3\"]), ([\"--skip\", 0], [\"2\", \"3\"]), ([\"--skip\", 0, \"--skip\", 2], [\"3\"]), ([\"--start-at\", 2], [\"2\",",
"REFERENCES [namespaces]([id]), [name] TEXT ); CREATE UNIQUE INDEX [idx_columns_namespace_name] ON [columns] ([namespace], [name]);",
"runner.invoke( cli, [ \"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo), \"--convert\", convert, ],",
"{\"just_name\": \"Gin\"}, {\"just_name\": \"<NAME>\"}, {\"just_name\": \"Rum\"}, ], ), ), ) def test_convert(repo, tmpdir,",
") ] assert item_version == [ {\"product_id\": 1, \"_version\": 1, \"name\": \"Gin\"}, {\"product_id\":",
"result.exit_code == 0 db = sqlite_utils.Database(db_path) actual_text = [r[\"text\"] for r in db[\"item_version\"].rows]",
"db.query( \"select _item, product_id, _version, name from {}_version order by _item, _version\".format( namespace",
"3, \"product_id\": 3, \"_version\": 1, \"name\": \"Rum\"}, {\"_item\": 3, \"product_id\": None, \"_version\": 2,",
"( [id] INTEGER PRIMARY KEY, [namespace] INTEGER REFERENCES [namespaces]([id]), [name] TEXT ); CREATE",
"2\"}, {\"PRODUCT_ID\": 3, \"NAME\": \"RUM\"}, ], ), # Generator ( ( \"data =",
"+ ([\"--namespace\", namespace] if namespace else []), ) assert result.exit_code == 0 db",
"{\"just_name\": \"Rum\"}, ], ), ), ) def test_convert(repo, tmpdir, convert, expected_rows): runner =",
"(\\n\" \" [id] INTEGER PRIMARY KEY,\\n\" \" [name] TEXT\\n\" \");\\n\" \"CREATE UNIQUE INDEX",
"# product_id is None because it did not change here {\"product_id\": None, \"_version\":",
"from columns where id in ( select column from {namespace}_changed where item_version =",
"Rum Pony assert db[\"one_version\"].count == 5 assert db[\"two_version\"].count == 5 @pytest.mark.parametrize(\"namespace\", (None, \"custom\"))",
"json_group_array(name) from columns where id in ( select column from {namespace}_changed where item_version",
"namespace or \"item\" assert result.exit_code == 0 db = sqlite_utils.Database(db_path) item_version = [",
"\"Gin\"}, {\"_item\": 2, \"product_id\": 2, \"_version\": 1, \"name\": \"Tonic\"}, {\"_item\": 2, \"product_id\": None,",
"\"_commit\": \"commit1\", \"rowid\": 6, }, { \"_id\": 3, \"_item\": \"Rum\", \"_version\": \"v1\", \"_commit\":",
"], catch_exceptions=False, ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) expected_schema = (",
"\"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo), \"--convert\", convert, ], catch_exceptions=False, ) assert",
"else []), ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) item_table = namespace",
"# This line has changed from \"Rum\" to \"Rum Pony\": {\"product_id\": 3, \"name\":",
"\"Tonic\"}, {\"_item\": 2, \"product_id\": None, \"_version\": 2, \"name\": \"Tonic 2\"}, {\"_item\": 3, \"product_id\":",
"= sqlite_utils.Database(db_path) assert ( db.schema == textwrap.dedent( \"\"\" CREATE TABLE [namespaces] ( [id]",
"[ \"file\", db_path, str(repo / \"trees.csv\"), \"--repo\", str(repo), \"--dialect\", dialect, ], catch_exceptions=False, )",
"\"--repo\", str(repo), \"--dialect\", dialect, ], catch_exceptions=False, ) assert result.exit_code == 0 db =",
"TEXT , [TreeID] TEXT, [name] TEXT, [_commit] INTEGER); CREATE UNIQUE INDEX [idx_item__item_id] ON",
"\"--csv\", \"--full-versions\", ], catch_exceptions=False, ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) assert",
"[commits] ([namespace], [hash]); CREATE TABLE [{namespace}] ( [_id] INTEGER PRIMARY KEY, [_item_id] TEXT",
"{\"just_name\": \"<NAME>\"}, {\"just_name\": \"Rum\"}, ], ), ), ) def test_convert(repo, tmpdir, convert, expected_rows):",
"item[\"name\"]}' ), [ {\"just_name\": \"Gin\"}, {\"just_name\": \"Tonic\"}, {\"just_name\": \"Gin\"}, {\"just_name\": \"<NAME>\"}, {\"just_name\": \"Rum\"},",
"CREATE TABLE [{namespace}_version] ( [_id] INTEGER PRIMARY KEY, [_item] INTEGER REFERENCES [{namespace}]([_id]), [_version]",
"\"name\": \"Tonic 2\", }, { \"product_id\": 3, \"name\": \"Rum\", }, ] ), \"utf-8\",",
") assert result.exit_code == 0 db = sqlite_utils.Database(db_path) rows = [{k: v for",
"expected_rows def test_convert_xml(repo, tmpdir): runner = CliRunner() (repo / \"items.xml\").write_text( \"\"\" <items> <item",
"TEXT, [rowid_] INTEGER, [_commit] INTEGER); CREATE UNIQUE INDEX [idx_item__item_id] ON [item] ([_item_id]); CREATE",
"of 4th and Vermont\", \"Type\": \"fire\", }, { \"IncidentID\": \"cde448\", \"Location\": \"555 West",
"CliRunner() db_path = str(tmpdir / \"db.db\") runner.invoke( cli, [ \"file\", db_path, str(repo /",
"}, ] ), \"utf-8\", ) (repo_dir / \"items-with-banned-columns.json\").write_text( json.dumps( [ { \"_id_\": 1,",
"INTEGER PRIMARY KEY,\\n\" \" [_item] INTEGER REFERENCES [{}]([_id]),\\n\".format(item_table) + \" [_version] INTEGER,\\n\" \"",
"\"rowid\": 7, }, ] ), \"utf-8\", ) subprocess.call(git_commit + [\"-m\", \"second\", \"-a\"], cwd=str(repo_dir))",
"[name] TEXT, [_commit] INTEGER);\\n\" \"CREATE UNIQUE INDEX [idx_{}__item_id]\\n\".format(item_table) + \" ON [{}] ([_item_id]);\\n\".format(item_table)",
"v for k, v in r.items() if k != \"_commit\"} for r in",
"[hash]); CREATE TABLE [item] ( [_id] INTEGER PRIMARY KEY, [_item_id] TEXT , [TreeID]",
"on {namespace}._id = {namespace}_version._item order by {namespace}.product_id, {namespace}_version._version, columns.name \"\"\".format( namespace=namespace or \"item\"",
"db = sqlite_utils.Database(db_path) assert set(db.table_names()) == { \"namespaces\", \"commits\", \"one\", \"one_version\", \"columns\", \"one_changed\",",
"[_id] INTEGER PRIMARY KEY, [_item_id] TEXT , [TreeID] TEXT, [name] TEXT, [_commit] INTEGER);",
"\"custom\")) def test_file_with_id_full_versions(repo, tmpdir, namespace): runner = CliRunner() db_path = str(tmpdir / \"db.db\")",
"name from {}\".format(version_table) ) ] assert item_version == [ {\"product_id\": 1, \"_version\": 1,",
"\"v1\", \"_commit_\": \"commit1\", \"rowid_\": 6, }, { \"_id_\": 3, \"_item_\": \"Rum\", \"_version_\": \"v1\",",
"tmpdir, dialect, expected_schema): runner = CliRunner() db_path = str(tmpdir / \"db.db\") with runner.isolated_filesystem():",
"== 0 for namespace in (\"one\", \"two\"): run(namespace) # Now modify items.json, commit",
"TABLE [{namespace}_version] ( [_id] INTEGER PRIMARY KEY, [_item] INTEGER REFERENCES [{namespace}]([_id]), [_version] INTEGER,",
"== 0 db = sqlite_utils.Database(db_path) actual_text = [r[\"text\"] for r in db[\"item_version\"].rows] assert",
"in db.query( \"select _id_, _item_, _version_, _commit_, rowid_ from item_version\" ) ] assert",
"{ \"_id_\": 2, \"_item_\": \"Tonic\", \"_version_\": \"v1\", \"_commit_\": \"commit1\", \"rowid_\": 6, }, {",
"\"version\": 1, \"column_name\": \"product_id\"}, {\"product_id\": 2, \"version\": 2, \"column_name\": \"name\"}, {\"product_id\": 3, \"version\":",
"\"-a\"], cwd=str(repo_dir)) # Three more commits to test --skip for i in range(2,",
"PRIMARY KEY,\\n\" \" [_item] INTEGER REFERENCES [{}]([_id]),\\n\".format(item_table) + \" [_version] INTEGER,\\n\" \" [_commit]",
"\"_id_\": 2, \"_item_\": \"Tonic 2\", \"_version_\": \"v1\", \"_commit_\": \"commit1\", \"rowid_\": 6, }, {",
"1, \"name\": \"Rum\"}, {\"_item\": 3, \"product_id\": None, \"_version\": 2, \"name\": \"Rum Pony\"}, ]",
"\"product_id\"}, ] # Test the view view_rows = list( db.query( \"select _version, product_id,",
"{ \"_id\": 3, \"_item\": \"Rum\", \"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\": 7, }, ]",
"@pytest.mark.parametrize(\"use_wal\", (True, False)) def test_wal(repo, tmpdir, use_wal): runner = CliRunner() db_path = str(tmpdir",
"_id_, _item_, _version_, _commit_, rowid_ from item_version\" ) ] assert item_version == [",
"1, \"_item_\": \"Gin\", \"_version_\": \"v1\", \"_commit_\": \"commit1\", \"rowid_\": 5, }, { \"_id_\": 2,",
"r in db[namespace or \"item\"].rows] == [ (1, \"Gin\"), (2, \"Tonic\"), (1, \"Gin\"),",
"== [ { \"_id_\": 1, \"_item_\": \"Gin\", \"_version_\": \"v1\", \"_commit_\": \"commit1\", \"rowid_\": 5,",
"REFERENCES [namespaces]([id]),\\n\" \" [hash] TEXT,\\n\" \" [commit_at] TEXT\\n\" \");\\n\" \"CREATE UNIQUE INDEX [idx_commits_namespace_hash]\\n\"",
"select commits.commit_at as _commit_at, commits.hash as _commit_hash, {namespace}_version.*, ( select json_group_array(name) from columns",
"), [ {\"just_name\": \"Gin\"}, {\"just_name\": \"Tonic\"}, {\"just_name\": \"Gin\"}, {\"just_name\": \"<NAME>\"}, {\"just_name\": \"Rum\"}, ],",
"([_item_id]); CREATE TABLE [item_version] ( [_id] INTEGER PRIMARY KEY, [_item] INTEGER REFERENCES [item]([_id]),",
"\"items.json\", \"items-with-reserved-columns.json\", \"items-with-banned-columns.json\", \"trees.csv\", \"trees.tsv\", \"increment.txt\", ], cwd=str(repo_dir), ) subprocess.call(git_commit + [\"-m\", \"first\"],",
"\"item\" assert result.exit_code == 0 db = sqlite_utils.Database(db_path) item_version = [ r for",
"for item in options] db_path = str(tmpdir / \"db.db\") result = runner.invoke( cli,",
"\"increment.txt\").write_text(str(i), \"utf-8\") subprocess.call( git_commit + [\"-m\", \"increment {}\".format(i), \"-a\"], cwd=str(repo_dir) ) return repo_dir",
"\"select product_id, _version, name from {}\".format(version_table) ) ] assert item_version == [ {\"product_id\":",
"r[\"name\"]) for r in db[namespace or \"item\"].rows] == [ (1, \"Gin\"), (2, \"Tonic\"),",
"[name] TEXT\\n\" \");\\n\" + expected_create_view(namespace or \"item\") + \"\\nCREATE INDEX [idx_{}__item]\\n\".format(version_table) + \"",
"runner.invoke( cli, [ \"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo), \"--id\", \"product_id\", \"--full-versions\",",
"{\"product_id\": 1, \"version\": 1, \"column_name\": \"product_id\"}, {\"product_id\": 2, \"version\": 1, \"column_name\": \"name\"}, {\"product_id\":",
"def make_repo(tmpdir): repo_dir = tmpdir / \"repo\" repo_dir.mkdir() # This one is used",
"[{namespace}]([_id]), [_version] INTEGER, [_commit] INTEGER REFERENCES [commits]([id]), [product_id] INTEGER, [name] TEXT, [_item_full_hash] TEXT",
"try again (repo / \"items.json\").write_text( json.dumps( [ {\"product_id\": 1, \"name\": \"Gin\"}, {\"product_id\": 2,",
"\"<NAME>\"}, {\"just_name\": \"Rum\"}, ], ), ), ) def test_convert(repo, tmpdir, convert, expected_rows): runner",
"order by {namespace}.product_id, {namespace}_version._version, columns.name \"\"\".format( namespace=namespace or \"item\" ) ) ) assert",
"@pytest.mark.parametrize( \"convert,expected_rows\", ( ( \"json.loads(content.upper())\", [ {\"PRODUCT_ID\": 1, \"NAME\": \"GIN\"}, {\"PRODUCT_ID\": 2, \"NAME\":",
"file), \"--repo\", str(repo), \"--id\", \"TreeID\", \"--csv\", \"--full-versions\", ], catch_exceptions=False, ) assert result.exit_code ==",
"( db.schema == textwrap.dedent( \"\"\" CREATE TABLE [namespaces] ( [id] INTEGER PRIMARY KEY,",
"expected_schema = ( textwrap.dedent( \"\"\" CREATE TABLE [namespaces] ( [id] INTEGER PRIMARY KEY,",
"[{}] (\\n\".format(item_table) + \" [_id] INTEGER PRIMARY KEY,\\n\" \" [_item_id] TEXT\\n\" \", [product_id]",
"# Rewrite options to replace integers with the corresponding commit hash options =",
"namespace=namespace ) ).strip() @pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def test_file_without_id(repo, tmpdir, namespace): runner = CliRunner()",
"/ \"reserved.db\") with runner.isolated_filesystem(): result = runner.invoke( cli, [ \"file\", db_path, str(repo /",
"[\"-m\", \"items.xml\"], cwd=str(repo)) db_path = str(tmpdir / \"db.db\") result = runner.invoke( cli, [",
"\"items-with-banned-columns.json\").write_text( json.dumps( [ { \"_id_\": 1, \"_version_\": \"Gin\", } ] ), \"utf-8\", )",
"\"Rum\" to \"Rum Pony\": {\"product_id\": 3, \"name\": \"Rum Pony\"}, ] ), \"utf-8\", )",
");\"\"\" ) + \"\\n\" + expected_create_view(\"item\") + \"\\nCREATE INDEX [idx_item_version__item]\\n\" \" ON [item_version]",
"0 db = sqlite_utils.Database(db_path) assert db.schema == ( \"CREATE TABLE [namespaces] (\\n\" \"",
"-> Rum Pony assert db[\"one_version\"].count == 5 assert db[\"two_version\"].count == 5 @pytest.mark.parametrize(\"namespace\", (None,",
"{\"product_id\": 3, \"_version\": 1, \"name\": \"Rum\"}, ] changed = list( db.query( \"\"\" select",
"options.append(\"--wal\") result = runner.invoke( cli, options, catch_exceptions=False, ) assert result.exit_code == 0 db",
"actual_text = [r[\"text\"] for r in db[\"item_version\"].rows] assert actual_text == expected_texts def test_reserved_columns_are_reserved(tmpdir,",
"2\", \"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\": 6, }, { \"_id\": 3, \"_item\": \"Rum\",",
"[name] TEXT );\"\"\" ).strip() + \"\\n\" + expected_create_view(\"item\") + \"\\nCREATE INDEX [idx_item_version__item]\\n\" \"",
"\"_item\": \"Tonic\", \"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\": 6, }, ] ), \"utf-8\", )",
"{\"PRODUCT_ID\": 3, \"NAME\": \"RUM\"}, ], ), # Generator ( ( \"data = json.loads(content)\\n\"",
"\"name\": \"Gin\"}, {\"product_id\": 2, \"name\": \"Tonic 2\"}, {\"product_id\": 3, \"name\": \"Rum Pony\"}, ]",
"[item_version] INTEGER REFERENCES [{namespace}_version]([_id]), [column] INTEGER REFERENCES [columns]([id]), PRIMARY KEY ([item_version], [column]) );",
"here {\"product_id\": None, \"_version\": 2, \"name\": \"Tonic 2\"}, {\"product_id\": 3, \"_version\": 1, \"name\":",
"db[\"commits\"].count == 2 # Should have no duplicates item_version = [ r for",
"\"--namespace\", namespace, ], ) assert result.exit_code == 0 for namespace in (\"one\", \"two\"):",
"INDEX [idx_{namespace}_version__item] ON [{namespace}_version] ([_item]); \"\"\".strip().format( namespace=namespace or \"item\", view=expected_create_view(namespace or \"item\"), )",
"db_path, str(repo / \"items.json\"), \"--repo\", str(repo), \"--id\", \"product_id\", ], ) # Find all",
"\"utf-8\", ) subprocess.call(git_commit + [\"-m\", \"second\", \"-a\"], cwd=str(repo_dir)) # Three more commits to",
"[_id_] INTEGER, [_item_] TEXT, [_version_] TEXT, [_commit_] TEXT, [rowid_] INTEGER, [_commit] INTEGER); CREATE",
"== textwrap.dedent( \"\"\" CREATE TABLE [namespaces] ( [id] INTEGER PRIMARY KEY, [name] TEXT",
"\"commit1\", \"rowid\": 7, }, ] ), \"utf-8\", ) subprocess.call(git_commit + [\"-m\", \"second\", \"-a\"],",
"\"_id\": 3, \"_item\": \"Rum\", \"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\": 7, }, ] ),",
"\"db.db\") result = runner.invoke( cli, [ \"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo),",
"1, \"product_id\": 2, \"name\": \"Tonic\", \"_changed_columns\": [\"name\", \"product_id\"], }, { \"_version\": 2, \"product_id\":",
"[idx_namespaces_name]\\n\" \" ON [namespaces] ([name]);\\n\" \"CREATE TABLE [commits] (\\n\" \" [id] INTEGER PRIMARY",
"[{}] ([_item_id]);\\n\".format(item_table) + \"CREATE TABLE [{}] (\\n\".format(version_table) + \" [_id] INTEGER PRIMARY KEY,\\n\"",
"column.startswith(\"_\") and not column.endswith(\"_\"): with_prefix.add(column) assert with_prefix == set(RESERVED) @pytest.mark.parametrize(\"use_wal\", (True, False)) def",
"run(namespace) db = sqlite_utils.Database(db_path) assert set(db.table_names()) == { \"namespaces\", \"commits\", \"one\", \"one_version\", \"columns\",",
"in (\"one\", \"two\"): run(namespace) db = sqlite_utils.Database(db_path) assert set(db.table_names()) == { \"namespaces\", \"commits\",",
"view_rows == [ { \"_version\": 1, \"product_id\": 1, \"name\": \"Gin\", \"_changed_columns\": [\"name\", \"product_id\"],",
"\"Tonic\", }, ] ), \"utf-8\", ) (repo_dir / \"items-with-reserved-columns.json\").write_text( json.dumps( [ { \"_id\":",
"== [ { \"_version\": 1, \"product_id\": 1, \"name\": \"Gin\", \"_changed_columns\": [\"name\", \"product_id\"], },",
"/ \"items.json\"), \"--repo\", str(repo), \"--id\", \"product_id\", \"--namespace\", namespace, ], ) assert result.exit_code ==",
"so fix that for row in view_rows: row[\"_changed_columns\"] = list(sorted(json.loads(row[\"_changed_columns\"]))) assert view_rows ==",
"\"add\", \"incidents.json\", \"items.json\", \"items-with-reserved-columns.json\", \"items-with-banned-columns.json\", \"trees.csv\", \"trees.tsv\", \"increment.txt\", ], cwd=str(repo_dir), ) subprocess.call(git_commit +",
"options) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) assert db.schema == ( \"CREATE",
"(1, \"Gin\"), (2, \"Tonic\"), (1, \"Gin\"), (2, \"Tonic 2\"), (3, \"Rum\"), ] @pytest.mark.parametrize(\"namespace\",",
"{namespace}_version._id join {namespace} on {namespace}._id = {namespace}_version._item order by {namespace}.product_id, {namespace}_version._version, columns.name \"\"\".format(",
"\"incidents.json\").write_text( json.dumps( [ { \"IncidentID\": \"abc123\", \"Location\": \"Corner of 4th and Vermont\", \"Type\":",
"from {namespace}_changed where item_version = {namespace}_version._id ) ) as _changed_columns from {namespace}_version join",
"db.query( \"\"\" select {namespace}.product_id, {namespace}_version._version as version, columns.name as column_name from {namespace}_changed join",
"for r in db.query( \"select _item, product_id, _version, name from {}_version order by",
"on {namespace}_changed.item_version = {namespace}_version._id join {namespace} on {namespace}._id = {namespace}_version._item order by {namespace}.product_id,",
"\"Corner of 4th and Vermont\", \"Type\": \"fire\", }, { \"IncidentID\": \"cde448\", \"Location\": \"555",
"\"\"\" CREATE TABLE [namespaces] ( [id] INTEGER PRIMARY KEY, [name] TEXT ); CREATE",
"== 0 item_version2 = [ r for r in db.query( \"select _item, product_id,",
"\"rowid\": 5, }, { \"_id\": 2, \"_item\": \"Tonic 2\", \"_version\": \"v1\", \"_commit\": \"commit1\",",
"CREATE TABLE [{namespace}_changed] ( [item_version] INTEGER REFERENCES [{namespace}_version]([_id]), [column] INTEGER REFERENCES [columns]([id]), PRIMARY",
"[\"2\", \"3\"]), ([\"--start-after\", 2], [\"3\"]), ([\"--start-at\", 3], [\"3\"]), ([\"--start-after\", 3], []), ), )",
"Test the view view_rows = list( db.query( \"select _version, product_id, name, _changed_columns from",
"None, \"name\": \"Tonic 2\", \"_changed_columns\": [\"name\"], }, { \"_version\": 1, \"product_id\": 3, \"name\":",
"UNIQUE INDEX [idx_item__item_id] ON [item] ([_item_id]); CREATE TABLE [item_version] ( [_id] INTEGER PRIMARY",
"2, \"name\": \"Tonic 2\"}, {\"_item\": 3, \"product_id\": 3, \"_version\": 1, \"name\": \"Rum\"}, {\"_item\":",
"\"CREATE UNIQUE INDEX [idx_{}__item_id]\\n\".format(item_table) + \" ON [{}] ([_item_id]);\\n\".format(item_table) + \"CREATE TABLE [{}]",
"\" [name] TEXT\\n\" \");\\n\" + expected_create_view(namespace or \"item\") + \"\\nCREATE INDEX [idx_{}__item]\\n\".format(version_table) +",
"[_commit] INTEGER REFERENCES [commits]([id]), [TreeID] TEXT, [name] TEXT );\"\"\" ).strip() + \"\\n\" +",
"5 @pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def test_file_with_id_full_versions(repo, tmpdir, namespace): runner = CliRunner() db_path =",
"\"name\": \"Rum\", }, ] ), \"utf-8\", ) (repo_dir / \"items-with-reserved-columns.json\").write_text( json.dumps( [ {",
"REFERENCES [{}]([_id]),\\n\".format(item_table) + \" [_version] INTEGER,\\n\" \" [_commit] INTEGER REFERENCES [commits]([id]),\\n\" \" [product_id]",
"[idx_{namespace}__item_id] ON [{namespace}] ([_item_id]); CREATE TABLE [{namespace}_version] ( [_id] INTEGER PRIMARY KEY, [_item]",
"git_history.cli import cli from git_history.utils import RESERVED import itertools import json import pytest",
"), ) def test_skip_options(repo, tmpdir, options, expected_texts): runner = CliRunner() commits = list(",
"3, \"_version\": 1, \"name\": \"Rum\"}, ] # Now we edit, commit and try",
"\"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\": 7, }, ] ), \"utf-8\", ) subprocess.call(git_commit +",
"\"--convert\", textwrap.dedent( \"\"\" tree = xml.etree.ElementTree.fromstring(content) return [el.attrib for el in tree.iter(\"item\")] \"\"\"",
"], ) # Find all columns with _ prefixes and no suffix db",
"\"rowid\": 5, }, { \"_id\": 2, \"_item\": \"Tonic\", \"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\":",
"\"_version\": 2, \"name\": \"Rum Pony\"}, ] def test_file_with_id_resume_two_namespaces(repo, tmpdir): # https://github.com/simonw/git-history/issues/43 runner =",
"with_prefix.add(column) assert with_prefix == set(RESERVED) @pytest.mark.parametrize(\"use_wal\", (True, False)) def test_wal(repo, tmpdir, use_wal): runner",
"INDEX [idx_columns_namespace_name] ON [columns] ([namespace], [name]); CREATE TABLE [{namespace}_changed] ( [item_version] INTEGER REFERENCES",
"db = sqlite_utils.Database(db_path) item_version = [ r for r in db.query( \"select product_id,",
"with the corresponding commit hash options = [commits[item] if isinstance(item, int) else item",
"REFERENCES [{namespace}]([_id]), [_version] INTEGER, [_commit] INTEGER REFERENCES [commits]([id]), [product_id] INTEGER, [name] TEXT, [_item_full_hash]",
"\"utf-8\", ) (repo_dir / \"items-with-banned-columns.json\").write_text( json.dumps( [ { \"_id_\": 1, \"_version_\": \"Gin\", }",
"\"utf-8\", ) (repo_dir / \"trees.tsv\").write_text( \"TreeID\\tname\\n1\\tSophia\\n2\\tCharlie\", \"utf-8\", ) (repo_dir / \"increment.txt\").write_text(\"1\", \"utf-8\") subprocess.call([\"git\",",
"\"Location\": \"555 West Example Drive\", \"Type\": \"medical\", }, ] ), \"utf-8\", ) (repo_dir",
"@pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def test_file_with_id(repo, tmpdir, namespace): runner = CliRunner() db_path = str(tmpdir",
").strip() @pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def test_file_without_id(repo, tmpdir, namespace): runner = CliRunner() db_path =",
"\" ON [commits] ([namespace], [hash]);\\n\" \"CREATE TABLE [{}] (\\n\".format(item_table) + \" [_id] INTEGER",
"2, \"_item\": \"Tonic\", \"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\": 6, }, ] ), \"utf-8\",",
"1, \"product_id\": 3, \"name\": \"Rum\", \"_changed_columns\": [\"name\", \"product_id\"], }, ] @pytest.mark.parametrize(\"namespace\", (None, \"custom\"))",
"\"Rum\", \"_changed_columns\": [\"name\", \"product_id\"], }, ] @pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def test_file_with_id_resume(repo, tmpdir, namespace):",
"\"--id\", \"product_id\", ] + ([\"--namespace\", namespace] if namespace else []), catch_exceptions=False, ) assert",
"}, { \"_id\": 3, \"_item\": \"Rum\", \"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\": 7, },",
"TEXT );\"\"\" ).strip() + \"\\n\" + expected_create_view(\"item\") + \"\\nCREATE INDEX [idx_item_version__item]\\n\" \" ON",
"by Cog: (repo_dir / \"incidents.json\").write_text( json.dumps( [ { \"IncidentID\": \"abc123\", \"Location\": \"Corner of",
"0], [\"2\", \"3\"]), ([\"--skip\", 0, \"--skip\", 2], [\"3\"]), ([\"--start-at\", 2], [\"2\", \"3\"]), ([\"--start-after\",",
"# Now we edit, commit and try again (repo / \"items.json\").write_text( json.dumps( [",
"subprocess.call([\"git\", \"add\", \"items.xml\"], cwd=str(repo)) subprocess.call(git_commit + [\"-m\", \"items.xml\"], cwd=str(repo)) db_path = str(tmpdir /",
"runner = CliRunner() (repo / \"items.xml\").write_text( \"\"\" <items> <item name=\"one\" value=\"1\" /> <item",
"str(tmpdir / \"db.db\") options = [ \"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo),",
"\"commit1\", \"rowid\": 5, }, { \"_id\": 2, \"_item\": \"Tonic\", \"_version\": \"v1\", \"_commit\": \"commit1\",",
"to replace integers with the corresponding commit hash options = [commits[item] if isinstance(item,",
"name, _changed_columns from {}_version_detail\".format( namespace or \"item\" ) ) ) # Sort order",
"\"Rum\"}, {\"_item\": 3, \"product_id\": None, \"_version\": 2, \"name\": \"Rum Pony\"}, ] def test_file_with_id_resume_two_namespaces(repo,",
"\"two\"): run(namespace) # Now modify items.json, commit and run again (repo / \"items.json\").write_text(",
"\"select _item, product_id, _version, name from {}_version order by _item, _version\".format( namespace )",
"if namespace else []), ) namespace = namespace or \"item\" assert result.exit_code ==",
"row in view_rows: row[\"_changed_columns\"] = list(sorted(json.loads(row[\"_changed_columns\"]))) assert view_rows == [ { \"_version\": 1,",
"\"_version\": 1, \"name\": \"Tonic\"}, {\"_item\": 2, \"product_id\": None, \"_version\": 2, \"name\": \"Tonic 2\"},",
"\"item\", view=expected_create_view(namespace or \"item\"), ) assert db[\"commits\"].count == 2 # Should have no",
"options, catch_exceptions=False, ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) actual_text = [r[\"text\"]",
"[el.attrib for el in tree.iter(\"item\")] \"\"\" ), \"--import\", \"xml.etree.ElementTree\", ], catch_exceptions=False, ) assert",
"\"name\"}, {\"product_id\": 1, \"version\": 1, \"column_name\": \"product_id\"}, {\"product_id\": 2, \"version\": 1, \"column_name\": \"name\"},",
"\"_version\": 2, \"product_id\": None, \"name\": \"Tonic 2\", \"_changed_columns\": [\"name\"], }, { \"_version\": 1,",
"TEXT, [rowid_] INTEGER );\"\"\" ) + \"\\n\" + expected_create_view(\"item\") + \"\\nCREATE INDEX [idx_item_version__item]\\n\"",
"KEY, [_item_id] TEXT , [_id_] INTEGER, [_item_] TEXT, [_version_] TEXT, [_commit_] TEXT, [rowid_]",
"1, \"name\": \"Rum\"}, ] def test_file_with_reserved_columns(repo, tmpdir): runner = CliRunner() db_path = str(tmpdir",
"edit, commit and try again (repo / \"items.json\").write_text( json.dumps( [ {\"product_id\": 1, \"name\":",
"INTEGER, [_item_] TEXT, [_version_] TEXT, [_commit_] TEXT, [rowid_] INTEGER );\"\"\" ) + \"\\n\"",
"cli, [ \"file\", db_path, str(repo / \"items-with-reserved-columns.json\"), \"--repo\", str(repo), \"--id\", \"_id\", \"--full-versions\", ],",
"\"init\"], cwd=str(repo_dir)) subprocess.call( [ \"git\", \"add\", \"incidents.json\", \"items.json\", \"items-with-reserved-columns.json\", \"items-with-banned-columns.json\", \"trees.csv\", \"trees.tsv\", \"increment.txt\",",
"3, \"_version\": 1, \"name\": \"Rum\"}, ] changed = list( db.query( \"\"\" select {namespace}.product_id,",
") (repo_dir / \"increment.txt\").write_text(\"1\", \"utf-8\") subprocess.call([\"git\", \"init\"], cwd=str(repo_dir)) subprocess.call( [ \"git\", \"add\", \"incidents.json\",",
"= list( reversed( subprocess.check_output([\"git\", \"log\", \"--pretty=format:%H\"], cwd=str(repo)) .decode(\"utf-8\") .split(\"\\n\") ) ) assert len(commits)",
"\"product_id\": 2, \"_version\": 1, \"name\": \"Tonic\"}, {\"_item\": 2, \"product_id\": None, \"_version\": 2, \"name\":",
"str(repo), \"--convert\", '[{\"id\": 1, \"text\": content.decode(\"utf-8\")}]', \"--id\", \"id\", ] + options, catch_exceptions=False, )",
"\"trees.tsv\")) def test_csv_tsv(repo, tmpdir, file): runner = CliRunner() db_path = str(tmpdir / \"db.db\")",
"RESERVED import itertools import json import pytest import subprocess import sqlite_utils import textwrap",
"not change here {\"product_id\": None, \"_version\": 2, \"name\": \"Tonic 2\"}, {\"product_id\": 3, \"_version\":",
"\"v1\", \"_commit\": \"commit1\", \"rowid\": 5, }, { \"_id\": 2, \"_item\": \"Tonic 2\", \"_version\":",
"assert result.exit_code == 0 db = sqlite_utils.Database(db_path) expected_schema = ( textwrap.dedent( \"\"\" CREATE",
"\"_commit_\": \"commit1\", \"rowid_\": 5, }, { \"_id_\": 2, \"_item_\": \"Tonic\", \"_version_\": \"v1\", \"_commit_\":",
"+ expected_create_view(\"item\") + \"\\nCREATE INDEX [idx_item_version__item]\\n\" \" ON [item_version] ([_item]);\" ) @pytest.mark.parametrize( \"dialect,expected_schema\",",
"assert view_rows == [ { \"_version\": 1, \"product_id\": 1, \"name\": \"Gin\", \"_changed_columns\": [\"name\",",
"from {}\".format(version_table) ) ] assert item_version == [ {\"product_id\": 1, \"_version\": 1, \"name\":",
"PRIMARY KEY, [_item_id] TEXT , [TreeID] TEXT, [name] TEXT, [_commit] INTEGER); CREATE UNIQUE",
"cli, options, catch_exceptions=False, ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) expected_journal_mode =",
"def test_csv_tsv(repo, tmpdir, file): runner = CliRunner() db_path = str(tmpdir / \"db.db\") with",
"0 db = sqlite_utils.Database(db_path) expected_journal_mode = \"wal\" if use_wal else \"delete\" assert db.journal_mode",
"\"version\": 1, \"column_name\": \"product_id\"}, ] # Test the view view_rows = list( db.query(",
"([namespace], [hash]); CREATE TABLE [item] ( [_id] INTEGER PRIMARY KEY, [_item_id] TEXT ,",
"), \"utf-8\", ) (repo_dir / \"items-with-reserved-columns.json\").write_text( json.dumps( [ { \"_id\": 1, \"_item\": \"Gin\",",
"\"name\": \"Gin\"}, {\"product_id\": 2, \"_version\": 1, \"name\": \"Tonic\"}, {\"product_id\": 2, \"_version\": 2, \"name\":",
"str(repo), \"--convert\", textwrap.dedent( \"\"\" tree = xml.etree.ElementTree.fromstring(content) return [el.attrib for el in tree.iter(\"item\")]",
"[ { \"_id\": 1, \"_item\": \"Gin\", \"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\": 5, },",
"runner = CliRunner() commits = list( reversed( subprocess.check_output([\"git\", \"log\", \"--pretty=format:%H\"], cwd=str(repo)) .decode(\"utf-8\") .split(\"\\n\")",
"1, \"column_name\": \"name\"}, {\"product_id\": 1, \"version\": 1, \"column_name\": \"product_id\"}, {\"product_id\": 2, \"version\": 1,",
"( [_id] INTEGER PRIMARY KEY, [_item] INTEGER REFERENCES [item]([_id]), [_version] INTEGER, [_commit] INTEGER",
"2, \"product_id\": None, \"_version\": 2, \"name\": \"Tonic 2\"}, {\"_item\": 3, \"product_id\": 3, \"_version\":",
"{\"product_id\": 2, \"version\": 1, \"column_name\": \"name\"}, {\"product_id\": 2, \"version\": 1, \"column_name\": \"product_id\"}, {\"product_id\":",
"\"--repo\", str(repo), \"--id\", \"TreeID\", \"--csv\", \"--full-versions\", ], catch_exceptions=False, ) assert result.exit_code == 0",
"TABLE [{namespace}] ( [_id] INTEGER PRIMARY KEY, [_item_id] TEXT , [product_id] INTEGER, [name]",
") assert result.exit_code == 0 db = sqlite_utils.Database(db_path) expected_journal_mode = \"wal\" if use_wal",
"[_id] INTEGER PRIMARY KEY, [_item_id] TEXT , [product_id] INTEGER, [name] TEXT, [_commit] INTEGER);",
"def test_file_without_id(repo, tmpdir, namespace): runner = CliRunner() db_path = str(tmpdir / \"db.db\") with",
"from {}_version_detail\".format( namespace or \"item\" ) ) ) # Sort order of _changed_columns",
"sqlite_utils.Database(db_path) item_version = [ r for r in db.query( \"select product_id, _version, name",
"1, \"column_name\": \"name\"}, {\"product_id\": 2, \"version\": 1, \"column_name\": \"product_id\"}, {\"product_id\": 2, \"version\": 2,",
"[item] ([_item_id]); CREATE TABLE [item_version] ( [_id] INTEGER PRIMARY KEY, [_item] INTEGER REFERENCES",
"{\"PRODUCT_ID\": 2, \"NAME\": \"TONIC\"}, {\"PRODUCT_ID\": 1, \"NAME\": \"GIN\"}, {\"PRODUCT_ID\": 2, \"NAME\": \"TONIC 2\"},",
"namespace or \"item\" version_table = \"{}_version\".format(item_table) assert db.schema == ( \"CREATE TABLE [namespaces]",
"\"TONIC\"}, {\"PRODUCT_ID\": 1, \"NAME\": \"GIN\"}, {\"PRODUCT_ID\": 2, \"NAME\": \"TONIC 2\"}, {\"PRODUCT_ID\": 3, \"NAME\":",
"INTEGER REFERENCES [namespaces]([id]), [name] TEXT ); CREATE UNIQUE INDEX [idx_columns_namespace_name] ON [columns] ([namespace],",
"\"name\"}, {\"product_id\": 2, \"version\": 1, \"column_name\": \"product_id\"}, {\"product_id\": 2, \"version\": 2, \"column_name\": \"name\"},",
"== 2 # Should have some duplicates assert [(r[\"product_id\"], r[\"name\"]) for r in",
"Gin, Tonic -> Tonic 2, Rum -> Rum Pony assert db[\"one_version\"].count == 5",
"\"Tonic 2\"}, {\"product_id\": 3, \"_version\": 1, \"name\": \"Rum\"}, ] # Now we edit,",
"def test_file_with_id_resume_two_namespaces(repo, tmpdir): # https://github.com/simonw/git-history/issues/43 runner = CliRunner() db_path = str(tmpdir / \"db.db\")",
"VIEW {namespace}_version_detail AS select commits.commit_at as _commit_at, commits.hash as _commit_hash, {namespace}_version.*, ( select",
"[_id] INTEGER PRIMARY KEY,\\n\" \" [_item] INTEGER REFERENCES [{}]([_id]),\\n\".format(item_table) + \" [_version] INTEGER,\\n\"",
"0 db = sqlite_utils.Database(db_path) expected_schema = ( textwrap.dedent( \"\"\" CREATE TABLE [namespaces] (",
"namespace = namespace or \"item\" assert result.exit_code == 0 db = sqlite_utils.Database(db_path) item_version",
"([_item_id]); CREATE TABLE [{namespace}_version] ( [_id] INTEGER PRIMARY KEY, [_item] INTEGER REFERENCES [{namespace}]([_id]),",
"namespace=namespace or \"item\", view=expected_create_view(namespace or \"item\"), ) assert db[\"commits\"].count == 2 # Should",
"INTEGER PRIMARY KEY, [_item] INTEGER REFERENCES [{namespace}]([_id]), [_version] INTEGER, [_commit] INTEGER REFERENCES [commits]([id]),",
"CREATE UNIQUE INDEX [idx_namespaces_name] ON [namespaces] ([name]); CREATE TABLE [commits] ( [id] INTEGER",
"tmpdir): # https://github.com/simonw/git-history/issues/43 runner = CliRunner() db_path = str(tmpdir / \"db.db\") def run(namespace):",
"options, expected_texts): runner = CliRunner() commits = list( reversed( subprocess.check_output([\"git\", \"log\", \"--pretty=format:%H\"], cwd=str(repo))",
"2, \"product_id\": None, \"name\": \"Tonic 2\", \"_changed_columns\": [\"name\"], }, { \"_version\": 1, \"product_id\":",
"1, \"text\": content.decode(\"utf-8\")}]', \"--id\", \"id\", ] + options, catch_exceptions=False, ) assert result.exit_code ==",
"/ \"increment.txt\").write_text(\"1\", \"utf-8\") subprocess.call([\"git\", \"init\"], cwd=str(repo_dir)) subprocess.call( [ \"git\", \"add\", \"incidents.json\", \"items.json\", \"items-with-reserved-columns.json\",",
"{ \"namespaces\", \"commits\", \"one\", \"one_version\", \"columns\", \"one_changed\", \"two\", \"two_version\", \"two_changed\", } # Should",
"assert item_version2 == [ {\"_item\": 1, \"product_id\": 1, \"_version\": 1, \"name\": \"Gin\"}, {\"_item\":",
"\"_commit\"} for r in db[\"item\"].rows] assert rows == expected_rows def test_convert_xml(repo, tmpdir): runner",
"result = runner.invoke(cli, options) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) assert db.schema",
"str(repo), \"--id\", \"product_id\", ] + ([\"--namespace\", namespace] if namespace else []), ) namespace",
"\"commit1\", \"rowid_\": 6, }, { \"_id_\": 3, \"_item_\": \"Rum\", \"_version_\": \"v1\", \"_commit_\": \"commit1\",",
"TEXT, [_commit] INTEGER); CREATE UNIQUE INDEX [idx_item__item_id] ON [item] ([_item_id]); CREATE TABLE [item_version]",
"_version\".format( namespace ) ) ] assert item_version2 == [ {\"_item\": 1, \"product_id\": 1,",
"make_repo(tmpdir) def expected_create_view(namespace): return textwrap.dedent( \"\"\" CREATE VIEW {namespace}_version_detail AS select commits.commit_at as",
"( [_id] INTEGER PRIMARY KEY, [_item_id] TEXT , [TreeID] TEXT, [name] TEXT, [_commit]",
"CliRunner from git_history.cli import cli from git_history.utils import RESERVED import itertools import json",
"2, \"NAME\": \"TONIC 2\"}, {\"PRODUCT_ID\": 3, \"NAME\": \"RUM\"}, ], ), # Generator (",
"/ \"db.db\") result = runner.invoke( cli, [ \"file\", db_path, str(repo / \"increment.txt\"), \"--repo\",",
"\"name\": \"Gin\"}, {\"product_id\": 2, \"_version\": 1, \"name\": \"Tonic\"}, # product_id is None because",
"https://github.com/simonw/git-history/issues/43 runner = CliRunner() db_path = str(tmpdir / \"db.db\") def run(namespace): result =",
"str(repo), ] if use_wal: options.append(\"--wal\") result = runner.invoke( cli, options, catch_exceptions=False, ) assert",
"[idx_{namespace}_version__item] ON [{namespace}_version] ([_item]); \"\"\".strip().format( namespace=namespace or \"item\", view=expected_create_view(namespace or \"item\"), ) assert",
"\"name\"}, {\"product_id\": 3, \"version\": 1, \"column_name\": \"product_id\"}, ] # Test the view view_rows",
"= CliRunner() db_path = str(tmpdir / \"db.db\") result = runner.invoke( cli, [ \"file\",",
"1, \"NAME\": \"GIN\"}, {\"PRODUCT_ID\": 2, \"NAME\": \"TONIC\"}, {\"PRODUCT_ID\": 1, \"NAME\": \"GIN\"}, {\"PRODUCT_ID\": 2,",
") (repo_dir / \"items-with-banned-columns.json\").write_text( json.dumps( [ { \"_id_\": 1, \"_version_\": \"Gin\", } ]",
"\"_version\": 1, \"name\": \"Rum\"}, {\"_item\": 3, \"product_id\": None, \"_version\": 2, \"name\": \"Rum Pony\"},",
"import subprocess import sqlite_utils import textwrap git_commit = [ \"git\", \"-c\", \"user.name='Tests'\", \"-c\",",
"--skip for i in range(2, 4): (repo_dir / \"increment.txt\").write_text(str(i), \"utf-8\") subprocess.call( git_commit +",
"str(repo / \"items.json\"), \"--repo\", str(repo), \"--id\", \"product_id\", ], ) # Find all columns",
"{}_version order by _item, _version\".format( namespace ) ) ] assert item_version2 == [",
"\"name\": \"Rum\"}, {\"_item\": 3, \"product_id\": None, \"_version\": 2, \"name\": \"Rum Pony\"}, ] def",
"INTEGER REFERENCES [{}]([_id]),\\n\".format(item_table) + \" [_version] INTEGER,\\n\" \" [_commit] INTEGER REFERENCES [commits]([id]),\\n\" \"",
"column_name from {namespace}_changed join columns on {namespace}_changed.column = columns.id join {namespace}_version on {namespace}_changed.item_version",
"TEXT, [_item_full_hash] TEXT ); CREATE TABLE [columns] ( [id] INTEGER PRIMARY KEY, [namespace]",
") return repo_dir @pytest.fixture def repo(tmpdir): return make_repo(tmpdir) def expected_create_view(namespace): return textwrap.dedent( \"\"\"",
"expected_rows): runner = CliRunner() db_path = str(tmpdir / \"db.db\") with runner.isolated_filesystem(): result =",
"== 0 db = sqlite_utils.Database(db_path) expected_journal_mode = \"wal\" if use_wal else \"delete\" assert",
"/ \"items.json\"), \"--repo\", str(repo), \"--id\", \"product_id\", ] + ([\"--namespace\", namespace] if namespace else",
"([name]);\\n\" \"CREATE TABLE [commits] (\\n\" \" [id] INTEGER PRIMARY KEY,\\n\" \" [namespace] INTEGER",
"because it did not change here {\"product_id\": None, \"_version\": 2, \"name\": \"Tonic 2\"},",
"1, \"_version\": 1, \"name\": \"Gin\"}, {\"product_id\": 2, \"_version\": 1, \"name\": \"Tonic\"}, {\"product_id\": 2,",
"(None, \"custom\")) def test_file_with_id_resume(repo, tmpdir, namespace): runner = CliRunner() db_path = str(tmpdir /",
"[item_version] ( [_id] INTEGER PRIMARY KEY, [_item] INTEGER REFERENCES [item]([_id]), [_version] INTEGER, [_commit]",
"\"\"\" select {namespace}.product_id, {namespace}_version._version as version, columns.name as column_name from {namespace}_changed join columns",
"TEXT, [_commit_] TEXT, [rowid_] INTEGER );\"\"\" ) + \"\\n\" + expected_create_view(\"item\") + \"\\nCREATE",
"\"product_id\"}, {\"product_id\": 2, \"version\": 1, \"column_name\": \"name\"}, {\"product_id\": 2, \"version\": 1, \"column_name\": \"product_id\"},",
"= sqlite_utils.Database(db_path) actual_text = [r[\"text\"] for r in db[\"item_version\"].rows] assert actual_text == expected_texts",
"tmpdir, namespace): runner = CliRunner() db_path = str(tmpdir / \"db.db\") result = runner.invoke(",
"\"db.db\") result = runner.invoke( cli, [ \"file\", db_path, str(repo / \"items.xml\"), \"--repo\", str(repo),",
"{\"rowid\"} for table in itertools.chain(db.tables, db.views): for column in table.columns_dict: if column.startswith(\"_\") and",
"cli, [ \"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo), \"--id\", \"product_id\", ], )",
"{\"product_id\": 2, \"_version\": 1, \"name\": \"Tonic\"}, {\"product_id\": 2, \"_version\": 2, \"name\": \"Tonic 2\"},",
"{ \"_id\": 2, \"_item\": \"Tonic\", \"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\": 6, }, ]",
"db[\"item\"].rows] assert rows == expected_rows def test_convert_xml(repo, tmpdir): runner = CliRunner() (repo /",
"[]), catch_exceptions=False, ) assert result2.exit_code == 0 item_version2 = [ r for r",
"+ ([\"--namespace\", namespace] if namespace else []), catch_exceptions=False, ) assert result2.exit_code == 0",
"\"rowid\": 6, }, ] ), \"utf-8\", ) (repo_dir / \"items-with-banned-columns.json\").write_text( json.dumps( [ {",
"); CREATE TABLE [columns] ( [id] INTEGER PRIMARY KEY, [namespace] INTEGER REFERENCES [namespaces]([id]),",
"\"increment.txt\").write_text(\"1\", \"utf-8\") subprocess.call([\"git\", \"init\"], cwd=str(repo_dir)) subprocess.call( [ \"git\", \"add\", \"incidents.json\", \"items.json\", \"items-with-reserved-columns.json\", \"items-with-banned-columns.json\",",
"ON [{}] ([_item_id]);\\n\".format(item_table) + \"CREATE TABLE [{}] (\\n\".format(version_table) + \" [_id] INTEGER PRIMARY",
"== [ {\"name\": \"one\", \"value\": \"1\"}, {\"name\": \"two\", \"value\": \"2\"}, ] @pytest.mark.parametrize( \"options,expected_texts\",",
"<item name=\"two\" value=\"2\" /> </items> \"\"\", \"utf-8\", ) subprocess.call([\"git\", \"add\", \"items.xml\"], cwd=str(repo)) subprocess.call(git_commit",
"\"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\": 5, }, { \"_id\": 2, \"_item\": \"Tonic 2\",",
"{\"product_id\": 1, \"_version\": 1, \"name\": \"Gin\"}, {\"product_id\": 2, \"_version\": 1, \"name\": \"Tonic\"}, #",
"\"--dialect\", dialect, ], catch_exceptions=False, ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) assert",
"\"item\") + \"\\nCREATE INDEX [idx_{}__item]\\n\".format(version_table) + \" ON [{}] ([_item]);\".format(version_table) ) assert db[\"commits\"].count",
"\"_version\": 1, \"product_id\": 2, \"name\": \"Tonic\", \"_changed_columns\": [\"name\", \"product_id\"], }, { \"_version\": 2,",
"\"CREATE TABLE [namespaces] (\\n\" \" [id] INTEGER PRIMARY KEY,\\n\" \" [name] TEXT\\n\" \");\\n\"",
"len(commits) == 4 # Rewrite options to replace integers with the corresponding commit",
"assert result.exit_code == 0 db = sqlite_utils.Database(db_path) expected_journal_mode = \"wal\" if use_wal else",
"{namespace}_version._item order by {namespace}.product_id, {namespace}_version._version, columns.name \"\"\".format( namespace=namespace or \"item\" ) ) )",
"catch_exceptions=False, ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) assert db[\"item\"].schema == expected_schema",
"commits = list( reversed( subprocess.check_output([\"git\", \"log\", \"--pretty=format:%H\"], cwd=str(repo)) .decode(\"utf-8\") .split(\"\\n\") ) ) assert",
"\"items.xml\"), \"--repo\", str(repo), \"--convert\", textwrap.dedent( \"\"\" tree = xml.etree.ElementTree.fromstring(content) return [el.attrib for el",
") def test_skip_options(repo, tmpdir, options, expected_texts): runner = CliRunner() commits = list( reversed(",
"\"column_name\": \"name\"}, {\"product_id\": 3, \"version\": 1, \"column_name\": \"product_id\"}, ] # Test the view",
"subprocess.check_output([\"git\", \"log\", \"--pretty=format:%H\"], cwd=str(repo)) .decode(\"utf-8\") .split(\"\\n\") ) ) assert len(commits) == 4 #",
"\"\"\" CREATE VIEW {namespace}_version_detail AS select commits.commit_at as _commit_at, commits.hash as _commit_hash, {namespace}_version.*,",
"1, \"name\": \"Tonic\"}, {\"_item\": 2, \"product_id\": None, \"_version\": 2, \"name\": \"Tonic 2\"}, {\"_item\":",
"for r in db[namespace or \"item\"].rows] == [ (1, \"Gin\"), (2, \"Tonic\"), (1,",
"PRIMARY KEY, [namespace] INTEGER REFERENCES [namespaces]([id]), [hash] TEXT, [commit_at] TEXT ); CREATE UNIQUE",
"or \"item\" ) ) ) assert changed == [ {\"product_id\": 1, \"version\": 1,",
"= runner.invoke( cli, [ \"file\", db_path, str(repo / \"items.xml\"), \"--repo\", str(repo), \"--convert\", textwrap.dedent(",
"{\"PRODUCT_ID\": 2, \"NAME\": \"TONIC 2\"}, {\"PRODUCT_ID\": 3, \"NAME\": \"RUM\"}, ], ), # Generator",
"namespace): runner = CliRunner() db_path = str(tmpdir / \"db.db\") with runner.isolated_filesystem(): result =",
"version, columns.name as column_name from {namespace}_changed join columns on {namespace}_changed.column = columns.id join",
"[column] INTEGER REFERENCES [columns]([id]), PRIMARY KEY ([item_version], [column]) ); {view} CREATE INDEX [idx_{namespace}_version__item]",
"one is used for the README generated by Cog: (repo_dir / \"incidents.json\").write_text( json.dumps(",
"[ r for r in db.query( \"select _id_, _item_, _version_, _commit_, rowid_ from",
"{namespace}_version join commits on commits.id = {namespace}_version._commit; \"\"\".format( namespace=namespace ) ).strip() @pytest.mark.parametrize(\"namespace\", (None,",
"select {namespace}.product_id, {namespace}_version._version as version, columns.name as column_name from {namespace}_changed join columns on",
"item_table = namespace or \"item\" version_table = \"{}_version\".format(item_table) assert db.schema == ( \"CREATE",
"subprocess.call([\"git\", \"init\"], cwd=str(repo_dir)) subprocess.call( [ \"git\", \"add\", \"incidents.json\", \"items.json\", \"items-with-reserved-columns.json\", \"items-with-banned-columns.json\", \"trees.csv\", \"trees.tsv\",",
"assert db[\"two_version\"].count == 5 @pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def test_file_with_id_full_versions(repo, tmpdir, namespace): runner =",
"2, \"name\": \"Tonic 2\"}, # This line has changed from \"Rum\" to \"Rum",
"_ prefixes and no suffix db = sqlite_utils.Database(db_path) with_prefix = {\"rowid\"} for table",
"[idx_commits_namespace_hash]\\n\" \" ON [commits] ([namespace], [hash]);\\n\" \"CREATE TABLE [{}] (\\n\".format(namespace or \"item\") +",
"use_wal): runner = CliRunner() db_path = str(tmpdir / \"db.db\") options = [ \"file\",",
"click.testing import CliRunner from git_history.cli import cli from git_history.utils import RESERVED import itertools",
"where id in ( select column from {namespace}_changed where item_version = {namespace}_version._id )",
"\"items.json\"), \"--repo\", str(repo), ] if use_wal: options.append(\"--wal\") result = runner.invoke( cli, options, catch_exceptions=False,",
"\"_item_\": \"Gin\", \"_version_\": \"v1\", \"_commit_\": \"commit1\", \"rowid_\": 5, }, { \"_id_\": 2, \"_item_\":",
"[{}] (\\n\".format(namespace or \"item\") + \" [product_id] INTEGER,\\n\" \" [name] TEXT\\n\" \");\" )",
"[ \"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo), \"--id\", \"product_id\", \"--namespace\", namespace, ],",
"], catch_exceptions=False, ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) assert ( db.schema",
"\"version\": 2, \"column_name\": \"name\"}, {\"product_id\": 3, \"version\": 1, \"column_name\": \"name\"}, {\"product_id\": 3, \"version\":",
"}, { \"_id_\": 2, \"_item_\": \"Tonic\", \"_version_\": \"v1\", \"_commit_\": \"commit1\", \"rowid_\": 6, },",
"\"rowid_\": 6, }, { \"_id_\": 2, \"_item_\": \"Tonic 2\", \"_version_\": \"v1\", \"_commit_\": \"commit1\",",
"\" [id] INTEGER PRIMARY KEY,\\n\" \" [name] TEXT\\n\" \");\\n\" \"CREATE UNIQUE INDEX [idx_namespaces_name]\\n\"",
"6, }, ] ), \"utf-8\", ) (repo_dir / \"items-with-banned-columns.json\").write_text( json.dumps( [ { \"_id_\":",
"TEXT , [product_id] INTEGER, [name] TEXT, [_commit] INTEGER); CREATE UNIQUE INDEX [idx_{namespace}__item_id] ON",
"[name]); CREATE TABLE [{namespace}_changed] ( [item_version] INTEGER REFERENCES [{namespace}_version]([_id]), [column] INTEGER REFERENCES [columns]([id]),",
"replace integers with the corresponding commit hash options = [commits[item] if isinstance(item, int)",
"[ \"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo), \"--id\", \"product_id\", ] + ([\"--namespace\",",
"Vermont\", \"Type\": \"fire\", }, { \"IncidentID\": \"cde448\", \"Location\": \"555 West Example Drive\", \"Type\":",
"\"increment.txt\", ], cwd=str(repo_dir), ) subprocess.call(git_commit + [\"-m\", \"first\"], cwd=str(repo_dir)) subprocess.call([\"git\", \"branch\", \"-m\", \"main\"],",
"db.query( \"select _id_, _item_, _version_, _commit_, rowid_ from item_version\" ) ] assert item_version",
"db_path, str(repo / \"items.json\"), \"--repo\", str(repo), \"--id\", \"product_id\", ] + ([\"--namespace\", namespace] if",
"# Should have some duplicates assert [(r[\"product_id\"], r[\"name\"]) for r in db[namespace or",
"1, \"name\": \"Tonic\"}, {\"product_id\": None, \"_version\": 2, \"name\": \"Tonic 2\"}, {\"product_id\": 3, \"_version\":",
"namespace] result = runner.invoke(cli, options) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) assert",
"value=\"2\" /> </items> \"\"\", \"utf-8\", ) subprocess.call([\"git\", \"add\", \"items.xml\"], cwd=str(repo)) subprocess.call(git_commit + [\"-m\",",
"6, }, { \"_id_\": 2, \"_item_\": \"Tonic 2\", \"_version_\": \"v1\", \"_commit_\": \"commit1\", \"rowid_\":",
"assert db[\"commits\"].count == 2 # Should have some duplicates assert [(r[\"product_id\"], r[\"name\"]) for",
"1, \"version\": 1, \"column_name\": \"name\"}, {\"product_id\": 1, \"version\": 1, \"column_name\": \"product_id\"}, {\"product_id\": 2,",
"str(tmpdir / \"db.db\") def run(namespace): result = runner.invoke( cli, [ \"file\", db_path, str(repo",
"\"Type\": \"fire\", }, { \"IncidentID\": \"cde448\", \"Location\": \"555 West Example Drive\", \"Type\": \"medical\",",
"}, ] @pytest.mark.parametrize(\"file\", (\"trees.csv\", \"trees.tsv\")) def test_csv_tsv(repo, tmpdir, file): runner = CliRunner() db_path",
"assert with_prefix == set(RESERVED) @pytest.mark.parametrize(\"use_wal\", (True, False)) def test_wal(repo, tmpdir, use_wal): runner =",
"(repo_dir / \"incidents.json\").write_text( json.dumps( [ { \"IncidentID\": \"abc123\", \"Location\": \"Corner of 4th and",
"2, \"version\": 2, \"column_name\": \"name\"}, {\"product_id\": 3, \"version\": 1, \"column_name\": \"name\"}, {\"product_id\": 3,",
"json.dumps( [ { \"product_id\": 1, \"name\": \"Gin\", }, { \"product_id\": 2, \"name\": \"Tonic",
") assert result2.exit_code == 0 item_version2 = [ r for r in db.query(",
"(repo / \"items.xml\").write_text( \"\"\" <items> <item name=\"one\" value=\"1\" /> <item name=\"two\" value=\"2\" />",
"\"utf-8\") subprocess.call([\"git\", \"init\"], cwd=str(repo_dir)) subprocess.call( [ \"git\", \"add\", \"incidents.json\", \"items.json\", \"items-with-reserved-columns.json\", \"items-with-banned-columns.json\", \"trees.csv\",",
"for k, v in r.items() if k != \"_commit\"} for r in db[\"item\"].rows]",
"TEXT, [commit_at] TEXT ); CREATE UNIQUE INDEX [idx_commits_namespace_hash] ON [commits] ([namespace], [hash]); CREATE",
"run(namespace) # Now modify items.json, commit and run again (repo / \"items.json\").write_text( json.dumps(",
"test_file_with_id_resume(repo, tmpdir, namespace): runner = CliRunner() db_path = str(tmpdir / \"db.db\") result =",
"@pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def test_file_without_id(repo, tmpdir, namespace): runner = CliRunner() db_path = str(tmpdir",
"import cli from git_history.utils import RESERVED import itertools import json import pytest import",
"we edit, commit and try again (repo / \"items.json\").write_text( json.dumps( [ {\"product_id\": 1,",
"row[\"_changed_columns\"] = list(sorted(json.loads(row[\"_changed_columns\"]))) assert view_rows == [ { \"_version\": 1, \"product_id\": 1, \"name\":",
"r for r in db.query( \"select product_id, _version, name from {}_version\".format(namespace) ) ]",
"2, \"version\": 1, \"column_name\": \"product_id\"}, {\"product_id\": 2, \"version\": 2, \"column_name\": \"name\"}, {\"product_id\": 3,",
"git_commit = [ \"git\", \"-c\", \"user.name='Tests'\", \"-c\", \"user.email='<EMAIL>'\", \"commit\", ] def make_repo(tmpdir): repo_dir",
"def test_convert_xml(repo, tmpdir): runner = CliRunner() (repo / \"items.xml\").write_text( \"\"\" <items> <item name=\"one\"",
"\"NAME\": \"TONIC\"}, {\"PRODUCT_ID\": 1, \"NAME\": \"GIN\"}, {\"PRODUCT_ID\": 2, \"NAME\": \"TONIC 2\"}, {\"PRODUCT_ID\": 3,",
"] def make_repo(tmpdir): repo_dir = tmpdir / \"repo\" repo_dir.mkdir() # This one is",
"ON [{namespace}] ([_item_id]); CREATE TABLE [{namespace}_version] ( [_id] INTEGER PRIMARY KEY, [_item] INTEGER",
"\"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\": 5, }, { \"_id\": 2, \"_item\": \"Tonic\", \"_version\":",
") ) # Sort order of _changed_columns JSON is undefined, so fix that",
"\"CREATE UNIQUE INDEX [idx_namespaces_name]\\n\" \" ON [namespaces] ([name]);\\n\" \"CREATE TABLE [commits] (\\n\" \"",
"else []), ) namespace = namespace or \"item\" assert result.exit_code == 0 db",
"= [ r for r in db.query( \"select _item, product_id, _version, name from",
"== set(RESERVED) @pytest.mark.parametrize(\"use_wal\", (True, False)) def test_wal(repo, tmpdir, use_wal): runner = CliRunner() db_path",
"[r[\"text\"] for r in db[\"item_version\"].rows] assert actual_text == expected_texts def test_reserved_columns_are_reserved(tmpdir, repo): runner",
"return repo_dir @pytest.fixture def repo(tmpdir): return make_repo(tmpdir) def expected_create_view(namespace): return textwrap.dedent( \"\"\" CREATE",
"r in db.query( \"select product_id, _version, name from {}_version\".format(namespace) ) ] assert item_version",
"CREATE UNIQUE INDEX [idx_commits_namespace_hash] ON [commits] ([namespace], [hash]); CREATE TABLE [item] ( [_id]",
"\"Tonic 2\", \"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\": 6, }, { \"_id\": 3, \"_item\":",
"== 0 db = sqlite_utils.Database(db_path) assert list(db[\"item\"].rows) == [ {\"name\": \"one\", \"value\": \"1\"},",
"\"v1\", \"_commit\": \"commit1\", \"rowid\": 5, }, { \"_id\": 2, \"_item\": \"Tonic\", \"_version\": \"v1\",",
"[_version] INTEGER, [_commit] INTEGER REFERENCES [commits]([id]), [product_id] INTEGER, [name] TEXT, [_item_full_hash] TEXT );",
"product_id, _version, name from {}\".format(version_table) ) ] assert item_version == [ {\"product_id\": 1,",
"db[namespace or \"item\"].rows] == [ (1, \"Gin\"), (2, \"Tonic\"), (1, \"Gin\"), (2, \"Tonic",
") def test_csv_dialect(repo, tmpdir, dialect, expected_schema): runner = CliRunner() db_path = str(tmpdir /",
"= runner.invoke( cli, [ \"file\", db_path, str(repo / \"trees.csv\"), \"--repo\", str(repo), \"--dialect\", dialect,",
"{ \"IncidentID\": \"cde448\", \"Location\": \"555 West Example Drive\", \"Type\": \"medical\", }, ] ),",
"cli from git_history.utils import RESERVED import itertools import json import pytest import subprocess",
"= \"{}_version\".format(item_table) assert db.schema == \"\"\" CREATE TABLE [namespaces] ( [id] INTEGER PRIMARY",
") assert db[\"commits\"].count == 2 # Should have no duplicates item_version = [",
"\"Gin\", } ] ), \"utf-8\", ) (repo_dir / \"trees.csv\").write_text( \"TreeID,name\\n1,Sophia\\n2,Charlie\", \"utf-8\", ) (repo_dir",
"convert, expected_rows): runner = CliRunner() db_path = str(tmpdir / \"db.db\") with runner.isolated_filesystem(): result",
"= sqlite_utils.Database(db_path) item_table = namespace or \"item\" version_table = \"{}_version\".format(item_table) assert db.schema ==",
"in ( select column from {namespace}_changed where item_version = {namespace}_version._id ) ) as",
") @pytest.mark.parametrize( \"dialect,expected_schema\", ( (\"excel\", \"CREATE TABLE [item] (\\n [TreeID] TEXT,\\n [name] TEXT\\n)\"),",
"content.decode(\"utf-8\")}]', \"--id\", \"id\", ] + options, catch_exceptions=False, ) assert result.exit_code == 0 db",
") assert db[\"commits\"].count == 2 # Should have some duplicates assert [(r[\"product_id\"], r[\"name\"])",
"{\"PRODUCT_ID\": 1, \"NAME\": \"GIN\"}, {\"PRODUCT_ID\": 2, \"NAME\": \"TONIC 2\"}, {\"PRODUCT_ID\": 3, \"NAME\": \"RUM\"},",
"INTEGER PRIMARY KEY, [namespace] INTEGER REFERENCES [namespaces]([id]), [hash] TEXT, [commit_at] TEXT ); CREATE",
"+ options, catch_exceptions=False, ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) actual_text =",
"cwd=str(repo)) result2 = runner.invoke( cli, [ \"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo),",
"PRIMARY KEY, [_item_id] TEXT , [_id_] INTEGER, [_item_] TEXT, [_version_] TEXT, [_commit_] TEXT,",
"@pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def test_file_with_id_resume(repo, tmpdir, namespace): runner = CliRunner() db_path = str(tmpdir",
"(None, \"custom\")) def test_file_with_id_full_versions(repo, tmpdir, namespace): runner = CliRunner() db_path = str(tmpdir /",
"3, \"version\": 1, \"column_name\": \"product_id\"}, ] # Test the view view_rows = list(",
"\"two_changed\", } # Should be five versions: Gin, Tonic -> Tonic 2, Rum",
"(\"excel\", \"CREATE TABLE [item] (\\n [TreeID] TEXT,\\n [name] TEXT\\n)\"), (\"excel-tab\", \"CREATE TABLE [item]",
"\"rowid\": 6, }, { \"_id\": 3, \"_item\": \"Rum\", \"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\":",
"return textwrap.dedent( \"\"\" CREATE VIEW {namespace}_version_detail AS select commits.commit_at as _commit_at, commits.hash as",
"\"--repo\", str(repo), \"--id\", \"product_id\", ] + ([\"--namespace\", namespace] if namespace else []), catch_exceptions=False,",
"\"_version_\": \"v1\", \"_commit_\": \"commit1\", \"rowid_\": 7, }, ] @pytest.mark.parametrize(\"file\", (\"trees.csv\", \"trees.tsv\")) def test_csv_tsv(repo,",
"= CliRunner() (repo / \"items.xml\").write_text( \"\"\" <items> <item name=\"one\" value=\"1\" /> <item name=\"two\"",
"assert changed == [ {\"product_id\": 1, \"version\": 1, \"column_name\": \"name\"}, {\"product_id\": 1, \"version\":",
"{}\".format(version_table) ) ] assert item_version == [ {\"product_id\": 1, \"_version\": 1, \"name\": \"Gin\"},",
"(None, \"custom\")) def test_file_without_id(repo, tmpdir, namespace): runner = CliRunner() db_path = str(tmpdir /",
"[columns]([id]), PRIMARY KEY ([item_version], [column]) ); {view} CREATE INDEX [idx_{namespace}_version__item] ON [{namespace}_version] ([_item]);",
"\"_commit\": \"commit1\", \"rowid\": 5, }, { \"_id\": 2, \"_item\": \"Tonic\", \"_version\": \"v1\", \"_commit\":",
"= runner.invoke( cli, [ \"file\", db_path, str(repo / file), \"--repo\", str(repo), \"--id\", \"TreeID\",",
"([_item_id]);\\n\".format(item_table) + \"CREATE TABLE [{}] (\\n\".format(version_table) + \" [_id] INTEGER PRIMARY KEY,\\n\" \"",
"changed from \"Rum\" to \"Rum Pony\": {\"product_id\": 3, \"name\": \"Rum Pony\"}, ] ),",
"result.exit_code == 0 for namespace in (\"one\", \"two\"): run(namespace) # Now modify items.json,",
"(repo_dir / \"items-with-banned-columns.json\").write_text( json.dumps( [ { \"_id_\": 1, \"_version_\": \"Gin\", } ] ),",
"(3, \"Rum\"), ] @pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def test_file_with_id(repo, tmpdir, namespace): runner = CliRunner()",
"(\\n\".format(item_table) + \" [_id] INTEGER PRIMARY KEY,\\n\" \" [_item_id] TEXT\\n\" \", [product_id] INTEGER,",
"= sqlite_utils.Database(db_path) assert set(db.table_names()) == { \"namespaces\", \"commits\", \"one\", \"one_version\", \"columns\", \"one_changed\", \"two\",",
"value=\"1\" /> <item name=\"two\" value=\"2\" /> </items> \"\"\", \"utf-8\", ) subprocess.call([\"git\", \"add\", \"items.xml\"],",
"[item_version] ([_item]);\" ).strip() assert db.schema == expected_schema item_version = [ r for r",
"[]), ), ) def test_skip_options(repo, tmpdir, options, expected_texts): runner = CliRunner() commits =",
"test_reserved_columns_are_reserved(tmpdir, repo): runner = CliRunner() db_path = str(tmpdir / \"db.db\") runner.invoke( cli, [",
"0 db = sqlite_utils.Database(db_path) rows = [{k: v for k, v in r.items()",
"[{namespace}_version] ( [_id] INTEGER PRIMARY KEY, [_item] INTEGER REFERENCES [{namespace}]([_id]), [_version] INTEGER, [_commit]",
"2], [\"3\"]), ([\"--start-at\", 2], [\"2\", \"3\"]), ([\"--start-after\", 2], [\"3\"]), ([\"--start-at\", 3], [\"3\"]), ([\"--start-after\",",
"CliRunner() db_path = str(tmpdir / \"reserved.db\") with runner.isolated_filesystem(): result = runner.invoke( cli, [",
"\"cde448\", \"Location\": \"555 West Example Drive\", \"Type\": \"medical\", }, ] ), \"utf-8\", )",
"REFERENCES [commits]([id]),\\n\" \" [product_id] INTEGER,\\n\" \" [name] TEXT\\n\" \");\\n\" + expected_create_view(namespace or \"item\")",
") ) as _changed_columns from {namespace}_version join commits on commits.id = {namespace}_version._commit; \"\"\".format(",
"] # Test the view view_rows = list( db.query( \"select _version, product_id, name,",
"/ \"db.db\") result = runner.invoke( cli, [ \"file\", db_path, str(repo / \"items.json\"), \"--repo\",",
"\"_commit_\": \"commit1\", \"rowid_\": 6, }, { \"_id_\": 3, \"_item_\": \"Rum\", \"_version_\": \"v1\", \"_commit_\":",
"\"convert,expected_rows\", ( ( \"json.loads(content.upper())\", [ {\"PRODUCT_ID\": 1, \"NAME\": \"GIN\"}, {\"PRODUCT_ID\": 2, \"NAME\": \"TONIC\"},",
"\"555 West Example Drive\", \"Type\": \"medical\", }, ] ), \"utf-8\", ) (repo_dir /",
"[hash] TEXT, [commit_at] TEXT ); CREATE UNIQUE INDEX [idx_commits_namespace_hash] ON [commits] ([namespace], [hash]);",
"\"name\": \"Rum Pony\"}, ] ), \"utf-8\", ) subprocess.call(git_commit + [\"-a\", \"-m\", \"another\"], cwd=str(repo))",
"\"1\"}, {\"name\": \"two\", \"value\": \"2\"}, ] @pytest.mark.parametrize( \"options,expected_texts\", ( ([], [\"1\", \"2\", \"3\"]),",
"\"_item\": \"Tonic 2\", \"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\": 6, }, { \"_id\": 3,",
"ON [columns] ([namespace], [name]); CREATE TABLE [{namespace}_changed] ( [item_version] INTEGER REFERENCES [{namespace}_version]([_id]), [column]",
"= sqlite_utils.Database(db_path) expected_schema = ( textwrap.dedent( \"\"\" CREATE TABLE [namespaces] ( [id] INTEGER",
"columns with _ prefixes and no suffix db = sqlite_utils.Database(db_path) with_prefix = {\"rowid\"}",
"\" [_id] INTEGER PRIMARY KEY,\\n\" \" [_item] INTEGER REFERENCES [{}]([_id]),\\n\".format(item_table) + \" [_version]",
"\"another\"], cwd=str(repo)) for namespace in (\"one\", \"two\"): run(namespace) db = sqlite_utils.Database(db_path) assert set(db.table_names())",
"PRIMARY KEY,\\n\" \" [namespace] INTEGER REFERENCES [namespaces]([id]),\\n\" \" [hash] TEXT,\\n\" \" [commit_at] TEXT\\n\"",
"cwd=str(repo_dir), ) subprocess.call(git_commit + [\"-m\", \"first\"], cwd=str(repo_dir)) subprocess.call([\"git\", \"branch\", \"-m\", \"main\"], cwd=str(repo_dir)) (repo_dir",
"import RESERVED import itertools import json import pytest import subprocess import sqlite_utils import",
") ] assert item_version == [ { \"_id_\": 1, \"_item_\": \"Gin\", \"_version_\": \"v1\",",
"assert result.exit_code == 0 db = sqlite_utils.Database(db_path) actual_text = [r[\"text\"] for r in",
"[commits]([id]), [_id_] INTEGER, [_item_] TEXT, [_version_] TEXT, [_commit_] TEXT, [rowid_] INTEGER );\"\"\" )",
"columns where id in ( select column from {namespace}_changed where item_version = {namespace}_version._id",
"[commits] ([namespace], [hash]);\\n\" \"CREATE TABLE [{}] (\\n\".format(item_table) + \" [_id] INTEGER PRIMARY KEY,\\n\"",
"0 db = sqlite_utils.Database(db_path) assert db[\"item\"].schema == expected_schema @pytest.mark.parametrize( \"convert,expected_rows\", ( ( \"json.loads(content.upper())\",",
"([_item]);\" ) @pytest.mark.parametrize( \"dialect,expected_schema\", ( (\"excel\", \"CREATE TABLE [item] (\\n [TreeID] TEXT,\\n [name]",
"CREATE INDEX [idx_{namespace}_version__item] ON [{namespace}_version] ([_item]); \"\"\".strip().format( namespace=namespace or \"item\", view=expected_create_view(namespace or \"item\"),",
"convert, ], catch_exceptions=False, ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) rows =",
"\"\"\".format( namespace=namespace ) ).strip() @pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def test_file_without_id(repo, tmpdir, namespace): runner =",
"( [_id] INTEGER PRIMARY KEY, [_item] INTEGER REFERENCES [{namespace}]([_id]), [_version] INTEGER, [_commit] INTEGER",
"CREATE UNIQUE INDEX [idx_columns_namespace_name] ON [columns] ([namespace], [name]); CREATE TABLE [{namespace}_changed] ( [item_version]",
"item_version = [ r for r in db.query( \"select product_id, _version, name from",
"is None because it did not change here {\"product_id\": None, \"_version\": 2, \"name\":",
"+ ([\"--namespace\", namespace] if namespace else []), ) namespace = namespace or \"item\"",
"3], [\"3\"]), ([\"--start-after\", 3], []), ), ) def test_skip_options(repo, tmpdir, options, expected_texts): runner",
"\"product_id\", \"--namespace\", namespace, ], ) assert result.exit_code == 0 for namespace in (\"one\",",
"\"IncidentID\": \"abc123\", \"Location\": \"Corner of 4th and Vermont\", \"Type\": \"fire\", }, { \"IncidentID\":",
"catch_exceptions=False, ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) assert ( db.schema ==",
"runner.invoke( cli, [ \"file\", db_path, str(repo / \"trees.csv\"), \"--repo\", str(repo), \"--dialect\", dialect, ],",
"(True, False)) def test_wal(repo, tmpdir, use_wal): runner = CliRunner() db_path = str(tmpdir /",
"\"name\": \"Tonic\"}, {\"_item\": 2, \"product_id\": None, \"_version\": 2, \"name\": \"Tonic 2\"}, {\"_item\": 3,",
"\"Rum\"}, ] def test_file_with_reserved_columns(repo, tmpdir): runner = CliRunner() db_path = str(tmpdir / \"reserved.db\")",
"None, \"_version\": 2, \"name\": \"Rum Pony\"}, ] def test_file_with_id_resume_two_namespaces(repo, tmpdir): # https://github.com/simonw/git-history/issues/43 runner",
"REFERENCES [commits]([id]), [product_id] INTEGER, [name] TEXT, [_item_full_hash] TEXT ); CREATE TABLE [columns] (",
"INTEGER, [_commit] INTEGER REFERENCES [commits]([id]), [TreeID] TEXT, [name] TEXT );\"\"\" ).strip() + \"\\n\"",
"str(repo), \"--dialect\", dialect, ], catch_exceptions=False, ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path)",
"2\", }, { \"product_id\": 3, \"name\": \"Rum\", }, ] ), \"utf-8\", ) (repo_dir",
"= str(tmpdir / \"reserved.db\") with runner.isolated_filesystem(): result = runner.invoke( cli, [ \"file\", db_path,",
"= runner.invoke( cli, [ \"file\", db_path, str(repo / \"increment.txt\"), \"--repo\", str(repo), \"--convert\", '[{\"id\":",
"2, \"version\": 1, \"column_name\": \"name\"}, {\"product_id\": 2, \"version\": 1, \"column_name\": \"product_id\"}, {\"product_id\": 2,",
"\"utf-8\") subprocess.call( git_commit + [\"-m\", \"increment {}\".format(i), \"-a\"], cwd=str(repo_dir) ) return repo_dir @pytest.fixture",
"); CREATE UNIQUE INDEX [idx_commits_namespace_hash] ON [commits] ([namespace], [hash]); CREATE TABLE [{namespace}] (",
"\"_version\": 1, \"name\": \"Gin\"}, {\"product_id\": 2, \"_version\": 1, \"name\": \"Tonic\"}, {\"product_id\": None, \"_version\":",
"[TreeID] TEXT, [name] TEXT, [_commit] INTEGER); CREATE UNIQUE INDEX [idx_item__item_id] ON [item] ([_item_id]);",
"cwd=str(repo)) db_path = str(tmpdir / \"db.db\") result = runner.invoke( cli, [ \"file\", db_path,",
"1, \"name\": \"Gin\"}, {\"product_id\": 2, \"name\": \"Tonic 2\"}, # This line has changed",
"CliRunner() db_path = str(tmpdir / \"db.db\") result = runner.invoke( cli, [ \"file\", db_path,",
"[item] ( [_id] INTEGER PRIMARY KEY, [_item_id] TEXT , [TreeID] TEXT, [name] TEXT,",
"not column.endswith(\"_\"): with_prefix.add(column) assert with_prefix == set(RESERVED) @pytest.mark.parametrize(\"use_wal\", (True, False)) def test_wal(repo, tmpdir,",
"\"two\"): run(namespace) db = sqlite_utils.Database(db_path) assert set(db.table_names()) == { \"namespaces\", \"commits\", \"one\", \"one_version\",",
"/ \"repo\" repo_dir.mkdir() # This one is used for the README generated by",
"{\"product_id\": 2, \"_version\": 2, \"name\": \"Tonic 2\"}, {\"product_id\": 3, \"_version\": 1, \"name\": \"Rum\"},",
"{namespace}_version on {namespace}_changed.item_version = {namespace}_version._id join {namespace} on {namespace}._id = {namespace}_version._item order by",
"INTEGER PRIMARY KEY, [_item_id] TEXT , [TreeID] TEXT, [name] TEXT, [_commit] INTEGER); CREATE",
"[{namespace}] ( [_id] INTEGER PRIMARY KEY, [_item_id] TEXT , [product_id] INTEGER, [name] TEXT,",
"( [_id] INTEGER PRIMARY KEY, [_item_id] TEXT , [_id_] INTEGER, [_item_] TEXT, [_version_]",
"7, }, ] @pytest.mark.parametrize(\"file\", (\"trees.csv\", \"trees.tsv\")) def test_csv_tsv(repo, tmpdir, file): runner = CliRunner()",
"+ expected_create_view(namespace or \"item\") + \"\\nCREATE INDEX [idx_{}__item]\\n\".format(version_table) + \" ON [{}] ([_item]);\".format(version_table)",
"INTEGER, [_item_] TEXT, [_version_] TEXT, [_commit_] TEXT, [rowid_] INTEGER, [_commit] INTEGER); CREATE UNIQUE",
"if column.startswith(\"_\") and not column.endswith(\"_\"): with_prefix.add(column) assert with_prefix == set(RESERVED) @pytest.mark.parametrize(\"use_wal\", (True, False))",
", [product_id] INTEGER, [name] TEXT, [_commit] INTEGER); CREATE UNIQUE INDEX [idx_{namespace}__item_id] ON [{namespace}]",
"2, \"name\": \"Tonic 2\", }, { \"product_id\": 3, \"name\": \"Rum\", }, ] ),",
"namespace in (\"one\", \"two\"): run(namespace) # Now modify items.json, commit and run again",
"\"_item_\": \"Rum\", \"_version_\": \"v1\", \"_commit_\": \"commit1\", \"rowid_\": 7, }, ] @pytest.mark.parametrize(\"file\", (\"trees.csv\", \"trees.tsv\"))",
"if namespace: options += [\"--namespace\", namespace] result = runner.invoke(cli, options) assert result.exit_code ==",
"\"IncidentID\": \"cde448\", \"Location\": \"555 West Example Drive\", \"Type\": \"medical\", }, ] ), \"utf-8\",",
"[name] TEXT ); CREATE UNIQUE INDEX [idx_columns_namespace_name] ON [columns] ([namespace], [name]); CREATE TABLE",
"KEY, [namespace] INTEGER REFERENCES [namespaces]([id]), [name] TEXT ); CREATE UNIQUE INDEX [idx_columns_namespace_name] ON",
"\"name\": \"Tonic 2\"}, {\"product_id\": 3, \"name\": \"Rum Pony\"}, ] ), \"utf-8\", ) subprocess.call(git_commit",
"[product_id] INTEGER, [name] TEXT, [_commit] INTEGER);\\n\" \"CREATE UNIQUE INDEX [idx_{}__item_id]\\n\".format(item_table) + \" ON",
"def test_reserved_columns_are_reserved(tmpdir, repo): runner = CliRunner() db_path = str(tmpdir / \"db.db\") runner.invoke( cli,",
"] assert item_version2 == [ {\"_item\": 1, \"product_id\": 1, \"_version\": 1, \"name\": \"Gin\"},",
"\"utf-8\", ) (repo_dir / \"items.json\").write_text( json.dumps( [ { \"product_id\": 1, \"name\": \"Gin\", },",
"_item_, _version_, _commit_, rowid_ from item_version\" ) ] assert item_version == [ {",
"!= \"_commit\"} for r in db[\"item\"].rows] assert rows == expected_rows def test_convert_xml(repo, tmpdir):",
"], ), # Generator ( ( \"data = json.loads(content)\\n\" \"for item in data:\\n\"",
"_version, product_id, name, _changed_columns from {}_version_detail\".format( namespace or \"item\" ) ) ) #",
"= sqlite_utils.Database(db_path) expected_journal_mode = \"wal\" if use_wal else \"delete\" assert db.journal_mode == expected_journal_mode",
"+ \" [_id] INTEGER PRIMARY KEY,\\n\" \" [_item_id] TEXT\\n\" \", [product_id] INTEGER, [name]",
"[{}]([_id]),\\n\".format(item_table) + \" [_version] INTEGER,\\n\" \" [_commit] INTEGER REFERENCES [commits]([id]),\\n\" \" [product_id] INTEGER,\\n\"",
"2, \"name\": \"Tonic\", }, ] ), \"utf-8\", ) (repo_dir / \"items-with-reserved-columns.json\").write_text( json.dumps( [",
"( \"json.loads(content.upper())\", [ {\"PRODUCT_ID\": 1, \"NAME\": \"GIN\"}, {\"PRODUCT_ID\": 2, \"NAME\": \"TONIC\"}, {\"PRODUCT_ID\": 1,",
"id in ( select column from {namespace}_changed where item_version = {namespace}_version._id ) )",
"\"name\"}, {\"product_id\": 3, \"version\": 1, \"column_name\": \"name\"}, {\"product_id\": 3, \"version\": 1, \"column_name\": \"product_id\"},",
"\"name\": \"Gin\", }, { \"product_id\": 2, \"name\": \"Tonic 2\", }, { \"product_id\": 3,",
"\"TreeID\", \"--csv\", \"--full-versions\", ], catch_exceptions=False, ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path)",
"/ \"trees.csv\"), \"--repo\", str(repo), \"--dialect\", dialect, ], catch_exceptions=False, ) assert result.exit_code == 0",
"{namespace}_version._id ) ) as _changed_columns from {namespace}_version join commits on commits.id = {namespace}_version._commit;",
"[columns] ( [id] INTEGER PRIMARY KEY, [namespace] INTEGER REFERENCES [namespaces]([id]), [name] TEXT );",
"order by _item, _version\".format( namespace ) ) ] assert item_version2 == [ {\"_item\":",
"= CliRunner() db_path = str(tmpdir / \"reserved.db\") with runner.isolated_filesystem(): result = runner.invoke( cli,",
"ON [commits] ([namespace], [hash]);\\n\" \"CREATE TABLE [{}] (\\n\".format(item_table) + \" [_id] INTEGER PRIMARY",
"[commits] ([namespace], [hash]); CREATE TABLE [item] ( [_id] INTEGER PRIMARY KEY, [_item_id] TEXT",
"[\"name\", \"product_id\"], }, { \"_version\": 2, \"product_id\": None, \"name\": \"Tonic 2\", \"_changed_columns\": [\"name\"],",
"db_path, str(repo / file), \"--repo\", str(repo), \"--id\", \"TreeID\", \"--csv\", \"--full-versions\", ], catch_exceptions=False, )",
"(\\n [TreeID,name] TEXT\\n)\"), ), ) def test_csv_dialect(repo, tmpdir, dialect, expected_schema): runner = CliRunner()",
"([name]); CREATE TABLE [commits] ( [id] INTEGER PRIMARY KEY, [namespace] INTEGER REFERENCES [namespaces]([id]),",
"textwrap git_commit = [ \"git\", \"-c\", \"user.name='Tests'\", \"-c\", \"user.email='<EMAIL>'\", \"commit\", ] def make_repo(tmpdir):",
"2, \"name\": \"Rum Pony\"}, ] def test_file_with_id_resume_two_namespaces(repo, tmpdir): # https://github.com/simonw/git-history/issues/43 runner = CliRunner()",
"}, { \"product_id\": 2, \"name\": \"Tonic\", }, ] ), \"utf-8\", ) (repo_dir /",
"2 # Should have no duplicates item_version = [ r for r in",
"0 db = sqlite_utils.Database(db_path) assert ( db.schema == textwrap.dedent( \"\"\" CREATE TABLE [namespaces]",
"= runner.invoke(cli, options) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) assert db.schema ==",
"\"items-with-banned-columns.json\", \"trees.csv\", \"trees.tsv\", \"increment.txt\", ], cwd=str(repo_dir), ) subprocess.call(git_commit + [\"-m\", \"first\"], cwd=str(repo_dir)) subprocess.call([\"git\",",
"from {}_version\".format(namespace) ) ] assert item_version == [ {\"product_id\": 1, \"_version\": 1, \"name\":",
"is undefined, so fix that for row in view_rows: row[\"_changed_columns\"] = list(sorted(json.loads(row[\"_changed_columns\"]))) assert",
"\"product_id\": 3, \"name\": \"Rum\", \"_changed_columns\": [\"name\", \"product_id\"], }, ] @pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def",
"_item, _version\".format( namespace ) ) ] assert item_version2 == [ {\"_item\": 1, \"product_id\":",
"\"_commit_\": \"commit1\", \"rowid_\": 7, }, ] @pytest.mark.parametrize(\"file\", (\"trees.csv\", \"trees.tsv\")) def test_csv_tsv(repo, tmpdir, file):",
"and no suffix db = sqlite_utils.Database(db_path) with_prefix = {\"rowid\"} for table in itertools.chain(db.tables,",
"[idx_item__item_id] ON [item] ([_item_id]); CREATE TABLE [item_version] ( [_id] INTEGER PRIMARY KEY, [_item]",
"_changed_columns from {}_version_detail\".format( namespace or \"item\" ) ) ) # Sort order of",
"have no duplicates item_version = [ r for r in db.query( \"select product_id,",
"INTEGER REFERENCES [item]([_id]), [_version] INTEGER, [_commit] INTEGER REFERENCES [commits]([id]), [TreeID] TEXT, [name] TEXT",
"\"_changed_columns\": [\"name\", \"product_id\"], }, { \"_version\": 2, \"product_id\": None, \"name\": \"Tonic 2\", \"_changed_columns\":",
"subprocess.call(git_commit + [\"-a\", \"-m\", \"another\"], cwd=str(repo)) for namespace in (\"one\", \"two\"): run(namespace) db",
"[TreeID] TEXT, [name] TEXT );\"\"\" ).strip() + \"\\n\" + expected_create_view(\"item\") + \"\\nCREATE INDEX",
"\"name\": \"Tonic 2\"}, # This line has changed from \"Rum\" to \"Rum Pony\":",
"{\"just_name\": item[\"name\"]}' ), [ {\"just_name\": \"Gin\"}, {\"just_name\": \"Tonic\"}, {\"just_name\": \"Gin\"}, {\"just_name\": \"<NAME>\"}, {\"just_name\":",
"TABLE [{}] (\\n\".format(namespace or \"item\") + \" [product_id] INTEGER,\\n\" \" [name] TEXT\\n\" \");\"",
"# Now modify items.json, commit and run again (repo / \"items.json\").write_text( json.dumps( [",
") (repo_dir / \"trees.csv\").write_text( \"TreeID,name\\n1,Sophia\\n2,Charlie\", \"utf-8\", ) (repo_dir / \"trees.tsv\").write_text( \"TreeID\\tname\\n1\\tSophia\\n2\\tCharlie\", \"utf-8\", )",
"\"custom\")) def test_file_with_id(repo, tmpdir, namespace): runner = CliRunner() db_path = str(tmpdir / \"db.db\")",
"[_commit] INTEGER REFERENCES [commits]([id]), [_id_] INTEGER, [_item_] TEXT, [_version_] TEXT, [_commit_] TEXT, [rowid_]",
"test_convert_xml(repo, tmpdir): runner = CliRunner() (repo / \"items.xml\").write_text( \"\"\" <items> <item name=\"one\" value=\"1\"",
"str(repo / \"items.json\"), \"--repo\", str(repo), \"--id\", \"product_id\", ] + ([\"--namespace\", namespace] if namespace",
"item_version\" ) ] assert item_version == [ { \"_id_\": 1, \"_item_\": \"Gin\", \"_version_\":",
"2, \"name\": \"Tonic\", \"_changed_columns\": [\"name\", \"product_id\"], }, { \"_version\": 2, \"product_id\": None, \"name\":",
"/ \"items.json\"), \"--repo\", str(repo)] if namespace: options += [\"--namespace\", namespace] result = runner.invoke(cli,",
"result = runner.invoke( cli, [ \"file\", db_path, str(repo / file), \"--repo\", str(repo), \"--id\",",
"{ \"_version\": 1, \"product_id\": 1, \"name\": \"Gin\", \"_changed_columns\": [\"name\", \"product_id\"], }, { \"_version\":",
"cli, [ \"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo), \"--convert\", convert, ], catch_exceptions=False,",
"cwd=str(repo)) .decode(\"utf-8\") .split(\"\\n\") ) ) assert len(commits) == 4 # Rewrite options to",
"commit and try again (repo / \"items.json\").write_text( json.dumps( [ {\"product_id\": 1, \"name\": \"Gin\"},",
"\"_version\": 1, \"name\": \"Tonic\"}, # product_id is None because it did not change",
"{\"product_id\": 2, \"name\": \"Tonic 2\"}, # This line has changed from \"Rum\" to",
"or \"item\", view=expected_create_view(namespace or \"item\"), ) assert db[\"commits\"].count == 2 # Should have",
"+ \"\\n\" + expected_create_view(\"item\") + \"\\nCREATE INDEX [idx_item_version__item]\\n\" \" ON [item_version] ([_item]);\" )",
"None because it did not change here {\"product_id\": None, \"_version\": 2, \"name\": \"Tonic",
"db_path, str(repo / \"items.json\"), \"--repo\", str(repo), \"--id\", \"product_id\", \"--full-versions\", ] + ([\"--namespace\", namespace]",
"[name] TEXT, [_commit] INTEGER); CREATE UNIQUE INDEX [idx_item__item_id] ON [item] ([_item_id]); CREATE TABLE",
") assert len(commits) == 4 # Rewrite options to replace integers with the",
"\"_commit\": \"commit1\", \"rowid\": 7, }, ] ), \"utf-8\", ) subprocess.call(git_commit + [\"-m\", \"second\",",
"view view_rows = list( db.query( \"select _version, product_id, name, _changed_columns from {}_version_detail\".format( namespace",
"[ \"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo), \"--id\", \"product_id\", ], ) #",
"sqlite_utils.Database(db_path) assert list(db[\"item\"].rows) == [ {\"name\": \"one\", \"value\": \"1\"}, {\"name\": \"two\", \"value\": \"2\"},",
"\"CREATE UNIQUE INDEX [idx_commits_namespace_hash]\\n\" \" ON [commits] ([namespace], [hash]);\\n\" \"CREATE TABLE [{}] (\\n\".format(item_table)",
"and not column.endswith(\"_\"): with_prefix.add(column) assert with_prefix == set(RESERVED) @pytest.mark.parametrize(\"use_wal\", (True, False)) def test_wal(repo,",
"/ \"trees.csv\").write_text( \"TreeID,name\\n1,Sophia\\n2,Charlie\", \"utf-8\", ) (repo_dir / \"trees.tsv\").write_text( \"TreeID\\tname\\n1\\tSophia\\n2\\tCharlie\", \"utf-8\", ) (repo_dir /",
"namespace in (\"one\", \"two\"): run(namespace) db = sqlite_utils.Database(db_path) assert set(db.table_names()) == { \"namespaces\",",
"( ([], [\"1\", \"2\", \"3\"]), ([\"--skip\", 0], [\"2\", \"3\"]), ([\"--skip\", 0, \"--skip\", 2],",
"_version, name from {}_version order by _item, _version\".format( namespace ) ) ] assert",
"it did not change here {\"product_id\": None, \"_version\": 2, \"name\": \"Tonic 2\"}, {\"product_id\":",
"+ \" ON [{}] ([_item_id]);\\n\".format(item_table) + \"CREATE TABLE [{}] (\\n\".format(version_table) + \" [_id]",
"in db[\"item\"].rows] assert rows == expected_rows def test_convert_xml(repo, tmpdir): runner = CliRunner() (repo",
"for table in itertools.chain(db.tables, db.views): for column in table.columns_dict: if column.startswith(\"_\") and not",
"db_path = str(tmpdir / \"db.db\") runner.invoke( cli, [ \"file\", db_path, str(repo / \"items.json\"),",
"as version, columns.name as column_name from {namespace}_changed join columns on {namespace}_changed.column = columns.id",
"subprocess.call([\"git\", \"branch\", \"-m\", \"main\"], cwd=str(repo_dir)) (repo_dir / \"items.json\").write_text( json.dumps( [ { \"product_id\": 1,",
"def run(namespace): result = runner.invoke( cli, [ \"file\", db_path, str(repo / \"items.json\"), \"--repo\",",
"= str(tmpdir / \"db.db\") def run(namespace): result = runner.invoke( cli, [ \"file\", db_path,",
"sqlite_utils.Database(db_path) item_table = namespace or \"item\" version_table = \"{}_version\".format(item_table) assert db.schema == (",
"Find all columns with _ prefixes and no suffix db = sqlite_utils.Database(db_path) with_prefix",
"db = sqlite_utils.Database(db_path) expected_schema = ( textwrap.dedent( \"\"\" CREATE TABLE [namespaces] ( [id]",
"([namespace], [hash]); CREATE TABLE [{namespace}] ( [_id] INTEGER PRIMARY KEY, [_item_id] TEXT ,",
"== expected_schema item_version = [ r for r in db.query( \"select _id_, _item_,",
"[item] (\\n [TreeID,name] TEXT\\n)\"), ), ) def test_csv_dialect(repo, tmpdir, dialect, expected_schema): runner =",
"\"Gin\"), (2, \"Tonic\"), (1, \"Gin\"), (2, \"Tonic 2\"), (3, \"Rum\"), ] @pytest.mark.parametrize(\"namespace\", (None,",
"KEY,\\n\" \" [_item] INTEGER REFERENCES [{}]([_id]),\\n\".format(item_table) + \" [_version] INTEGER,\\n\" \" [_commit] INTEGER",
"{\"product_id\": None, \"_version\": 2, \"name\": \"Tonic 2\"}, {\"product_id\": 3, \"_version\": 1, \"name\": \"Rum\"},",
"INDEX [idx_commits_namespace_hash]\\n\" \" ON [commits] ([namespace], [hash]);\\n\" \"CREATE TABLE [{}] (\\n\".format(item_table) + \"",
"\"CREATE TABLE [commits] (\\n\" \" [id] INTEGER PRIMARY KEY,\\n\" \" [namespace] INTEGER REFERENCES",
"[rowid_] INTEGER );\"\"\" ) + \"\\n\" + expected_create_view(\"item\") + \"\\nCREATE INDEX [idx_item_version__item]\\n\" \"",
"\"item\" version_table = \"{}_version\".format(item_table) assert db.schema == \"\"\" CREATE TABLE [namespaces] ( [id]",
"), \"utf-8\", ) (repo_dir / \"items-with-banned-columns.json\").write_text( json.dumps( [ { \"_id_\": 1, \"_version_\": \"Gin\",",
"1, \"column_name\": \"product_id\"}, {\"product_id\": 2, \"version\": 1, \"column_name\": \"name\"}, {\"product_id\": 2, \"version\": 1,",
"\"product_id\": 1, \"name\": \"Gin\", }, { \"product_id\": 2, \"name\": \"Tonic\", }, ] ),",
"namespace): runner = CliRunner() db_path = str(tmpdir / \"db.db\") result = runner.invoke( cli,",
"\"v1\", \"_commit\": \"commit1\", \"rowid\": 6, }, ] ), \"utf-8\", ) (repo_dir / \"items-with-banned-columns.json\").write_text(",
"if use_wal: options.append(\"--wal\") result = runner.invoke( cli, options, catch_exceptions=False, ) assert result.exit_code ==",
"\"name\": \"Tonic 2\"}, {\"product_id\": 3, \"_version\": 1, \"name\": \"Rum\"}, ] # Now we",
"runner = CliRunner() db_path = str(tmpdir / \"db.db\") runner.invoke( cli, [ \"file\", db_path,",
"column from {namespace}_changed where item_version = {namespace}_version._id ) ) as _changed_columns from {namespace}_version",
"namespace: options += [\"--namespace\", namespace] result = runner.invoke(cli, options) assert result.exit_code == 0",
"KEY, [_item] INTEGER REFERENCES [{namespace}]([_id]), [_version] INTEGER, [_commit] INTEGER REFERENCES [commits]([id]), [product_id] INTEGER,",
"TABLE [commits] ( [id] INTEGER PRIMARY KEY, [namespace] INTEGER REFERENCES [namespaces]([id]), [hash] TEXT,",
"}, { \"_id\": 2, \"_item\": \"Tonic\", \"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\": 6, },",
"2, \"name\": \"Tonic 2\"}, {\"product_id\": 3, \"_version\": 1, \"name\": \"Rum\"}, ] changed =",
"[\"name\"], }, { \"_version\": 1, \"product_id\": 3, \"name\": \"Rum\", \"_changed_columns\": [\"name\", \"product_id\"], },",
"that for row in view_rows: row[\"_changed_columns\"] = list(sorted(json.loads(row[\"_changed_columns\"]))) assert view_rows == [ {",
"tree = xml.etree.ElementTree.fromstring(content) return [el.attrib for el in tree.iter(\"item\")] \"\"\" ), \"--import\", \"xml.etree.ElementTree\",",
"catch_exceptions=False, ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) expected_journal_mode = \"wal\" if",
"= sqlite_utils.Database(db_path) with_prefix = {\"rowid\"} for table in itertools.chain(db.tables, db.views): for column in",
"\"two\", \"two_version\", \"two_changed\", } # Should be five versions: Gin, Tonic -> Tonic",
"\"\"\" tree = xml.etree.ElementTree.fromstring(content) return [el.attrib for el in tree.iter(\"item\")] \"\"\" ), \"--import\",",
"with_prefix = {\"rowid\"} for table in itertools.chain(db.tables, db.views): for column in table.columns_dict: if",
"db[\"one_version\"].count == 5 assert db[\"two_version\"].count == 5 @pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def test_file_with_id_full_versions(repo, tmpdir,",
"] + ([\"--namespace\", namespace] if namespace else []), catch_exceptions=False, ) assert result2.exit_code ==",
"); CREATE UNIQUE INDEX [idx_namespaces_name] ON [namespaces] ([name]); CREATE TABLE [commits] ( [id]",
"CliRunner() db_path = str(tmpdir / \"db.db\") options = [ \"file\", db_path, str(repo /",
"str(repo / \"items.json\"), \"--repo\", str(repo), \"--id\", \"product_id\", \"--full-versions\", ] + ([\"--namespace\", namespace] if",
"select json_group_array(name) from columns where id in ( select column from {namespace}_changed where",
"namespace else []), ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) item_table =",
", [TreeID] TEXT, [name] TEXT, [_commit] INTEGER); CREATE UNIQUE INDEX [idx_item__item_id] ON [item]",
"\");\" ) assert db[\"commits\"].count == 2 # Should have some duplicates assert [(r[\"product_id\"],",
"options to replace integers with the corresponding commit hash options = [commits[item] if",
"\"name\": \"Tonic 2\", \"_changed_columns\": [\"name\"], }, { \"_version\": 1, \"product_id\": 3, \"name\": \"Rum\",",
"== 0 db = sqlite_utils.Database(db_path) item_table = namespace or \"item\" version_table = \"{}_version\".format(item_table)",
"db_path, str(repo / \"items-with-reserved-columns.json\"), \"--repo\", str(repo), \"--id\", \"_id\", \"--full-versions\", ], catch_exceptions=False, ) assert",
"\"--id\", \"product_id\", \"--namespace\", namespace, ], ) assert result.exit_code == 0 for namespace in",
"TABLE [{namespace}_changed] ( [item_version] INTEGER REFERENCES [{namespace}_version]([_id]), [column] INTEGER REFERENCES [columns]([id]), PRIMARY KEY",
"/ \"items-with-banned-columns.json\").write_text( json.dumps( [ { \"_id_\": 1, \"_version_\": \"Gin\", } ] ), \"utf-8\",",
"\"items.json\").write_text( json.dumps( [ {\"product_id\": 1, \"name\": \"Gin\"}, {\"product_id\": 2, \"name\": \"Tonic 2\"}, #",
"\"product_id\", ] + ([\"--namespace\", namespace] if namespace else []), ) assert result.exit_code ==",
"], ) assert result.exit_code == 0 for namespace in (\"one\", \"two\"): run(namespace) #",
"}, ] ), \"utf-8\", ) (repo_dir / \"items.json\").write_text( json.dumps( [ { \"product_id\": 1,",
"\"name\": \"Tonic\"}, {\"product_id\": None, \"_version\": 2, \"name\": \"Tonic 2\"}, {\"product_id\": 3, \"_version\": 1,",
"str(repo), \"--id\", \"TreeID\", \"--csv\", \"--full-versions\", ], catch_exceptions=False, ) assert result.exit_code == 0 db",
"\"_version\": 2, \"name\": \"Tonic 2\"}, {\"product_id\": 3, \"_version\": 1, \"name\": \"Rum\"}, ] #",
"\"user.name='Tests'\", \"-c\", \"user.email='<EMAIL>'\", \"commit\", ] def make_repo(tmpdir): repo_dir = tmpdir / \"repo\" repo_dir.mkdir()",
"with runner.isolated_filesystem(): options = [\"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo)] if namespace:",
"KEY, [_item_id] TEXT , [product_id] INTEGER, [name] TEXT, [_commit] INTEGER); CREATE UNIQUE INDEX",
"db.views): for column in table.columns_dict: if column.startswith(\"_\") and not column.endswith(\"_\"): with_prefix.add(column) assert with_prefix",
"for r in db.query( \"select product_id, _version, name from {}\".format(version_table) ) ] assert",
"INTEGER PRIMARY KEY, [_item_id] TEXT , [product_id] INTEGER, [name] TEXT, [_commit] INTEGER); CREATE",
"[name] TEXT, [_item_full_hash] TEXT ); CREATE TABLE [columns] ( [id] INTEGER PRIMARY KEY,",
"= {namespace}_version._id join {namespace} on {namespace}._id = {namespace}_version._item order by {namespace}.product_id, {namespace}_version._version, columns.name",
"str(repo), \"--id\", \"product_id\", \"--full-versions\", ] + ([\"--namespace\", namespace] if namespace else []), )",
"\"name\": \"Rum Pony\"}, ] def test_file_with_id_resume_two_namespaces(repo, tmpdir): # https://github.com/simonw/git-history/issues/43 runner = CliRunner() db_path",
"== \"\"\" CREATE TABLE [namespaces] ( [id] INTEGER PRIMARY KEY, [name] TEXT );",
"\"db.db\") with runner.isolated_filesystem(): options = [\"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo)] if",
"] @pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def test_file_with_id(repo, tmpdir, namespace): runner = CliRunner() db_path =",
"def test_wal(repo, tmpdir, use_wal): runner = CliRunner() db_path = str(tmpdir / \"db.db\") options",
"git_history.utils import RESERVED import itertools import json import pytest import subprocess import sqlite_utils",
"INDEX [idx_commits_namespace_hash]\\n\" \" ON [commits] ([namespace], [hash]);\\n\" \"CREATE TABLE [{}] (\\n\".format(namespace or \"item\")",
"def repo(tmpdir): return make_repo(tmpdir) def expected_create_view(namespace): return textwrap.dedent( \"\"\" CREATE VIEW {namespace}_version_detail AS",
"{\"product_id\": 2, \"_version\": 1, \"name\": \"Tonic\"}, # product_id is None because it did",
"\"rowid_\": 7, }, ] @pytest.mark.parametrize(\"file\", (\"trees.csv\", \"trees.tsv\")) def test_csv_tsv(repo, tmpdir, file): runner =",
"[ (1, \"Gin\"), (2, \"Tonic\"), (1, \"Gin\"), (2, \"Tonic 2\"), (3, \"Rum\"), ]",
") assert result.exit_code == 0 db = sqlite_utils.Database(db_path) expected_schema = ( textwrap.dedent( \"\"\"",
"[_item_] TEXT, [_version_] TEXT, [_commit_] TEXT, [rowid_] INTEGER, [_commit] INTEGER); CREATE UNIQUE INDEX",
"k != \"_commit\"} for r in db[\"item\"].rows] assert rows == expected_rows def test_convert_xml(repo,",
"\"product_id\": 1, \"name\": \"Gin\", }, { \"product_id\": 2, \"name\": \"Tonic 2\", }, {",
"in db.query( \"select _item, product_id, _version, name from {}_version order by _item, _version\".format(",
"2, \"_version\": 1, \"name\": \"Tonic\"}, {\"product_id\": 2, \"_version\": 2, \"name\": \"Tonic 2\"}, {\"product_id\":",
"or \"item\" assert result.exit_code == 0 db = sqlite_utils.Database(db_path) item_version = [ r",
"with runner.isolated_filesystem(): result = runner.invoke( cli, [ \"file\", db_path, str(repo / \"items.json\"), \"--repo\",",
"\"Tonic\"}, {\"product_id\": 2, \"_version\": 2, \"name\": \"Tonic 2\"}, {\"product_id\": 3, \"_version\": 1, \"name\":",
"INTEGER PRIMARY KEY,\\n\" \" [name] TEXT\\n\" \");\\n\" \"CREATE UNIQUE INDEX [idx_namespaces_name]\\n\" \" ON",
"db[\"commits\"].count == 2 # Should have some duplicates assert [(r[\"product_id\"], r[\"name\"]) for r",
"CREATE TABLE [namespaces] ( [id] INTEGER PRIMARY KEY, [name] TEXT ); CREATE UNIQUE",
"\"items.json\").write_text( json.dumps( [ {\"product_id\": 1, \"name\": \"Gin\"}, {\"product_id\": 2, \"name\": \"Tonic 2\"}, {\"product_id\":",
"change here {\"product_id\": None, \"_version\": 2, \"name\": \"Tonic 2\"}, {\"product_id\": 3, \"_version\": 1,",
"table.columns_dict: if column.startswith(\"_\") and not column.endswith(\"_\"): with_prefix.add(column) assert with_prefix == set(RESERVED) @pytest.mark.parametrize(\"use_wal\", (True,",
"UNIQUE INDEX [idx_{}__item_id]\\n\".format(item_table) + \" ON [{}] ([_item_id]);\\n\".format(item_table) + \"CREATE TABLE [{}] (\\n\".format(version_table)",
"@pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def test_file_with_id_full_versions(repo, tmpdir, namespace): runner = CliRunner() db_path = str(tmpdir",
"\"_id\": 2, \"_item\": \"Tonic\", \"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\": 6, }, ] ),",
").strip() assert db.schema == expected_schema item_version = [ r for r in db.query(",
"([\"--skip\", 0], [\"2\", \"3\"]), ([\"--skip\", 0, \"--skip\", 2], [\"3\"]), ([\"--start-at\", 2], [\"2\", \"3\"]),",
"[_item] INTEGER REFERENCES [item]([_id]), [_version] INTEGER, [_commit] INTEGER REFERENCES [commits]([id]), [TreeID] TEXT, [name]",
"] ), \"utf-8\", ) (repo_dir / \"trees.csv\").write_text( \"TreeID,name\\n1,Sophia\\n2,Charlie\", \"utf-8\", ) (repo_dir / \"trees.tsv\").write_text(",
"\"increment.txt\"), \"--repo\", str(repo), \"--convert\", '[{\"id\": 1, \"text\": content.decode(\"utf-8\")}]', \"--id\", \"id\", ] + options,",
"repo_dir.mkdir() # This one is used for the README generated by Cog: (repo_dir",
"assert result.exit_code == 0 db = sqlite_utils.Database(db_path) assert ( db.schema == textwrap.dedent( \"\"\"",
"\" [hash] TEXT,\\n\" \" [commit_at] TEXT\\n\" \");\\n\" \"CREATE UNIQUE INDEX [idx_commits_namespace_hash]\\n\" \" ON",
"_commit_at, commits.hash as _commit_hash, {namespace}_version.*, ( select json_group_array(name) from columns where id in",
"3, \"_item\": \"Rum\", \"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\": 7, }, ] ), \"utf-8\",",
"by _item, _version\".format( namespace ) ) ] assert item_version2 == [ {\"_item\": 1,",
"[item_version] ([_item]);\" ) @pytest.mark.parametrize( \"dialect,expected_schema\", ( (\"excel\", \"CREATE TABLE [item] (\\n [TreeID] TEXT,\\n",
"CliRunner() db_path = str(tmpdir / \"db.db\") with runner.isolated_filesystem(): options = [\"file\", db_path, str(repo",
"UNIQUE INDEX [idx_{namespace}__item_id] ON [{namespace}] ([_item_id]); CREATE TABLE [{namespace}_version] ( [_id] INTEGER PRIMARY",
"as column_name from {namespace}_changed join columns on {namespace}_changed.column = columns.id join {namespace}_version on",
"{\"name\": \"one\", \"value\": \"1\"}, {\"name\": \"two\", \"value\": \"2\"}, ] @pytest.mark.parametrize( \"options,expected_texts\", ( ([],",
"list(db[\"item\"].rows) == [ {\"name\": \"one\", \"value\": \"1\"}, {\"name\": \"two\", \"value\": \"2\"}, ] @pytest.mark.parametrize(",
"(\\n\" \" [id] INTEGER PRIMARY KEY,\\n\" \" [namespace] INTEGER REFERENCES [namespaces]([id]),\\n\" \" [hash]",
"TABLE [namespaces] (\\n\" \" [id] INTEGER PRIMARY KEY,\\n\" \" [name] TEXT\\n\" \");\\n\" \"CREATE",
"\"GIN\"}, {\"PRODUCT_ID\": 2, \"NAME\": \"TONIC 2\"}, {\"PRODUCT_ID\": 3, \"NAME\": \"RUM\"}, ], ), #",
"), \"utf-8\", ) (repo_dir / \"items.json\").write_text( json.dumps( [ { \"product_id\": 1, \"name\": \"Gin\",",
"[\"name\", \"product_id\"], }, ] @pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def test_file_with_id_resume(repo, tmpdir, namespace): runner =",
"/ \"db.db\") options = [ \"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo), ]",
"\"--pretty=format:%H\"], cwd=str(repo)) .decode(\"utf-8\") .split(\"\\n\") ) ) assert len(commits) == 4 # Rewrite options",
"more commits to test --skip for i in range(2, 4): (repo_dir / \"increment.txt\").write_text(str(i),",
"sqlite_utils.Database(db_path) rows = [{k: v for k, v in r.items() if k !=",
"= {namespace}_version._item order by {namespace}.product_id, {namespace}_version._version, columns.name \"\"\".format( namespace=namespace or \"item\" ) )",
"from click.testing import CliRunner from git_history.cli import cli from git_history.utils import RESERVED import",
"= {namespace}_version._id ) ) as _changed_columns from {namespace}_version join commits on commits.id =",
"runner.invoke(cli, options) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) assert db.schema == (",
"commit hash options = [commits[item] if isinstance(item, int) else item for item in",
"\"Tonic\"}, # product_id is None because it did not change here {\"product_id\": None,",
"\"name\": \"Tonic\", }, ] ), \"utf-8\", ) (repo_dir / \"items-with-reserved-columns.json\").write_text( json.dumps( [ {",
"join commits on commits.id = {namespace}_version._commit; \"\"\".format( namespace=namespace ) ).strip() @pytest.mark.parametrize(\"namespace\", (None, \"custom\"))",
"result.exit_code == 0 db = sqlite_utils.Database(db_path) expected_journal_mode = \"wal\" if use_wal else \"delete\"",
"def test_file_with_id_full_versions(repo, tmpdir, namespace): runner = CliRunner() db_path = str(tmpdir / \"db.db\") with",
"\"NAME\": \"RUM\"}, ], ), # Generator ( ( \"data = json.loads(content)\\n\" \"for item",
"in options] db_path = str(tmpdir / \"db.db\") result = runner.invoke( cli, [ \"file\",",
"sqlite_utils.Database(db_path) assert db.schema == ( \"CREATE TABLE [namespaces] (\\n\" \" [id] INTEGER PRIMARY",
"db = sqlite_utils.Database(db_path) rows = [{k: v for k, v in r.items() if",
"This line has changed from \"Rum\" to \"Rum Pony\": {\"product_id\": 3, \"name\": \"Rum",
"[namespace] INTEGER REFERENCES [namespaces]([id]), [hash] TEXT, [commit_at] TEXT ); CREATE UNIQUE INDEX [idx_commits_namespace_hash]",
"\"git\", \"add\", \"incidents.json\", \"items.json\", \"items-with-reserved-columns.json\", \"items-with-banned-columns.json\", \"trees.csv\", \"trees.tsv\", \"increment.txt\", ], cwd=str(repo_dir), ) subprocess.call(git_commit",
"[ \"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo), \"--id\", \"product_id\", \"--full-versions\", ] +",
"str(repo / \"increment.txt\"), \"--repo\", str(repo), \"--convert\", '[{\"id\": 1, \"text\": content.decode(\"utf-8\")}]', \"--id\", \"id\", ]",
"\"-m\", \"another\"], cwd=str(repo)) for namespace in (\"one\", \"two\"): run(namespace) db = sqlite_utils.Database(db_path) assert",
"\"column_name\": \"product_id\"}, ] # Test the view view_rows = list( db.query( \"select _version,",
"r in db.query( \"select _item, product_id, _version, name from {}_version order by _item,",
"2, \"_version\": 1, \"name\": \"Tonic\"}, {\"_item\": 2, \"product_id\": None, \"_version\": 2, \"name\": \"Tonic",
"as _commit_at, commits.hash as _commit_hash, {namespace}_version.*, ( select json_group_array(name) from columns where id",
"= [ r for r in db.query( \"select product_id, _version, name from {}_version\".format(namespace)",
"test_file_with_reserved_columns(repo, tmpdir): runner = CliRunner() db_path = str(tmpdir / \"reserved.db\") with runner.isolated_filesystem(): result",
"or \"item\") + \"\\nCREATE INDEX [idx_{}__item]\\n\".format(version_table) + \" ON [{}] ([_item]);\".format(version_table) ) assert",
"\"name\": \"Gin\"}, {\"product_id\": 2, \"name\": \"Tonic 2\"}, # This line has changed from",
"integers with the corresponding commit hash options = [commits[item] if isinstance(item, int) else",
"\" ON [{}] ([_item_id]);\\n\".format(item_table) + \"CREATE TABLE [{}] (\\n\".format(version_table) + \" [_id] INTEGER",
"( select json_group_array(name) from columns where id in ( select column from {namespace}_changed",
"[\"-m\", \"increment {}\".format(i), \"-a\"], cwd=str(repo_dir) ) return repo_dir @pytest.fixture def repo(tmpdir): return make_repo(tmpdir)",
"( ( \"data = json.loads(content)\\n\" \"for item in data:\\n\" ' yield {\"just_name\": item[\"name\"]}'",
"db_path, str(repo / \"increment.txt\"), \"--repo\", str(repo), \"--convert\", '[{\"id\": 1, \"text\": content.decode(\"utf-8\")}]', \"--id\", \"id\",",
"INTEGER,\\n\" \" [name] TEXT\\n\" \");\" ) assert db[\"commits\"].count == 2 # Should have",
"line has changed from \"Rum\" to \"Rum Pony\": {\"product_id\": 3, \"name\": \"Rum Pony\"},",
").strip() + \"\\n\" + expected_create_view(\"item\") + \"\\nCREATE INDEX [idx_item_version__item]\\n\" \" ON [item_version] ([_item]);\"",
"\"name\": \"Rum\"}, ] changed = list( db.query( \"\"\" select {namespace}.product_id, {namespace}_version._version as version,",
"), ) def test_csv_dialect(repo, tmpdir, dialect, expected_schema): runner = CliRunner() db_path = str(tmpdir",
"subprocess.call(git_commit + [\"-m\", \"first\"], cwd=str(repo_dir)) subprocess.call([\"git\", \"branch\", \"-m\", \"main\"], cwd=str(repo_dir)) (repo_dir / \"items.json\").write_text(",
"\"Rum\", }, ] ), \"utf-8\", ) (repo_dir / \"items-with-reserved-columns.json\").write_text( json.dumps( [ { \"_id\":",
"or \"item\" version_table = \"{}_version\".format(item_table) assert db.schema == ( \"CREATE TABLE [namespaces] (\\n\"",
"xml.etree.ElementTree.fromstring(content) return [el.attrib for el in tree.iter(\"item\")] \"\"\" ), \"--import\", \"xml.etree.ElementTree\", ], catch_exceptions=False,",
"\"Tonic 2\"}, {\"product_id\": 3, \"_version\": 1, \"name\": \"Rum\"}, ] changed = list( db.query(",
"db_path = str(tmpdir / \"reserved.db\") with runner.isolated_filesystem(): result = runner.invoke( cli, [ \"file\",",
"\"--full-versions\", ], catch_exceptions=False, ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) assert (",
"else []), catch_exceptions=False, ) assert result2.exit_code == 0 item_version2 = [ r for",
"sqlite_utils.Database(db_path) item_table = namespace or \"item\" version_table = \"{}_version\".format(item_table) assert db.schema == \"\"\"",
"TEXT\\n\" \", [product_id] INTEGER, [name] TEXT, [_commit] INTEGER);\\n\" \"CREATE UNIQUE INDEX [idx_{}__item_id]\\n\".format(item_table) +",
"# Sort order of _changed_columns JSON is undefined, so fix that for row",
"INDEX [idx_{}__item]\\n\".format(version_table) + \" ON [{}] ([_item]);\".format(version_table) ) assert db[\"commits\"].count == 2 #",
"+ \" [_version] INTEGER,\\n\" \" [_commit] INTEGER REFERENCES [commits]([id]),\\n\" \" [product_id] INTEGER,\\n\" \"",
"= list(sorted(json.loads(row[\"_changed_columns\"]))) assert view_rows == [ { \"_version\": 1, \"product_id\": 1, \"name\": \"Gin\",",
"str(tmpdir / \"db.db\") runner.invoke( cli, [ \"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo),",
"[\"3\"]), ([\"--start-at\", 3], [\"3\"]), ([\"--start-after\", 3], []), ), ) def test_skip_options(repo, tmpdir, options,",
"runner = CliRunner() db_path = str(tmpdir / \"db.db\") def run(namespace): result = runner.invoke(",
"INTEGER REFERENCES [commits]([id]),\\n\" \" [product_id] INTEGER,\\n\" \" [name] TEXT\\n\" \");\\n\" + expected_create_view(namespace or",
"or \"item\" version_table = \"{}_version\".format(item_table) assert db.schema == \"\"\" CREATE TABLE [namespaces] (",
"\"Gin\"}, {\"just_name\": \"<NAME>\"}, {\"just_name\": \"Rum\"}, ], ), ), ) def test_convert(repo, tmpdir, convert,",
"] if use_wal: options.append(\"--wal\") result = runner.invoke( cli, options, catch_exceptions=False, ) assert result.exit_code",
"), \"utf-8\", ) subprocess.call(git_commit + [\"-a\", \"-m\", \"another\"], cwd=str(repo)) for namespace in (\"one\",",
") ) ) # Sort order of _changed_columns JSON is undefined, so fix",
"{namespace} on {namespace}._id = {namespace}_version._item order by {namespace}.product_id, {namespace}_version._version, columns.name \"\"\".format( namespace=namespace or",
"\"Tonic 2\"}, {\"_item\": 3, \"product_id\": 3, \"_version\": 1, \"name\": \"Rum\"}, {\"_item\": 3, \"product_id\":",
"INTEGER, [name] TEXT, [_commit] INTEGER);\\n\" \"CREATE UNIQUE INDEX [idx_{}__item_id]\\n\".format(item_table) + \" ON [{}]",
"\"product_id\": None, \"_version\": 2, \"name\": \"Tonic 2\"}, {\"_item\": 3, \"product_id\": 3, \"_version\": 1,",
"] + ([\"--namespace\", namespace] if namespace else []), ) assert result.exit_code == 0",
"Tonic 2, Rum -> Rum Pony assert db[\"one_version\"].count == 5 assert db[\"two_version\"].count ==",
"[product_id] INTEGER,\\n\" \" [name] TEXT\\n\" \");\\n\" + expected_create_view(namespace or \"item\") + \"\\nCREATE INDEX",
"\"_version\": 1, \"name\": \"Rum\"}, ] def test_file_with_reserved_columns(repo, tmpdir): runner = CliRunner() db_path =",
"REFERENCES [item]([_id]), [_version] INTEGER, [_commit] INTEGER REFERENCES [commits]([id]), [TreeID] TEXT, [name] TEXT );\"\"\"",
"2, \"name\": \"Tonic 2\"}, {\"product_id\": 3, \"name\": \"Rum Pony\"}, ] ), \"utf-8\", )",
"@pytest.mark.parametrize( \"dialect,expected_schema\", ( (\"excel\", \"CREATE TABLE [item] (\\n [TreeID] TEXT,\\n [name] TEXT\\n)\"), (\"excel-tab\",",
"\"column_name\": \"product_id\"}, {\"product_id\": 2, \"version\": 2, \"column_name\": \"name\"}, {\"product_id\": 3, \"version\": 1, \"column_name\":",
"db_path, str(repo / \"items.json\"), \"--repo\", str(repo), ] if use_wal: options.append(\"--wal\") result = runner.invoke(",
"[{namespace}_version]([_id]), [column] INTEGER REFERENCES [columns]([id]), PRIMARY KEY ([item_version], [column]) ); {view} CREATE INDEX",
"hash options = [commits[item] if isinstance(item, int) else item for item in options]",
"assert result.exit_code == 0 db = sqlite_utils.Database(db_path) assert db.schema == ( \"CREATE TABLE",
"], catch_exceptions=False, ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) rows = [{k:",
"\"item\"), ) assert db[\"commits\"].count == 2 # Should have no duplicates item_version =",
"\"utf-8\", ) (repo_dir / \"trees.csv\").write_text( \"TreeID,name\\n1,Sophia\\n2,Charlie\", \"utf-8\", ) (repo_dir / \"trees.tsv\").write_text( \"TreeID\\tname\\n1\\tSophia\\n2\\tCharlie\", \"utf-8\",",
"INTEGER REFERENCES [namespaces]([id]),\\n\" \" [hash] TEXT,\\n\" \" [commit_at] TEXT\\n\" \");\\n\" \"CREATE UNIQUE INDEX",
"[idx_{}__item_id]\\n\".format(item_table) + \" ON [{}] ([_item_id]);\\n\".format(item_table) + \"CREATE TABLE [{}] (\\n\".format(version_table) + \"",
"set(db.table_names()) == { \"namespaces\", \"commits\", \"one\", \"one_version\", \"columns\", \"one_changed\", \"two\", \"two_version\", \"two_changed\", }",
"did not change here {\"product_id\": None, \"_version\": 2, \"name\": \"Tonic 2\"}, {\"product_id\": 3,",
"[ { \"product_id\": 1, \"name\": \"Gin\", }, { \"product_id\": 2, \"name\": \"Tonic\", },",
"git_commit + [\"-m\", \"increment {}\".format(i), \"-a\"], cwd=str(repo_dir) ) return repo_dir @pytest.fixture def repo(tmpdir):",
"= CliRunner() db_path = str(tmpdir / \"db.db\") def run(namespace): result = runner.invoke( cli,",
"1, \"column_name\": \"product_id\"}, ] # Test the view view_rows = list( db.query( \"select",
"\"3\"]), ([\"--skip\", 0, \"--skip\", 2], [\"3\"]), ([\"--start-at\", 2], [\"2\", \"3\"]), ([\"--start-after\", 2], [\"3\"]),",
"}, { \"_id\": 2, \"_item\": \"Tonic 2\", \"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\": 6,",
"namespace] if namespace else []), ) namespace = namespace or \"item\" assert result.exit_code",
"assert rows == expected_rows def test_convert_xml(repo, tmpdir): runner = CliRunner() (repo / \"items.xml\").write_text(",
"str(tmpdir / \"reserved.db\") with runner.isolated_filesystem(): result = runner.invoke( cli, [ \"file\", db_path, str(repo",
"from git_history.utils import RESERVED import itertools import json import pytest import subprocess import",
"{\"product_id\": 3, \"_version\": 1, \"name\": \"Rum\"}, ] def test_file_with_reserved_columns(repo, tmpdir): runner = CliRunner()",
"\"Rum Pony\": {\"product_id\": 3, \"name\": \"Rum Pony\"}, ] ), \"utf-8\", ) subprocess.call(git_commit +",
"\"name\": \"Tonic\"}, {\"product_id\": 2, \"_version\": 2, \"name\": \"Tonic 2\"}, {\"product_id\": 3, \"_version\": 1,",
"runner.isolated_filesystem(): result = runner.invoke( cli, [ \"file\", db_path, str(repo / file), \"--repo\", str(repo),",
"\"\\nCREATE INDEX [idx_item_version__item]\\n\" \" ON [item_version] ([_item]);\" ) @pytest.mark.parametrize( \"dialect,expected_schema\", ( (\"excel\", \"CREATE",
"rowid_ from item_version\" ) ] assert item_version == [ { \"_id_\": 1, \"_item_\":",
"= {namespace}_version._commit; \"\"\".format( namespace=namespace ) ).strip() @pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def test_file_without_id(repo, tmpdir, namespace):",
"+ [\"-m\", \"items.xml\"], cwd=str(repo)) db_path = str(tmpdir / \"db.db\") result = runner.invoke( cli,",
"isinstance(item, int) else item for item in options] db_path = str(tmpdir / \"db.db\")",
"in db.query( \"select product_id, _version, name from {}_version\".format(namespace) ) ] assert item_version ==",
"2\"), (3, \"Rum\"), ] @pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def test_file_with_id(repo, tmpdir, namespace): runner =",
"{ \"_id\": 2, \"_item\": \"Tonic 2\", \"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\": 6, },",
"(repo_dir / \"trees.csv\").write_text( \"TreeID,name\\n1,Sophia\\n2,Charlie\", \"utf-8\", ) (repo_dir / \"trees.tsv\").write_text( \"TreeID\\tname\\n1\\tSophia\\n2\\tCharlie\", \"utf-8\", ) (repo_dir",
"); CREATE UNIQUE INDEX [idx_columns_namespace_name] ON [columns] ([namespace], [name]); CREATE TABLE [{namespace}_changed] (",
"2\"}, {\"product_id\": 3, \"name\": \"Rum Pony\"}, ] ), \"utf-8\", ) subprocess.call(git_commit + [\"-a\",",
"/ \"items.json\").write_text( json.dumps( [ {\"product_id\": 1, \"name\": \"Gin\"}, {\"product_id\": 2, \"name\": \"Tonic 2\"},",
"INDEX [idx_commits_namespace_hash] ON [commits] ([namespace], [hash]); CREATE TABLE [item] ( [_id] INTEGER PRIMARY",
"from {namespace}_changed join columns on {namespace}_changed.column = columns.id join {namespace}_version on {namespace}_changed.item_version =",
"] changed = list( db.query( \"\"\" select {namespace}.product_id, {namespace}_version._version as version, columns.name as",
"cwd=str(repo_dir)) # Three more commits to test --skip for i in range(2, 4):",
"namespace=namespace or \"item\" ) ) ) assert changed == [ {\"product_id\": 1, \"version\":",
"], cwd=str(repo_dir), ) subprocess.call(git_commit + [\"-m\", \"first\"], cwd=str(repo_dir)) subprocess.call([\"git\", \"branch\", \"-m\", \"main\"], cwd=str(repo_dir))",
"= str(tmpdir / \"db.db\") with runner.isolated_filesystem(): result = runner.invoke( cli, [ \"file\", db_path,",
"catch_exceptions=False, ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) rows = [{k: v",
"list( reversed( subprocess.check_output([\"git\", \"log\", \"--pretty=format:%H\"], cwd=str(repo)) .decode(\"utf-8\") .split(\"\\n\") ) ) assert len(commits) ==",
"\"name\": \"Tonic\", \"_changed_columns\": [\"name\", \"product_id\"], }, { \"_version\": 2, \"product_id\": None, \"name\": \"Tonic",
"TEXT, [name] TEXT );\"\"\" ).strip() + \"\\n\" + expected_create_view(\"item\") + \"\\nCREATE INDEX [idx_item_version__item]\\n\"",
"TABLE [columns] ( [id] INTEGER PRIMARY KEY, [namespace] INTEGER REFERENCES [namespaces]([id]), [name] TEXT",
"] # Now we edit, commit and try again (repo / \"items.json\").write_text( json.dumps(",
"/ \"db.db\") runner.invoke( cli, [ \"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo), \"--id\",",
"\"incidents.json\", \"items.json\", \"items-with-reserved-columns.json\", \"items-with-banned-columns.json\", \"trees.csv\", \"trees.tsv\", \"increment.txt\", ], cwd=str(repo_dir), ) subprocess.call(git_commit + [\"-m\",",
"rows = [{k: v for k, v in r.items() if k != \"_commit\"}",
"five versions: Gin, Tonic -> Tonic 2, Rum -> Rum Pony assert db[\"one_version\"].count",
"== 5 @pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def test_file_with_id_full_versions(repo, tmpdir, namespace): runner = CliRunner() db_path",
"\"--repo\", str(repo), \"--convert\", textwrap.dedent( \"\"\" tree = xml.etree.ElementTree.fromstring(content) return [el.attrib for el in",
"\"select _id_, _item_, _version_, _commit_, rowid_ from item_version\" ) ] assert item_version ==",
"set(RESERVED) @pytest.mark.parametrize(\"use_wal\", (True, False)) def test_wal(repo, tmpdir, use_wal): runner = CliRunner() db_path =",
"all columns with _ prefixes and no suffix db = sqlite_utils.Database(db_path) with_prefix =",
"3, \"name\": \"Rum Pony\"}, ] ), \"utf-8\", ) subprocess.call(git_commit + [\"-a\", \"-m\", \"another\"],",
"\"_commit_\": \"commit1\", \"rowid_\": 6, }, { \"_id_\": 2, \"_item_\": \"Tonic 2\", \"_version_\": \"v1\",",
"/> <item name=\"two\" value=\"2\" /> </items> \"\"\", \"utf-8\", ) subprocess.call([\"git\", \"add\", \"items.xml\"], cwd=str(repo))",
"{ \"_id\": 1, \"_item\": \"Gin\", \"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\": 5, }, {",
") assert result.exit_code == 0 db = sqlite_utils.Database(db_path) item_table = namespace or \"item\"",
"# This one is used for the README generated by Cog: (repo_dir /",
"), ), ) def test_convert(repo, tmpdir, convert, expected_rows): runner = CliRunner() db_path =",
") ) ] assert item_version2 == [ {\"_item\": 1, \"product_id\": 1, \"_version\": 1,",
"([item_version], [column]) ); {view} CREATE INDEX [idx_{namespace}_version__item] ON [{namespace}_version] ([_item]); \"\"\".strip().format( namespace=namespace or",
"r for r in db.query( \"select product_id, _version, name from {}\".format(version_table) ) ]",
"\"Tonic 2\", \"_changed_columns\": [\"name\"], }, { \"_version\": 1, \"product_id\": 3, \"name\": \"Rum\", \"_changed_columns\":",
"Three more commits to test --skip for i in range(2, 4): (repo_dir /",
"\"\\n\" + expected_create_view(\"item\") + \"\\nCREATE INDEX [idx_item_version__item]\\n\" \" ON [item_version] ([_item]);\" ) @pytest.mark.parametrize(",
"\"Tonic\", \"_version_\": \"v1\", \"_commit_\": \"commit1\", \"rowid_\": 6, }, { \"_id_\": 2, \"_item_\": \"Tonic",
"( [item_version] INTEGER REFERENCES [{namespace}_version]([_id]), [column] INTEGER REFERENCES [columns]([id]), PRIMARY KEY ([item_version], [column])",
"], catch_exceptions=False, ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) assert db[\"item\"].schema ==",
") assert result.exit_code == 0 for namespace in (\"one\", \"two\"): run(namespace) # Now",
"PRIMARY KEY, [name] TEXT ); CREATE UNIQUE INDEX [idx_namespaces_name] ON [namespaces] ([name]); CREATE",
"INTEGER REFERENCES [{namespace}]([_id]), [_version] INTEGER, [_commit] INTEGER REFERENCES [commits]([id]), [product_id] INTEGER, [name] TEXT,",
"# Three more commits to test --skip for i in range(2, 4): (repo_dir",
"\"product_id\", ] + ([\"--namespace\", namespace] if namespace else []), catch_exceptions=False, ) assert result2.exit_code",
"\"_id_\": 2, \"_item_\": \"Tonic\", \"_version_\": \"v1\", \"_commit_\": \"commit1\", \"rowid_\": 6, }, { \"_id_\":",
"ON [commits] ([namespace], [hash]);\\n\" \"CREATE TABLE [{}] (\\n\".format(namespace or \"item\") + \" [product_id]",
"\"v1\", \"_commit\": \"commit1\", \"rowid\": 7, }, ] ), \"utf-8\", ) subprocess.call(git_commit + [\"-m\",",
"[namespaces]([id]), [hash] TEXT, [commit_at] TEXT ); CREATE UNIQUE INDEX [idx_commits_namespace_hash] ON [commits] ([namespace],",
"tmpdir): runner = CliRunner() db_path = str(tmpdir / \"reserved.db\") with runner.isolated_filesystem(): result =",
"assert set(db.table_names()) == { \"namespaces\", \"commits\", \"one\", \"one_version\", \"columns\", \"one_changed\", \"two\", \"two_version\", \"two_changed\",",
"json.loads(content)\\n\" \"for item in data:\\n\" ' yield {\"just_name\": item[\"name\"]}' ), [ {\"just_name\": \"Gin\"},",
"[namespaces] ([name]); CREATE TABLE [commits] ( [id] INTEGER PRIMARY KEY, [namespace] INTEGER REFERENCES",
"\"items.json\").write_text( json.dumps( [ { \"product_id\": 1, \"name\": \"Gin\", }, { \"product_id\": 2, \"name\":",
"[namespaces] ([name]);\\n\" \"CREATE TABLE [commits] (\\n\" \" [id] INTEGER PRIMARY KEY,\\n\" \" [namespace]",
"\"value\": \"1\"}, {\"name\": \"two\", \"value\": \"2\"}, ] @pytest.mark.parametrize( \"options,expected_texts\", ( ([], [\"1\", \"2\",",
") assert changed == [ {\"product_id\": 1, \"version\": 1, \"column_name\": \"name\"}, {\"product_id\": 1,",
"prefixes and no suffix db = sqlite_utils.Database(db_path) with_prefix = {\"rowid\"} for table in",
"/ file), \"--repo\", str(repo), \"--id\", \"TreeID\", \"--csv\", \"--full-versions\", ], catch_exceptions=False, ) assert result.exit_code",
"= CliRunner() commits = list( reversed( subprocess.check_output([\"git\", \"log\", \"--pretty=format:%H\"], cwd=str(repo)) .decode(\"utf-8\") .split(\"\\n\") )",
"\"_version\": 1, \"name\": \"Rum\"}, ] changed = list( db.query( \"\"\" select {namespace}.product_id, {namespace}_version._version",
"\"first\"], cwd=str(repo_dir)) subprocess.call([\"git\", \"branch\", \"-m\", \"main\"], cwd=str(repo_dir)) (repo_dir / \"items.json\").write_text( json.dumps( [ {",
"(\"trees.csv\", \"trees.tsv\")) def test_csv_tsv(repo, tmpdir, file): runner = CliRunner() db_path = str(tmpdir /",
"\"--id\", \"product_id\", ] + ([\"--namespace\", namespace] if namespace else []), ) namespace =",
"\"Type\": \"medical\", }, ] ), \"utf-8\", ) (repo_dir / \"items.json\").write_text( json.dumps( [ {",
"\"select _version, product_id, name, _changed_columns from {}_version_detail\".format( namespace or \"item\" ) ) )",
"\"Rum Pony\"}, ] ), \"utf-8\", ) subprocess.call(git_commit + [\"-a\", \"-m\", \"another\"], cwd=str(repo)) result2",
"] ), \"utf-8\", ) subprocess.call(git_commit + [\"-m\", \"second\", \"-a\"], cwd=str(repo_dir)) # Three more",
"\"data = json.loads(content)\\n\" \"for item in data:\\n\" ' yield {\"just_name\": item[\"name\"]}' ), [",
"yield {\"just_name\": item[\"name\"]}' ), [ {\"just_name\": \"Gin\"}, {\"just_name\": \"Tonic\"}, {\"just_name\": \"Gin\"}, {\"just_name\": \"<NAME>\"},",
"r in db.query( \"select _id_, _item_, _version_, _commit_, rowid_ from item_version\" ) ]",
"\"second\", \"-a\"], cwd=str(repo_dir)) # Three more commits to test --skip for i in",
"\"Gin\"}, {\"product_id\": 2, \"name\": \"Tonic 2\"}, {\"product_id\": 3, \"name\": \"Rum Pony\"}, ] ),",
"of _changed_columns JSON is undefined, so fix that for row in view_rows: row[\"_changed_columns\"]",
"\"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo), ] if use_wal: options.append(\"--wal\") result =",
"\"column_name\": \"name\"}, {\"product_id\": 1, \"version\": 1, \"column_name\": \"product_id\"}, {\"product_id\": 2, \"version\": 1, \"column_name\":",
"from \"Rum\" to \"Rum Pony\": {\"product_id\": 3, \"name\": \"Rum Pony\"}, ] ), \"utf-8\",",
"\"product_id\": 2, \"name\": \"Tonic\", \"_changed_columns\": [\"name\", \"product_id\"], }, { \"_version\": 2, \"product_id\": None,",
"INTEGER REFERENCES [columns]([id]), PRIMARY KEY ([item_version], [column]) ); {view} CREATE INDEX [idx_{namespace}_version__item] ON",
"TEXT,\\n\" \" [commit_at] TEXT\\n\" \");\\n\" \"CREATE UNIQUE INDEX [idx_commits_namespace_hash]\\n\" \" ON [commits] ([namespace],",
"( [id] INTEGER PRIMARY KEY, [namespace] INTEGER REFERENCES [namespaces]([id]), [hash] TEXT, [commit_at] TEXT",
"PRIMARY KEY ([item_version], [column]) ); {view} CREATE INDEX [idx_{namespace}_version__item] ON [{namespace}_version] ([_item]); \"\"\".strip().format(",
"for r in db.query( \"select product_id, _version, name from {}_version\".format(namespace) ) ] assert",
"repo_dir = tmpdir / \"repo\" repo_dir.mkdir() # This one is used for the",
"for r in db[\"item\"].rows] assert rows == expected_rows def test_convert_xml(repo, tmpdir): runner =",
"\" ON [namespaces] ([name]);\\n\" \"CREATE TABLE [commits] (\\n\" \" [id] INTEGER PRIMARY KEY,\\n\"",
"== [ {\"product_id\": 1, \"_version\": 1, \"name\": \"Gin\"}, {\"product_id\": 2, \"_version\": 1, \"name\":",
"\"file\", db_path, str(repo / \"items-with-reserved-columns.json\"), \"--repo\", str(repo), \"--id\", \"_id\", \"--full-versions\", ], catch_exceptions=False, )",
"\"dialect,expected_schema\", ( (\"excel\", \"CREATE TABLE [item] (\\n [TreeID] TEXT,\\n [name] TEXT\\n)\"), (\"excel-tab\", \"CREATE",
"\"Rum\", \"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\": 7, }, ] ), \"utf-8\", ) subprocess.call(git_commit",
"with runner.isolated_filesystem(): result = runner.invoke( cli, [ \"file\", db_path, str(repo / \"trees.csv\"), \"--repo\",",
"/ \"items.json\"), \"--repo\", str(repo), ] if use_wal: options.append(\"--wal\") result = runner.invoke( cli, options,",
"PRIMARY KEY, [_item] INTEGER REFERENCES [item]([_id]), [_version] INTEGER, [_commit] INTEGER REFERENCES [commits]([id]), [TreeID]",
"runner.invoke( cli, options, catch_exceptions=False, ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) expected_journal_mode",
"expected_create_view(namespace): return textwrap.dedent( \"\"\" CREATE VIEW {namespace}_version_detail AS select commits.commit_at as _commit_at, commits.hash",
".decode(\"utf-8\") .split(\"\\n\") ) ) assert len(commits) == 4 # Rewrite options to replace",
"\"Tonic 2\", }, { \"product_id\": 3, \"name\": \"Rum\", }, ] ), \"utf-8\", )",
"repo(tmpdir): return make_repo(tmpdir) def expected_create_view(namespace): return textwrap.dedent( \"\"\" CREATE VIEW {namespace}_version_detail AS select",
"sqlite_utils import textwrap git_commit = [ \"git\", \"-c\", \"user.name='Tests'\", \"-c\", \"user.email='<EMAIL>'\", \"commit\", ]",
"\"_version\": 1, \"name\": \"Rum\"}, ] # Now we edit, commit and try again",
"None, \"_version\": 2, \"name\": \"Tonic 2\"}, {\"product_id\": 3, \"_version\": 1, \"name\": \"Rum\"}, ]",
"[ {\"PRODUCT_ID\": 1, \"NAME\": \"GIN\"}, {\"PRODUCT_ID\": 2, \"NAME\": \"TONIC\"}, {\"PRODUCT_ID\": 1, \"NAME\": \"GIN\"},",
"<items> <item name=\"one\" value=\"1\" /> <item name=\"two\" value=\"2\" /> </items> \"\"\", \"utf-8\", )",
") subprocess.call([\"git\", \"add\", \"items.xml\"], cwd=str(repo)) subprocess.call(git_commit + [\"-m\", \"items.xml\"], cwd=str(repo)) db_path = str(tmpdir",
"INTEGER REFERENCES [commits]([id]), [_id_] INTEGER, [_item_] TEXT, [_version_] TEXT, [_commit_] TEXT, [rowid_] INTEGER",
"[]), ) namespace = namespace or \"item\" assert result.exit_code == 0 db =",
"INTEGER); CREATE UNIQUE INDEX [idx_{namespace}__item_id] ON [{namespace}] ([_item_id]); CREATE TABLE [{namespace}_version] ( [_id]",
"\"Gin\", \"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\": 5, }, { \"_id\": 2, \"_item\": \"Tonic",
"{ \"_id_\": 1, \"_item_\": \"Gin\", \"_version_\": \"v1\", \"_commit_\": \"commit1\", \"rowid_\": 5, }, {",
"if k != \"_commit\"} for r in db[\"item\"].rows] assert rows == expected_rows def",
"\"items.xml\").write_text( \"\"\" <items> <item name=\"one\" value=\"1\" /> <item name=\"two\" value=\"2\" /> </items> \"\"\",",
"import sqlite_utils import textwrap git_commit = [ \"git\", \"-c\", \"user.name='Tests'\", \"-c\", \"user.email='<EMAIL>'\", \"commit\",",
"2\"}, # This line has changed from \"Rum\" to \"Rum Pony\": {\"product_id\": 3,",
"= list( db.query( \"select _version, product_id, name, _changed_columns from {}_version_detail\".format( namespace or \"item\"",
") subprocess.call(git_commit + [\"-a\", \"-m\", \"another\"], cwd=str(repo)) for namespace in (\"one\", \"two\"): run(namespace)",
"TEXT\\n)\"), (\"excel-tab\", \"CREATE TABLE [item] (\\n [TreeID,name] TEXT\\n)\"), ), ) def test_csv_dialect(repo, tmpdir,",
"{\"PRODUCT_ID\": 1, \"NAME\": \"GIN\"}, {\"PRODUCT_ID\": 2, \"NAME\": \"TONIC\"}, {\"PRODUCT_ID\": 1, \"NAME\": \"GIN\"}, {\"PRODUCT_ID\":",
"= ( textwrap.dedent( \"\"\" CREATE TABLE [namespaces] ( [id] INTEGER PRIMARY KEY, [name]",
"Drive\", \"Type\": \"medical\", }, ] ), \"utf-8\", ) (repo_dir / \"items.json\").write_text( json.dumps( [",
"{namespace}_changed.item_version = {namespace}_version._id join {namespace} on {namespace}._id = {namespace}_version._item order by {namespace}.product_id, {namespace}_version._version,",
"3, \"name\": \"Rum\", }, ] ), \"utf-8\", ) (repo_dir / \"items-with-reserved-columns.json\").write_text( json.dumps( [",
"1, \"product_id\": 1, \"name\": \"Gin\", \"_changed_columns\": [\"name\", \"product_id\"], }, { \"_version\": 1, \"product_id\":",
"], ), ), ) def test_convert(repo, tmpdir, convert, expected_rows): runner = CliRunner() db_path",
"def test_file_with_reserved_columns(repo, tmpdir): runner = CliRunner() db_path = str(tmpdir / \"reserved.db\") with runner.isolated_filesystem():",
") # Sort order of _changed_columns JSON is undefined, so fix that for",
"result.exit_code == 0 db = sqlite_utils.Database(db_path) assert db[\"item\"].schema == expected_schema @pytest.mark.parametrize( \"convert,expected_rows\", (",
"{}_version\".format(namespace) ) ] assert item_version == [ {\"product_id\": 1, \"_version\": 1, \"name\": \"Gin\"},",
"\"items-with-reserved-columns.json\", \"items-with-banned-columns.json\", \"trees.csv\", \"trees.tsv\", \"increment.txt\", ], cwd=str(repo_dir), ) subprocess.call(git_commit + [\"-m\", \"first\"], cwd=str(repo_dir))",
"([\"--start-at\", 3], [\"3\"]), ([\"--start-after\", 3], []), ), ) def test_skip_options(repo, tmpdir, options, expected_texts):",
"\"RUM\"}, ], ), # Generator ( ( \"data = json.loads(content)\\n\" \"for item in",
"{ \"_version\": 1, \"product_id\": 3, \"name\": \"Rum\", \"_changed_columns\": [\"name\", \"product_id\"], }, ] @pytest.mark.parametrize(\"namespace\",",
"_changed_columns JSON is undefined, so fix that for row in view_rows: row[\"_changed_columns\"] =",
"\"increment {}\".format(i), \"-a\"], cwd=str(repo_dir) ) return repo_dir @pytest.fixture def repo(tmpdir): return make_repo(tmpdir) def",
"0 item_version2 = [ r for r in db.query( \"select _item, product_id, _version,",
"7, }, ] ), \"utf-8\", ) subprocess.call(git_commit + [\"-m\", \"second\", \"-a\"], cwd=str(repo_dir)) #",
"[name] TEXT, [_commit] INTEGER); CREATE UNIQUE INDEX [idx_{namespace}__item_id] ON [{namespace}] ([_item_id]); CREATE TABLE",
"{\"just_name\": \"Tonic\"}, {\"just_name\": \"Gin\"}, {\"just_name\": \"<NAME>\"}, {\"just_name\": \"Rum\"}, ], ), ), ) def",
"[_commit] INTEGER REFERENCES [commits]([id]),\\n\" \" [product_id] INTEGER,\\n\" \" [name] TEXT\\n\" \");\\n\" + expected_create_view(namespace",
"} # Should be five versions: Gin, Tonic -> Tonic 2, Rum ->",
"This one is used for the README generated by Cog: (repo_dir / \"incidents.json\").write_text(",
"\"name\": \"Gin\"}, {\"product_id\": 2, \"_version\": 1, \"name\": \"Tonic\"}, {\"product_id\": None, \"_version\": 2, \"name\":",
"+ [\"-a\", \"-m\", \"another\"], cwd=str(repo)) for namespace in (\"one\", \"two\"): run(namespace) db =",
"\"db.db\") options = [ \"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo), ] if",
"select column from {namespace}_changed where item_version = {namespace}_version._id ) ) as _changed_columns from",
"\"items.json\"), \"--repo\", str(repo), \"--id\", \"product_id\", \"--full-versions\", ] + ([\"--namespace\", namespace] if namespace else",
"\"\\nCREATE INDEX [idx_item_version__item]\\n\" \" ON [item_version] ([_item]);\" ).strip() assert db.schema == expected_schema item_version",
"TEXT, [_commit] INTEGER); CREATE UNIQUE INDEX [idx_{namespace}__item_id] ON [{namespace}] ([_item_id]); CREATE TABLE [{namespace}_version]",
"test_csv_tsv(repo, tmpdir, file): runner = CliRunner() db_path = str(tmpdir / \"db.db\") with runner.isolated_filesystem():",
"cwd=str(repo_dir)) (repo_dir / \"items.json\").write_text( json.dumps( [ { \"product_id\": 1, \"name\": \"Gin\", }, {",
"[ {\"product_id\": 1, \"name\": \"Gin\"}, {\"product_id\": 2, \"name\": \"Tonic 2\"}, # This line",
"PRIMARY KEY, [_item] INTEGER REFERENCES [{namespace}]([_id]), [_version] INTEGER, [_commit] INTEGER REFERENCES [commits]([id]), [product_id]",
"<item name=\"one\" value=\"1\" /> <item name=\"two\" value=\"2\" /> </items> \"\"\", \"utf-8\", ) subprocess.call([\"git\",",
"\"name\": \"Tonic 2\"}, {\"product_id\": 3, \"_version\": 1, \"name\": \"Rum\"}, ] def test_file_with_reserved_columns(repo, tmpdir):",
"+= [\"--namespace\", namespace] result = runner.invoke(cli, options) assert result.exit_code == 0 db =",
"\"name\": \"Tonic 2\"}, {\"product_id\": 3, \"_version\": 1, \"name\": \"Rum\"}, ] changed = list(",
"4th and Vermont\", \"Type\": \"fire\", }, { \"IncidentID\": \"cde448\", \"Location\": \"555 West Example",
"= sqlite_utils.Database(db_path) assert list(db[\"item\"].rows) == [ {\"name\": \"one\", \"value\": \"1\"}, {\"name\": \"two\", \"value\":",
"\" [product_id] INTEGER,\\n\" \" [name] TEXT\\n\" \");\" ) assert db[\"commits\"].count == 2 #",
"\");\\n\" \"CREATE UNIQUE INDEX [idx_namespaces_name]\\n\" \" ON [namespaces] ([name]);\\n\" \"CREATE TABLE [commits] (\\n\"",
"for r in db.query( \"select _id_, _item_, _version_, _commit_, rowid_ from item_version\" )",
"1, \"name\": \"Tonic\"}, {\"product_id\": 2, \"_version\": 2, \"name\": \"Tonic 2\"}, {\"product_id\": 3, \"_version\":",
"1, \"NAME\": \"GIN\"}, {\"PRODUCT_ID\": 2, \"NAME\": \"TONIC 2\"}, {\"PRODUCT_ID\": 3, \"NAME\": \"RUM\"}, ],",
"str(repo)] if namespace: options += [\"--namespace\", namespace] result = runner.invoke(cli, options) assert result.exit_code",
"join columns on {namespace}_changed.column = columns.id join {namespace}_version on {namespace}_changed.item_version = {namespace}_version._id join",
"\"v1\", \"_commit_\": \"commit1\", \"rowid_\": 6, }, { \"_id_\": 2, \"_item_\": \"Tonic 2\", \"_version_\":",
"( [_id] INTEGER PRIMARY KEY, [_item_id] TEXT , [product_id] INTEGER, [name] TEXT, [_commit]",
"\"one\", \"value\": \"1\"}, {\"name\": \"two\", \"value\": \"2\"}, ] @pytest.mark.parametrize( \"options,expected_texts\", ( ([], [\"1\",",
"\"Rum\"), ] @pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def test_file_with_id(repo, tmpdir, namespace): runner = CliRunner() db_path",
"[{namespace}_changed] ( [item_version] INTEGER REFERENCES [{namespace}_version]([_id]), [column] INTEGER REFERENCES [columns]([id]), PRIMARY KEY ([item_version],",
"CREATE VIEW {namespace}_version_detail AS select commits.commit_at as _commit_at, commits.hash as _commit_hash, {namespace}_version.*, (",
"expected_schema item_version = [ r for r in db.query( \"select _id_, _item_, _version_,",
"{\"just_name\": \"Gin\"}, {\"just_name\": \"Tonic\"}, {\"just_name\": \"Gin\"}, {\"just_name\": \"<NAME>\"}, {\"just_name\": \"Rum\"}, ], ), ),",
"str(tmpdir / \"db.db\") result = runner.invoke( cli, [ \"file\", db_path, str(repo / \"items.xml\"),",
"def test_file_with_id_resume(repo, tmpdir, namespace): runner = CliRunner() db_path = str(tmpdir / \"db.db\") result",
"\" [commit_at] TEXT\\n\" \");\\n\" \"CREATE UNIQUE INDEX [idx_commits_namespace_hash]\\n\" \" ON [commits] ([namespace], [hash]);\\n\"",
"\"one_changed\", \"two\", \"two_version\", \"two_changed\", } # Should be five versions: Gin, Tonic ->",
"[commits]([id]), [product_id] INTEGER, [name] TEXT, [_item_full_hash] TEXT ); CREATE TABLE [columns] ( [id]",
"\"\"\", \"utf-8\", ) subprocess.call([\"git\", \"add\", \"items.xml\"], cwd=str(repo)) subprocess.call(git_commit + [\"-m\", \"items.xml\"], cwd=str(repo)) db_path",
"(\"excel-tab\", \"CREATE TABLE [item] (\\n [TreeID,name] TEXT\\n)\"), ), ) def test_csv_dialect(repo, tmpdir, dialect,",
"[namespaces]([id]), [name] TEXT ); CREATE UNIQUE INDEX [idx_columns_namespace_name] ON [columns] ([namespace], [name]); CREATE",
"test_file_with_id(repo, tmpdir, namespace): runner = CliRunner() db_path = str(tmpdir / \"db.db\") with runner.isolated_filesystem():",
"\"Gin\", \"_version_\": \"v1\", \"_commit_\": \"commit1\", \"rowid_\": 5, }, { \"_id_\": 2, \"_item_\": \"Tonic\",",
"CliRunner() commits = list( reversed( subprocess.check_output([\"git\", \"log\", \"--pretty=format:%H\"], cwd=str(repo)) .decode(\"utf-8\") .split(\"\\n\") ) )",
"TEXT ); CREATE UNIQUE INDEX [idx_commits_namespace_hash] ON [commits] ([namespace], [hash]); CREATE TABLE [item]",
"CliRunner() (repo / \"items.xml\").write_text( \"\"\" <items> <item name=\"one\" value=\"1\" /> <item name=\"two\" value=\"2\"",
"TABLE [item] (\\n [TreeID,name] TEXT\\n)\"), ), ) def test_csv_dialect(repo, tmpdir, dialect, expected_schema): runner",
");\"\"\" ).strip() + \"\\n\" + expected_create_view(\"item\") + \"\\nCREATE INDEX [idx_item_version__item]\\n\" \" ON [item_version]",
"db.schema == expected_schema item_version = [ r for r in db.query( \"select _id_,",
"\"-m\", \"another\"], cwd=str(repo)) result2 = runner.invoke( cli, [ \"file\", db_path, str(repo / \"items.json\"),",
"Pony\"}, ] ), \"utf-8\", ) subprocess.call(git_commit + [\"-a\", \"-m\", \"another\"], cwd=str(repo)) result2 =",
"and try again (repo / \"items.json\").write_text( json.dumps( [ {\"product_id\": 1, \"name\": \"Gin\"}, {\"product_id\":",
"item_version = [ r for r in db.query( \"select _id_, _item_, _version_, _commit_,",
"] ), \"utf-8\", ) (repo_dir / \"items-with-banned-columns.json\").write_text( json.dumps( [ { \"_id_\": 1, \"_version_\":",
"== expected_rows def test_convert_xml(repo, tmpdir): runner = CliRunner() (repo / \"items.xml\").write_text( \"\"\" <items>",
"subprocess.call( [ \"git\", \"add\", \"incidents.json\", \"items.json\", \"items-with-reserved-columns.json\", \"items-with-banned-columns.json\", \"trees.csv\", \"trees.tsv\", \"increment.txt\", ], cwd=str(repo_dir),",
"(repo_dir / \"increment.txt\").write_text(\"1\", \"utf-8\") subprocess.call([\"git\", \"init\"], cwd=str(repo_dir)) subprocess.call( [ \"git\", \"add\", \"incidents.json\", \"items.json\",",
"([namespace], [name]); CREATE TABLE [{namespace}_changed] ( [item_version] INTEGER REFERENCES [{namespace}_version]([_id]), [column] INTEGER REFERENCES",
"TEXT ); CREATE UNIQUE INDEX [idx_namespaces_name] ON [namespaces] ([name]); CREATE TABLE [commits] (",
"\"_changed_columns\": [\"name\", \"product_id\"], }, ] @pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def test_file_with_id_resume(repo, tmpdir, namespace): runner",
"REFERENCES [item]([_id]), [_version] INTEGER, [_commit] INTEGER REFERENCES [commits]([id]), [_id_] INTEGER, [_item_] TEXT, [_version_]",
"= [r[\"text\"] for r in db[\"item_version\"].rows] assert actual_text == expected_texts def test_reserved_columns_are_reserved(tmpdir, repo):",
"subprocess.call( git_commit + [\"-m\", \"increment {}\".format(i), \"-a\"], cwd=str(repo_dir) ) return repo_dir @pytest.fixture def",
"{ \"_id_\": 1, \"_version_\": \"Gin\", } ] ), \"utf-8\", ) (repo_dir / \"trees.csv\").write_text(",
"[_id] INTEGER PRIMARY KEY, [_item_id] TEXT , [_id_] INTEGER, [_item_] TEXT, [_version_] TEXT,",
"INDEX [idx_commits_namespace_hash] ON [commits] ([namespace], [hash]); CREATE TABLE [{namespace}] ( [_id] INTEGER PRIMARY",
"repo): runner = CliRunner() db_path = str(tmpdir / \"db.db\") runner.invoke( cli, [ \"file\",",
"and run again (repo / \"items.json\").write_text( json.dumps( [ {\"product_id\": 1, \"name\": \"Gin\"}, {\"product_id\":",
"str(tmpdir / \"db.db\") with runner.isolated_filesystem(): options = [\"file\", db_path, str(repo / \"items.json\"), \"--repo\",",
"INTEGER PRIMARY KEY, [name] TEXT ); CREATE UNIQUE INDEX [idx_namespaces_name] ON [namespaces] ([name]);",
"TABLE [namespaces] ( [id] INTEGER PRIMARY KEY, [name] TEXT ); CREATE UNIQUE INDEX",
"str(repo / \"trees.csv\"), \"--repo\", str(repo), \"--dialect\", dialect, ], catch_exceptions=False, ) assert result.exit_code ==",
"= [\"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo)] if namespace: options += [\"--namespace\",",
"2\"}, {\"_item\": 3, \"product_id\": 3, \"_version\": 1, \"name\": \"Rum\"}, {\"_item\": 3, \"product_id\": None,",
"\"_version_\": \"v1\", \"_commit_\": \"commit1\", \"rowid_\": 6, }, { \"_id_\": 2, \"_item_\": \"Tonic 2\",",
"runner.invoke( cli, [ \"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo), \"--id\", \"product_id\", \"--namespace\",",
"[_commit] INTEGER REFERENCES [commits]([id]), [product_id] INTEGER, [name] TEXT, [_item_full_hash] TEXT ); CREATE TABLE",
"dialect, ], catch_exceptions=False, ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) assert db[\"item\"].schema",
"( select column from {namespace}_changed where item_version = {namespace}_version._id ) ) as _changed_columns",
"5 assert db[\"two_version\"].count == 5 @pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def test_file_with_id_full_versions(repo, tmpdir, namespace): runner",
"\"items.xml\"], cwd=str(repo)) subprocess.call(git_commit + [\"-m\", \"items.xml\"], cwd=str(repo)) db_path = str(tmpdir / \"db.db\") result",
"\"CREATE TABLE [{}] (\\n\".format(namespace or \"item\") + \" [product_id] INTEGER,\\n\" \" [name] TEXT\\n\"",
"expected_create_view(\"item\") + \"\\nCREATE INDEX [idx_item_version__item]\\n\" \" ON [item_version] ([_item]);\" ).strip() assert db.schema ==",
"\"utf-8\", ) subprocess.call(git_commit + [\"-a\", \"-m\", \"another\"], cwd=str(repo)) result2 = runner.invoke( cli, [",
"INTEGER REFERENCES [namespaces]([id]), [hash] TEXT, [commit_at] TEXT ); CREATE UNIQUE INDEX [idx_commits_namespace_hash] ON",
"r.items() if k != \"_commit\"} for r in db[\"item\"].rows] assert rows == expected_rows",
"6, }, { \"_id_\": 3, \"_item_\": \"Rum\", \"_version_\": \"v1\", \"_commit_\": \"commit1\", \"rowid_\": 7,",
"_commit_, rowid_ from item_version\" ) ] assert item_version == [ { \"_id_\": 1,",
"r in db[\"item\"].rows] assert rows == expected_rows def test_convert_xml(repo, tmpdir): runner = CliRunner()",
"([\"--start-at\", 2], [\"2\", \"3\"]), ([\"--start-after\", 2], [\"3\"]), ([\"--start-at\", 3], [\"3\"]), ([\"--start-after\", 3], []),",
"JSON is undefined, so fix that for row in view_rows: row[\"_changed_columns\"] = list(sorted(json.loads(row[\"_changed_columns\"])))",
"== 5 assert db[\"two_version\"].count == 5 @pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def test_file_with_id_full_versions(repo, tmpdir, namespace):",
"[item]([_id]), [_version] INTEGER, [_commit] INTEGER REFERENCES [commits]([id]), [TreeID] TEXT, [name] TEXT );\"\"\" ).strip()",
"db_path = str(tmpdir / \"db.db\") options = [ \"file\", db_path, str(repo / \"items.json\"),",
"INTEGER PRIMARY KEY, [namespace] INTEGER REFERENCES [namespaces]([id]), [name] TEXT ); CREATE UNIQUE INDEX",
"2, \"_version\": 1, \"name\": \"Tonic\"}, # product_id is None because it did not",
"list( db.query( \"\"\" select {namespace}.product_id, {namespace}_version._version as version, columns.name as column_name from {namespace}_changed",
"\"_version_\": \"v1\", \"_commit_\": \"commit1\", \"rowid_\": 5, }, { \"_id_\": 2, \"_item_\": \"Tonic\", \"_version_\":",
"\"commit1\", \"rowid_\": 5, }, { \"_id_\": 2, \"_item_\": \"Tonic\", \"_version_\": \"v1\", \"_commit_\": \"commit1\",",
"# Should have no duplicates item_version = [ r for r in db.query(",
"{\"product_id\": 1, \"_version\": 1, \"name\": \"Gin\"}, {\"product_id\": 2, \"_version\": 1, \"name\": \"Tonic\"}, {\"product_id\":",
"{ \"product_id\": 2, \"name\": \"Tonic 2\", }, { \"product_id\": 3, \"name\": \"Rum\", },",
"\"Rum\"}, ] # Now we edit, commit and try again (repo / \"items.json\").write_text(",
"runner = CliRunner() db_path = str(tmpdir / \"db.db\") result = runner.invoke( cli, [",
"2, \"product_id\": 2, \"_version\": 1, \"name\": \"Tonic\"}, {\"_item\": 2, \"product_id\": None, \"_version\": 2,",
"\"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\": 6, }, { \"_id\": 3, \"_item\": \"Rum\", \"_version\":",
"+ [\"-m\", \"first\"], cwd=str(repo_dir)) subprocess.call([\"git\", \"branch\", \"-m\", \"main\"], cwd=str(repo_dir)) (repo_dir / \"items.json\").write_text( json.dumps(",
"[name] TEXT ); CREATE UNIQUE INDEX [idx_namespaces_name] ON [namespaces] ([name]); CREATE TABLE [commits]",
"\"db.db\") result = runner.invoke( cli, [ \"file\", db_path, str(repo / \"increment.txt\"), \"--repo\", str(repo),",
"INDEX [idx_namespaces_name] ON [namespaces] ([name]); CREATE TABLE [commits] ( [id] INTEGER PRIMARY KEY,",
"db_path, str(repo / \"items.json\"), \"--repo\", str(repo)] if namespace: options += [\"--namespace\", namespace] result",
"/ \"items.json\"), \"--repo\", str(repo), \"--id\", \"product_id\", ], ) # Find all columns with",
"\"commit\", ] def make_repo(tmpdir): repo_dir = tmpdir / \"repo\" repo_dir.mkdir() # This one",
"[ { \"IncidentID\": \"abc123\", \"Location\": \"Corner of 4th and Vermont\", \"Type\": \"fire\", },",
"== expected_texts def test_reserved_columns_are_reserved(tmpdir, repo): runner = CliRunner() db_path = str(tmpdir / \"db.db\")",
"AS select commits.commit_at as _commit_at, commits.hash as _commit_hash, {namespace}_version.*, ( select json_group_array(name) from",
"\"--repo\", str(repo), \"--id\", \"_id\", \"--full-versions\", ], catch_exceptions=False, ) assert result.exit_code == 0 db",
"[product_id] INTEGER, [name] TEXT, [_commit] INTEGER); CREATE UNIQUE INDEX [idx_{namespace}__item_id] ON [{namespace}] ([_item_id]);",
"use_wal: options.append(\"--wal\") result = runner.invoke( cli, options, catch_exceptions=False, ) assert result.exit_code == 0",
"[\"-a\", \"-m\", \"another\"], cwd=str(repo)) result2 = runner.invoke( cli, [ \"file\", db_path, str(repo /",
"\" [_version] INTEGER,\\n\" \" [_commit] INTEGER REFERENCES [commits]([id]),\\n\" \" [product_id] INTEGER,\\n\" \" [name]",
"or \"item\"].rows] == [ (1, \"Gin\"), (2, \"Tonic\"), (1, \"Gin\"), (2, \"Tonic 2\"),",
"}, { \"_version\": 1, \"product_id\": 3, \"name\": \"Rum\", \"_changed_columns\": [\"name\", \"product_id\"], }, ]",
"str(repo), \"--id\", \"product_id\", ], ) # Find all columns with _ prefixes and",
"subprocess.call(git_commit + [\"-m\", \"second\", \"-a\"], cwd=str(repo_dir)) # Three more commits to test --skip",
"\"_version\": 2, \"name\": \"Tonic 2\"}, {\"product_id\": 3, \"_version\": 1, \"name\": \"Rum\"}, ] def",
"_version, name from {}_version\".format(namespace) ) ] assert item_version == [ {\"product_id\": 1, \"_version\":",
"in r.items() if k != \"_commit\"} for r in db[\"item\"].rows] assert rows ==",
"[\"-m\", \"second\", \"-a\"], cwd=str(repo_dir)) # Three more commits to test --skip for i",
"\"item\" ) ) ) assert changed == [ {\"product_id\": 1, \"version\": 1, \"column_name\":",
"1, \"product_id\": 1, \"_version\": 1, \"name\": \"Gin\"}, {\"_item\": 2, \"product_id\": 2, \"_version\": 1,",
"\"product_id\"}, {\"product_id\": 2, \"version\": 2, \"column_name\": \"name\"}, {\"product_id\": 3, \"version\": 1, \"column_name\": \"name\"},",
"Sort order of _changed_columns JSON is undefined, so fix that for row in",
"\"abc123\", \"Location\": \"Corner of 4th and Vermont\", \"Type\": \"fire\", }, { \"IncidentID\": \"cde448\",",
"for el in tree.iter(\"item\")] \"\"\" ), \"--import\", \"xml.etree.ElementTree\", ], catch_exceptions=False, ) assert result.exit_code",
"cwd=str(repo_dir) ) return repo_dir @pytest.fixture def repo(tmpdir): return make_repo(tmpdir) def expected_create_view(namespace): return textwrap.dedent(",
"duplicates item_version = [ r for r in db.query( \"select product_id, _version, name",
"\"items.xml\"], cwd=str(repo)) db_path = str(tmpdir / \"db.db\") result = runner.invoke( cli, [ \"file\",",
"make_repo(tmpdir): repo_dir = tmpdir / \"repo\" repo_dir.mkdir() # This one is used for",
"namespace or \"item\" version_table = \"{}_version\".format(item_table) assert db.schema == \"\"\" CREATE TABLE [namespaces]",
"[_item_] TEXT, [_version_] TEXT, [_commit_] TEXT, [rowid_] INTEGER );\"\"\" ) + \"\\n\" +",
"by {namespace}.product_id, {namespace}_version._version, columns.name \"\"\".format( namespace=namespace or \"item\" ) ) ) assert changed",
"{ \"product_id\": 3, \"name\": \"Rum\", }, ] ), \"utf-8\", ) (repo_dir / \"items-with-reserved-columns.json\").write_text(",
"), \"--import\", \"xml.etree.ElementTree\", ], catch_exceptions=False, ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path)",
"[\"1\", \"2\", \"3\"]), ([\"--skip\", 0], [\"2\", \"3\"]), ([\"--skip\", 0, \"--skip\", 2], [\"3\"]), ([\"--start-at\",",
"= json.loads(content)\\n\" \"for item in data:\\n\" ' yield {\"just_name\": item[\"name\"]}' ), [ {\"just_name\":",
"+ [\"-a\", \"-m\", \"another\"], cwd=str(repo)) result2 = runner.invoke( cli, [ \"file\", db_path, str(repo",
"\"--id\", \"product_id\", ], ) # Find all columns with _ prefixes and no",
"version_table = \"{}_version\".format(item_table) assert db.schema == ( \"CREATE TABLE [namespaces] (\\n\" \" [id]",
"[commits]([id]), [TreeID] TEXT, [name] TEXT );\"\"\" ).strip() + \"\\n\" + expected_create_view(\"item\") + \"\\nCREATE",
"options = [ \"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo), ] if use_wal:",
"textwrap.dedent( \"\"\" CREATE TABLE [namespaces] ( [id] INTEGER PRIMARY KEY, [name] TEXT );",
"\"name\": \"Rum\"}, ] # Now we edit, commit and try again (repo /",
"== 0 db = sqlite_utils.Database(db_path) expected_schema = ( textwrap.dedent( \"\"\" CREATE TABLE [namespaces]",
"@pytest.mark.parametrize( \"options,expected_texts\", ( ([], [\"1\", \"2\", \"3\"]), ([\"--skip\", 0], [\"2\", \"3\"]), ([\"--skip\", 0,",
"(2, \"Tonic\"), (1, \"Gin\"), (2, \"Tonic 2\"), (3, \"Rum\"), ] @pytest.mark.parametrize(\"namespace\", (None, \"custom\"))",
"{\"product_id\": 3, \"version\": 1, \"column_name\": \"product_id\"}, ] # Test the view view_rows =",
"\"column_name\": \"name\"}, {\"product_id\": 2, \"version\": 1, \"column_name\": \"product_id\"}, {\"product_id\": 2, \"version\": 2, \"column_name\":",
"[commit_at] TEXT\\n\" \");\\n\" \"CREATE UNIQUE INDEX [idx_commits_namespace_hash]\\n\" \" ON [commits] ([namespace], [hash]);\\n\" \"CREATE",
"items.json, commit and run again (repo / \"items.json\").write_text( json.dumps( [ {\"product_id\": 1, \"name\":",
"assert db[\"one_version\"].count == 5 assert db[\"two_version\"].count == 5 @pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def test_file_with_id_full_versions(repo,",
"INTEGER PRIMARY KEY,\\n\" \" [namespace] INTEGER REFERENCES [namespaces]([id]),\\n\" \" [hash] TEXT,\\n\" \" [commit_at]",
"expected_texts def test_reserved_columns_are_reserved(tmpdir, repo): runner = CliRunner() db_path = str(tmpdir / \"db.db\") runner.invoke(",
"[idx_namespaces_name] ON [namespaces] ([name]); CREATE TABLE [commits] ( [id] INTEGER PRIMARY KEY, [namespace]",
"[commits] ( [id] INTEGER PRIMARY KEY, [namespace] INTEGER REFERENCES [namespaces]([id]), [hash] TEXT, [commit_at]",
"\"product_id\", \"--full-versions\", ] + ([\"--namespace\", namespace] if namespace else []), ) assert result.exit_code",
"\"--import\", \"xml.etree.ElementTree\", ], catch_exceptions=False, ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) assert",
"run(namespace): result = runner.invoke( cli, [ \"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo),",
"db.schema == \"\"\" CREATE TABLE [namespaces] ( [id] INTEGER PRIMARY KEY, [name] TEXT",
"{\"product_id\": 3, \"name\": \"Rum Pony\"}, ] ), \"utf-8\", ) subprocess.call(git_commit + [\"-a\", \"-m\",",
"+ expected_create_view(\"item\") + \"\\nCREATE INDEX [idx_item_version__item]\\n\" \" ON [item_version] ([_item]);\" ).strip() assert db.schema",
"{\"product_id\": 2, \"_version\": 1, \"name\": \"Tonic\"}, {\"product_id\": None, \"_version\": 2, \"name\": \"Tonic 2\"},",
"result = runner.invoke( cli, [ \"file\", db_path, str(repo / \"items.json\"), \"--repo\", str(repo), \"--convert\",",
"return make_repo(tmpdir) def expected_create_view(namespace): return textwrap.dedent( \"\"\" CREATE VIEW {namespace}_version_detail AS select commits.commit_at",
"== [ (1, \"Gin\"), (2, \"Tonic\"), (1, \"Gin\"), (2, \"Tonic 2\"), (3, \"Rum\"),",
"db.query( \"select product_id, _version, name from {}\".format(version_table) ) ] assert item_version == [",
"runner.isolated_filesystem(): result = runner.invoke( cli, [ \"file\", db_path, str(repo / \"items-with-reserved-columns.json\"), \"--repo\", str(repo),",
"result.exit_code == 0 db = sqlite_utils.Database(db_path) assert db.schema == ( \"CREATE TABLE [namespaces]",
"sqlite_utils.Database(db_path) actual_text = [r[\"text\"] for r in db[\"item_version\"].rows] assert actual_text == expected_texts def",
"expected_create_view(namespace or \"item\") + \"\\nCREATE INDEX [idx_{}__item]\\n\".format(version_table) + \" ON [{}] ([_item]);\".format(version_table) )",
"@pytest.mark.parametrize(\"file\", (\"trees.csv\", \"trees.tsv\")) def test_csv_tsv(repo, tmpdir, file): runner = CliRunner() db_path = str(tmpdir",
"\"one\", \"one_version\", \"columns\", \"one_changed\", \"two\", \"two_version\", \"two_changed\", } # Should be five versions:",
"expected_texts): runner = CliRunner() commits = list( reversed( subprocess.check_output([\"git\", \"log\", \"--pretty=format:%H\"], cwd=str(repo)) .decode(\"utf-8\")",
"}, ] ), \"utf-8\", ) (repo_dir / \"items-with-reserved-columns.json\").write_text( json.dumps( [ { \"_id\": 1,",
"] def test_file_with_reserved_columns(repo, tmpdir): runner = CliRunner() db_path = str(tmpdir / \"reserved.db\") with",
"\"--id\", \"TreeID\", \"--csv\", \"--full-versions\", ], catch_exceptions=False, ) assert result.exit_code == 0 db =",
"[commits] ([namespace], [hash]);\\n\" \"CREATE TABLE [{}] (\\n\".format(namespace or \"item\") + \" [product_id] INTEGER,\\n\"",
"/> </items> \"\"\", \"utf-8\", ) subprocess.call([\"git\", \"add\", \"items.xml\"], cwd=str(repo)) subprocess.call(git_commit + [\"-m\", \"items.xml\"],",
"the README generated by Cog: (repo_dir / \"incidents.json\").write_text( json.dumps( [ { \"IncidentID\": \"abc123\",",
"), # Generator ( ( \"data = json.loads(content)\\n\" \"for item in data:\\n\" '",
"= [ \"git\", \"-c\", \"user.name='Tests'\", \"-c\", \"user.email='<EMAIL>'\", \"commit\", ] def make_repo(tmpdir): repo_dir =",
"itertools import json import pytest import subprocess import sqlite_utils import textwrap git_commit =",
"\"trees.tsv\").write_text( \"TreeID\\tname\\n1\\tSophia\\n2\\tCharlie\", \"utf-8\", ) (repo_dir / \"increment.txt\").write_text(\"1\", \"utf-8\") subprocess.call([\"git\", \"init\"], cwd=str(repo_dir)) subprocess.call( [",
"+ \" [product_id] INTEGER,\\n\" \" [name] TEXT\\n\" \");\" ) assert db[\"commits\"].count == 2",
"str(repo / \"items.json\"), \"--repo\", str(repo), \"--id\", \"product_id\", \"--namespace\", namespace, ], ) assert result.exit_code",
"in table.columns_dict: if column.startswith(\"_\") and not column.endswith(\"_\"): with_prefix.add(column) assert with_prefix == set(RESERVED) @pytest.mark.parametrize(\"use_wal\",",
"\"Tonic 2\", \"_version_\": \"v1\", \"_commit_\": \"commit1\", \"rowid_\": 6, }, { \"_id_\": 3, \"_item_\":",
"{namespace}_version.*, ( select json_group_array(name) from columns where id in ( select column from",
"2, \"_version\": 2, \"name\": \"Tonic 2\"}, {\"product_id\": 3, \"_version\": 1, \"name\": \"Rum\"}, ]",
"REFERENCES [commits]([id]), [TreeID] TEXT, [name] TEXT );\"\"\" ).strip() + \"\\n\" + expected_create_view(\"item\") +",
"\"options,expected_texts\", ( ([], [\"1\", \"2\", \"3\"]), ([\"--skip\", 0], [\"2\", \"3\"]), ([\"--skip\", 0, \"--skip\",",
"again (repo / \"items.json\").write_text( json.dumps( [ {\"product_id\": 1, \"name\": \"Gin\"}, {\"product_id\": 2, \"name\":",
"r for r in db.query( \"select _id_, _item_, _version_, _commit_, rowid_ from item_version\"",
"for r in db[\"item_version\"].rows] assert actual_text == expected_texts def test_reserved_columns_are_reserved(tmpdir, repo): runner =",
"db[\"item_version\"].rows] assert actual_text == expected_texts def test_reserved_columns_are_reserved(tmpdir, repo): runner = CliRunner() db_path =",
"] assert item_version == [ {\"product_id\": 1, \"_version\": 1, \"name\": \"Gin\"}, {\"product_id\": 2,",
"6, }, { \"_id\": 3, \"_item\": \"Rum\", \"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\": 7,",
"commits on commits.id = {namespace}_version._commit; \"\"\".format( namespace=namespace ) ).strip() @pytest.mark.parametrize(\"namespace\", (None, \"custom\")) def",
"[idx_columns_namespace_name] ON [columns] ([namespace], [name]); CREATE TABLE [{namespace}_changed] ( [item_version] INTEGER REFERENCES [{namespace}_version]([_id]),",
"\"_version\": 1, \"name\": \"Tonic\"}, {\"product_id\": 2, \"_version\": 2, \"name\": \"Tonic 2\"}, {\"product_id\": 3,",
"\"value\": \"2\"}, ] @pytest.mark.parametrize( \"options,expected_texts\", ( ([], [\"1\", \"2\", \"3\"]), ([\"--skip\", 0], [\"2\",",
"view=expected_create_view(namespace or \"item\"), ) assert db[\"commits\"].count == 2 # Should have no duplicates",
"\"_version\": 2, \"name\": \"Tonic 2\"}, {\"_item\": 3, \"product_id\": 3, \"_version\": 1, \"name\": \"Rum\"},",
"INDEX [idx_namespaces_name]\\n\" \" ON [namespaces] ([name]);\\n\" \"CREATE TABLE [commits] (\\n\" \" [id] INTEGER",
"INTEGER );\"\"\" ) + \"\\n\" + expected_create_view(\"item\") + \"\\nCREATE INDEX [idx_item_version__item]\\n\" \" ON",
"test_skip_options(repo, tmpdir, options, expected_texts): runner = CliRunner() commits = list( reversed( subprocess.check_output([\"git\", \"log\",",
"str(tmpdir / \"db.db\") with runner.isolated_filesystem(): result = runner.invoke( cli, [ \"file\", db_path, str(repo",
"runner.invoke( cli, [ \"file\", db_path, str(repo / \"increment.txt\"), \"--repo\", str(repo), \"--convert\", '[{\"id\": 1,",
"\"_id_\": 1, \"_item_\": \"Gin\", \"_version_\": \"v1\", \"_commit_\": \"commit1\", \"rowid_\": 5, }, { \"_id_\":",
"\" [product_id] INTEGER,\\n\" \" [name] TEXT\\n\" \");\\n\" + expected_create_view(namespace or \"item\") + \"\\nCREATE",
"# https://github.com/simonw/git-history/issues/43 runner = CliRunner() db_path = str(tmpdir / \"db.db\") def run(namespace): result",
"def expected_create_view(namespace): return textwrap.dedent( \"\"\" CREATE VIEW {namespace}_version_detail AS select commits.commit_at as _commit_at,",
"KEY,\\n\" \" [name] TEXT\\n\" \");\\n\" \"CREATE UNIQUE INDEX [idx_namespaces_name]\\n\" \" ON [namespaces] ([name]);\\n\"",
"\"product_id\": None, \"_version\": 2, \"name\": \"Rum Pony\"}, ] def test_file_with_id_resume_two_namespaces(repo, tmpdir): # https://github.com/simonw/git-history/issues/43",
"or \"item\"), ) assert db[\"commits\"].count == 2 # Should have no duplicates item_version",
") subprocess.call(git_commit + [\"-m\", \"first\"], cwd=str(repo_dir)) subprocess.call([\"git\", \"branch\", \"-m\", \"main\"], cwd=str(repo_dir)) (repo_dir /",
"assert db[\"commits\"].count == 2 # Should have no duplicates item_version = [ r",
"/ \"db.db\") def run(namespace): result = runner.invoke( cli, [ \"file\", db_path, str(repo /",
"\"_item_\": \"Tonic\", \"_version_\": \"v1\", \"_commit_\": \"commit1\", \"rowid_\": 6, }, { \"_id_\": 2, \"_item_\":",
"subprocess.call(git_commit + [\"-m\", \"items.xml\"], cwd=str(repo)) db_path = str(tmpdir / \"db.db\") result = runner.invoke(",
"[namespaces]([id]),\\n\" \" [hash] TEXT,\\n\" \" [commit_at] TEXT\\n\" \");\\n\" \"CREATE UNIQUE INDEX [idx_commits_namespace_hash]\\n\" \"",
"some duplicates assert [(r[\"product_id\"], r[\"name\"]) for r in db[namespace or \"item\"].rows] == [",
"[namespace] INTEGER REFERENCES [namespaces]([id]), [name] TEXT ); CREATE UNIQUE INDEX [idx_columns_namespace_name] ON [columns]",
"# Generator ( ( \"data = json.loads(content)\\n\" \"for item in data:\\n\" ' yield",
"INTEGER, [name] TEXT, [_item_full_hash] TEXT ); CREATE TABLE [columns] ( [id] INTEGER PRIMARY",
"[_id] INTEGER PRIMARY KEY, [_item] INTEGER REFERENCES [item]([_id]), [_version] INTEGER, [_commit] INTEGER REFERENCES",
"\"\\nCREATE INDEX [idx_{}__item]\\n\".format(version_table) + \" ON [{}] ([_item]);\".format(version_table) ) assert db[\"commits\"].count == 2",
"\"Rum\"}, ] changed = list( db.query( \"\"\" select {namespace}.product_id, {namespace}_version._version as version, columns.name",
"TABLE [item_version] ( [_id] INTEGER PRIMARY KEY, [_item] INTEGER REFERENCES [item]([_id]), [_version] INTEGER,",
") ] assert item_version2 == [ {\"_item\": 1, \"product_id\": 1, \"_version\": 1, \"name\":",
"INTEGER, [_commit] INTEGER); CREATE UNIQUE INDEX [idx_item__item_id] ON [item] ([_item_id]); CREATE TABLE [item_version]",
"ON [item_version] ([_item]);\" ).strip() assert db.schema == expected_schema item_version = [ r for",
"Now modify items.json, commit and run again (repo / \"items.json\").write_text( json.dumps( [ {\"product_id\":",
"\"Tonic\"}, {\"just_name\": \"Gin\"}, {\"just_name\": \"<NAME>\"}, {\"just_name\": \"Rum\"}, ], ), ), ) def test_convert(repo,",
"db = sqlite_utils.Database(db_path) with_prefix = {\"rowid\"} for table in itertools.chain(db.tables, db.views): for column",
"/ \"increment.txt\"), \"--repo\", str(repo), \"--convert\", '[{\"id\": 1, \"text\": content.decode(\"utf-8\")}]', \"--id\", \"id\", ] +",
", [_id_] INTEGER, [_item_] TEXT, [_version_] TEXT, [_commit_] TEXT, [rowid_] INTEGER, [_commit] INTEGER);",
"\"_version\": 1, \"name\": \"Gin\"}, {\"product_id\": 2, \"_version\": 1, \"name\": \"Tonic\"}, {\"product_id\": 2, \"_version\":",
"( ( \"json.loads(content.upper())\", [ {\"PRODUCT_ID\": 1, \"NAME\": \"GIN\"}, {\"PRODUCT_ID\": 2, \"NAME\": \"TONIC\"}, {\"PRODUCT_ID\":",
"reversed( subprocess.check_output([\"git\", \"log\", \"--pretty=format:%H\"], cwd=str(repo)) .decode(\"utf-8\") .split(\"\\n\") ) ) assert len(commits) == 4",
"1, \"name\": \"Rum\"}, ] # Now we edit, commit and try again (repo",
"\"_id\": 2, \"_item\": \"Tonic 2\", \"_version\": \"v1\", \"_commit\": \"commit1\", \"rowid\": 6, }, {",
".split(\"\\n\") ) ) assert len(commits) == 4 # Rewrite options to replace integers",
"has changed from \"Rum\" to \"Rum Pony\": {\"product_id\": 3, \"name\": \"Rum Pony\"}, ]",
"\"CREATE UNIQUE INDEX [idx_commits_namespace_hash]\\n\" \" ON [commits] ([namespace], [hash]);\\n\" \"CREATE TABLE [{}] (\\n\".format(namespace",
"str(repo / file), \"--repo\", str(repo), \"--id\", \"TreeID\", \"--csv\", \"--full-versions\", ], catch_exceptions=False, ) assert",
"\"items-with-reserved-columns.json\"), \"--repo\", str(repo), \"--id\", \"_id\", \"--full-versions\", ], catch_exceptions=False, ) assert result.exit_code == 0",
"0 db = sqlite_utils.Database(db_path) item_table = namespace or \"item\" version_table = \"{}_version\".format(item_table) assert",
"is used for the README generated by Cog: (repo_dir / \"incidents.json\").write_text( json.dumps( [",
"view_rows = list( db.query( \"select _version, product_id, name, _changed_columns from {}_version_detail\".format( namespace or",
"\"NAME\": \"GIN\"}, {\"PRODUCT_ID\": 2, \"NAME\": \"TONIC\"}, {\"PRODUCT_ID\": 1, \"NAME\": \"GIN\"}, {\"PRODUCT_ID\": 2, \"NAME\":",
"\"_item_\": \"Tonic 2\", \"_version_\": \"v1\", \"_commit_\": \"commit1\", \"rowid_\": 6, }, { \"_id_\": 3,",
"result.exit_code == 0 db = sqlite_utils.Database(db_path) assert list(db[\"item\"].rows) == [ {\"name\": \"one\", \"value\":",
"Pony\"}, ] def test_file_with_id_resume_two_namespaces(repo, tmpdir): # https://github.com/simonw/git-history/issues/43 runner = CliRunner() db_path = str(tmpdir",
"\"--skip\", 2], [\"3\"]), ([\"--start-at\", 2], [\"2\", \"3\"]), ([\"--start-after\", 2], [\"3\"]), ([\"--start-at\", 3], [\"3\"]),",
"CREATE TABLE [item_version] ( [_id] INTEGER PRIMARY KEY, [_item] INTEGER REFERENCES [item]([_id]), [_version]",
"+ \"\\nCREATE INDEX [idx_item_version__item]\\n\" \" ON [item_version] ([_item]);\" ) @pytest.mark.parametrize( \"dialect,expected_schema\", ( (\"excel\",",
"sqlite_utils.Database(db_path) assert set(db.table_names()) == { \"namespaces\", \"commits\", \"one\", \"one_version\", \"columns\", \"one_changed\", \"two\", \"two_version\",",
"(\"one\", \"two\"): run(namespace) db = sqlite_utils.Database(db_path) assert set(db.table_names()) == { \"namespaces\", \"commits\", \"one\",",
"1, \"_version_\": \"Gin\", } ] ), \"utf-8\", ) (repo_dir / \"trees.csv\").write_text( \"TreeID,name\\n1,Sophia\\n2,Charlie\", \"utf-8\",",
"), \"utf-8\", ) subprocess.call(git_commit + [\"-a\", \"-m\", \"another\"], cwd=str(repo)) result2 = runner.invoke( cli,",
"be five versions: Gin, Tonic -> Tonic 2, Rum -> Rum Pony assert",
"[_item_id] TEXT , [_id_] INTEGER, [_item_] TEXT, [_version_] TEXT, [_commit_] TEXT, [rowid_] INTEGER,",
"\"product_id\": 3, \"name\": \"Rum\", }, ] ), \"utf-8\", ) (repo_dir / \"items-with-reserved-columns.json\").write_text( json.dumps(",
"str(repo), \"--id\", \"product_id\", ] + ([\"--namespace\", namespace] if namespace else []), catch_exceptions=False, )",
"( [id] INTEGER PRIMARY KEY, [name] TEXT ); CREATE UNIQUE INDEX [idx_namespaces_name] ON",
"== [ {\"_item\": 1, \"product_id\": 1, \"_version\": 1, \"name\": \"Gin\"}, {\"_item\": 2, \"product_id\":",
"\"{}_version\".format(item_table) assert db.schema == \"\"\" CREATE TABLE [namespaces] ( [id] INTEGER PRIMARY KEY,",
"cwd=str(repo_dir)) subprocess.call( [ \"git\", \"add\", \"incidents.json\", \"items.json\", \"items-with-reserved-columns.json\", \"items-with-banned-columns.json\", \"trees.csv\", \"trees.tsv\", \"increment.txt\", ],",
"\"commit1\", \"rowid\": 6, }, { \"_id\": 3, \"_item\": \"Rum\", \"_version\": \"v1\", \"_commit\": \"commit1\",",
"in db.query( \"select product_id, _version, name from {}\".format(version_table) ) ] assert item_version ==",
"\"Tonic 2\"}, {\"product_id\": 3, \"_version\": 1, \"name\": \"Rum\"}, ] def test_file_with_reserved_columns(repo, tmpdir): runner",
"_changed_columns from {namespace}_version join commits on commits.id = {namespace}_version._commit; \"\"\".format( namespace=namespace ) ).strip()",
"\"version\": 1, \"column_name\": \"product_id\"}, {\"product_id\": 2, \"version\": 1, \"column_name\": \"name\"}, {\"product_id\": 2, \"version\":",
"KEY ([item_version], [column]) ); {view} CREATE INDEX [idx_{namespace}_version__item] ON [{namespace}_version] ([_item]); \"\"\".strip().format( namespace=namespace",
"\" [_id] INTEGER PRIMARY KEY,\\n\" \" [_item_id] TEXT\\n\" \", [product_id] INTEGER, [name] TEXT,",
"assert [(r[\"product_id\"], r[\"name\"]) for r in db[namespace or \"item\"].rows] == [ (1, \"Gin\"),",
"tmpdir, convert, expected_rows): runner = CliRunner() db_path = str(tmpdir / \"db.db\") with runner.isolated_filesystem():",
"[ {\"product_id\": 1, \"version\": 1, \"column_name\": \"name\"}, {\"product_id\": 1, \"version\": 1, \"column_name\": \"product_id\"},",
"from {}_version order by _item, _version\".format( namespace ) ) ] assert item_version2 ==",
"runner.isolated_filesystem(): result = runner.invoke( cli, [ \"file\", db_path, str(repo / \"trees.csv\"), \"--repo\", str(repo),",
"[ \"git\", \"add\", \"incidents.json\", \"items.json\", \"items-with-reserved-columns.json\", \"items-with-banned-columns.json\", \"trees.csv\", \"trees.tsv\", \"increment.txt\", ], cwd=str(repo_dir), )",
"\"CREATE TABLE [{}] (\\n\".format(item_table) + \" [_id] INTEGER PRIMARY KEY,\\n\" \" [_item_id] TEXT\\n\"",
"[product_id] INTEGER,\\n\" \" [name] TEXT\\n\" \");\" ) assert db[\"commits\"].count == 2 # Should",
"UNIQUE INDEX [idx_columns_namespace_name] ON [columns] ([namespace], [name]); CREATE TABLE [{namespace}_changed] ( [item_version] INTEGER",
"[ \"file\", db_path, str(repo / \"items.xml\"), \"--repo\", str(repo), \"--convert\", textwrap.dedent( \"\"\" tree =",
"tmpdir / \"repo\" repo_dir.mkdir() # This one is used for the README generated",
"= namespace or \"item\" version_table = \"{}_version\".format(item_table) assert db.schema == \"\"\" CREATE TABLE",
"(\\n\".format(version_table) + \" [_id] INTEGER PRIMARY KEY,\\n\" \" [_item] INTEGER REFERENCES [{}]([_id]),\\n\".format(item_table) +",
"== 4 # Rewrite options to replace integers with the corresponding commit hash",
"\"main\"], cwd=str(repo_dir)) (repo_dir / \"items.json\").write_text( json.dumps( [ { \"product_id\": 1, \"name\": \"Gin\", },",
"+ \"CREATE TABLE [{}] (\\n\".format(version_table) + \" [_id] INTEGER PRIMARY KEY,\\n\" \" [_item]",
"\"medical\", }, ] ), \"utf-8\", ) (repo_dir / \"items.json\").write_text( json.dumps( [ { \"product_id\":",
"rows == expected_rows def test_convert_xml(repo, tmpdir): runner = CliRunner() (repo / \"items.xml\").write_text( \"\"\"",
"\"name\": \"Tonic 2\"}, {\"_item\": 3, \"product_id\": 3, \"_version\": 1, \"name\": \"Rum\"}, {\"_item\": 3,",
"== 0 db = sqlite_utils.Database(db_path) assert db[\"item\"].schema == expected_schema @pytest.mark.parametrize( \"convert,expected_rows\", ( (",
") ) assert len(commits) == 4 # Rewrite options to replace integers with",
"[{namespace}] ([_item_id]); CREATE TABLE [{namespace}_version] ( [_id] INTEGER PRIMARY KEY, [_item] INTEGER REFERENCES",
"} ] ), \"utf-8\", ) (repo_dir / \"trees.csv\").write_text( \"TreeID,name\\n1,Sophia\\n2,Charlie\", \"utf-8\", ) (repo_dir /"
] |
[
"user_trace_token=<PASSWORD>1<PASSWORD>; LGUID=20180611153613-1e11da71-6d4a-11e8-9446-5254005c3644; JSESSIONID=ABAAABAAAGFABEFA887FF2126C2345351E1CF33022A085A; _gid=GA1.2.295504001.1536894927; LGSID=20180914111529-6ee84ad5-b7cc-11e8-b939-5254005c3644; Hm_lvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1536894927; index_location_city=%E5%85%A8%E5%9B%BD; TG-TRACK-CODE=index_navigation; SEARCH_ID=f8b502632588469da5ea73ee9dd382a5; _gat=1; Hm_lpvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1536897145; LGRID=20180914115228-993585b5-b7d1-11e8-b939-5254005c3644', 'Host':",
"'Host': 'www.lagou.com', # 'Referer': 'https://www.lagou.com/zhaopin/Java/?labelWords=label', 'Upgrade-Insecure-Requests': '1', 'User-Agent': '%s' % UserAgent.pc_agent()}, # 简书",
"'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Cache-Control': 'max-age=0', 'Connection': 'keep-alive', 'Cookie': 'GA1.2.151205434.1528702564;",
"<reponame>solider245/Requests_Html_Spider #!/usr/bin/env python # encoding: utf-8 \"\"\" @version: v1.0 @author: W_H_J @license: Apache",
"@version: v1.0 @author: W_H_J @license: Apache Licence @contact: <EMAIL> @software: PyCharm @file: HEADERS.py",
"@license: Apache Licence @contact: <EMAIL> @software: PyCharm @file: HEADERS.py @time: 2018/9/26 17:31 @describe:",
"import UserAgent HEADERS = { # 配置样例 \"heasers\": { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Encoding': 'gzip,",
"'max-age=0', 'Connection': 'keep-alive', 'Cookie': 'GA1.2.151205434.1528702564; user_trace_token=<PASSWORD>1<PASSWORD>; LGUID=20180611153613-1e11da71-6d4a-11e8-9446-5254005c3644; JSESSIONID=ABAAABAAAGFABEFA887FF2126C2345351E1CF33022A085A; _gid=GA1.2.295504001.1536894927; LGSID=20180914111529-6ee84ad5-b7cc-11e8-b939-5254005c3644; Hm_lvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1536894927; index_location_city=%E5%85%A8%E5%9B%BD; TG-TRACK-CODE=index_navigation;",
"# 配置样例 \"heasers\": { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Cache-Control':",
"@time: 2018/9/26 17:31 @describe: 请求头集合--爬虫请求头信息在此配置 'User-Agent': '%s' % UserAgent.pc_agent() 启用轮换浏览器请求头 \"\"\" import os",
"Hm_lpvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1536897145; LGRID=20180914115228-993585b5-b7d1-11e8-b939-5254005c3644', 'Host': 'www.lagou.com', # 'Referer': 'https://www.lagou.com/zhaopin/Java/?labelWords=label', 'Upgrade-Insecure-Requests': '1', 'User-Agent': '%s' % UserAgent.pc_agent()},",
"\"heasers\": { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Cache-Control': 'max-age=0', 'Connection':",
"@describe: 请求头集合--爬虫请求头信息在此配置 'User-Agent': '%s' % UserAgent.pc_agent() 启用轮换浏览器请求头 \"\"\" import os import sys sys.path.append(r'your_path')",
"'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Cache-Control': 'max-age=0', 'Connection': 'keep-alive', 'Host': 'www.jianshu.com',",
"17:31 @describe: 请求头集合--爬虫请求头信息在此配置 'User-Agent': '%s' % UserAgent.pc_agent() 启用轮换浏览器请求头 \"\"\" import os import sys",
"{ # 配置样例 \"heasers\": { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.9',",
"# 'Referer': 'https://www.lagou.com/zhaopin/Java/?labelWords=label', 'Upgrade-Insecure-Requests': '1', 'User-Agent': '%s' % UserAgent.pc_agent()}, # 简书 \"headersJianShun\": {",
"\"\"\" @version: v1.0 @author: W_H_J @license: Apache Licence @contact: <EMAIL> @software: PyCharm @file:",
"'User-Agent': '%s' % UserAgent.pc_agent()}, # 简书 \"headersJianShun\": { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate,",
"sys sys.path.append(r'your_path') sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..')) sys.path.append(\"..\") from BaseFile.UserAgent import UserAgent HEADERS",
"Licence @contact: <EMAIL> @software: PyCharm @file: HEADERS.py @time: 2018/9/26 17:31 @describe: 请求头集合--爬虫请求头信息在此配置 'User-Agent':",
"'User-Agent': '%s' % UserAgent.pc_agent() 启用轮换浏览器请求头 \"\"\" import os import sys sys.path.append(r'your_path') sys.path.append(os.path.abspath(os.path.dirname(__file__) +",
"br', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Cache-Control': 'max-age=0', 'Connection': 'keep-alive', 'Host': 'www.jianshu.com', 'Upgrade-Insecure-Requests': '1', 'User-Agent': '%s'",
"utf-8 \"\"\" @version: v1.0 @author: W_H_J @license: Apache Licence @contact: <EMAIL> @software: PyCharm",
"'Cookie': 'GA1.2.151205434.1528702564; user_trace_token=<PASSWORD>1<PASSWORD>; LGUID=20180611153613-1e11da71-6d4a-11e8-9446-5254005c3644; JSESSIONID=ABAAABAAAGFABEFA887FF2126C2345351E1CF33022A085A; _gid=GA1.2.295504001.1536894927; LGSID=20180914111529-6ee84ad5-b7cc-11e8-b939-5254005c3644; Hm_lvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1536894927; index_location_city=%E5%85%A8%E5%9B%BD; TG-TRACK-CODE=index_navigation; SEARCH_ID=f8b502632588469da5ea73ee9dd382a5; _gat=1; Hm_lpvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1536897145;",
"deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Cache-Control': 'max-age=0', 'Connection': 'keep-alive', 'Host': 'www.jianshu.com', 'Upgrade-Insecure-Requests': '1', 'User-Agent':",
"'www.jianshu.com', 'Upgrade-Insecure-Requests': '1', 'User-Agent': '%s' % UserAgent.pc_agent()}, } if __name__ == '__main__': print(HEADERS['heasers'])",
"v1.0 @author: W_H_J @license: Apache Licence @contact: <EMAIL> @software: PyCharm @file: HEADERS.py @time:",
"@software: PyCharm @file: HEADERS.py @time: 2018/9/26 17:31 @describe: 请求头集合--爬虫请求头信息在此配置 'User-Agent': '%s' % UserAgent.pc_agent()",
"'www.lagou.com', # 'Referer': 'https://www.lagou.com/zhaopin/Java/?labelWords=label', 'Upgrade-Insecure-Requests': '1', 'User-Agent': '%s' % UserAgent.pc_agent()}, # 简书 \"headersJianShun\":",
"'keep-alive', 'Cookie': 'GA1.2.151205434.1528702564; user_trace_token=<PASSWORD>1<PASSWORD>; LGUID=20180611153613-1e11da71-6d4a-11e8-9446-5254005c3644; JSESSIONID=ABAAABAAAGFABEFA887FF2126C2345351E1CF33022A085A; _gid=GA1.2.295504001.1536894927; LGSID=20180914111529-6ee84ad5-b7cc-11e8-b939-5254005c3644; Hm_lvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1536894927; index_location_city=%E5%85%A8%E5%9B%BD; TG-TRACK-CODE=index_navigation; SEARCH_ID=f8b502632588469da5ea73ee9dd382a5; _gat=1;",
"UserAgent.pc_agent()}, # 简书 \"headersJianShun\": { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.9',",
"sys.path.append(\"..\") from BaseFile.UserAgent import UserAgent HEADERS = { # 配置样例 \"heasers\": { 'Accept':",
"_gid=GA1.2.295504001.1536894927; LGSID=20180914111529-6ee84ad5-b7cc-11e8-b939-5254005c3644; Hm_lvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1536894927; index_location_city=%E5%85%A8%E5%9B%BD; TG-TRACK-CODE=index_navigation; SEARCH_ID=f8b502632588469da5ea73ee9dd382a5; _gat=1; Hm_lpvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1536897145; LGRID=20180914115228-993585b5-b7d1-11e8-b939-5254005c3644', 'Host': 'www.lagou.com', # 'Referer':",
"LGUID=20180611153613-1e11da71-6d4a-11e8-9446-5254005c3644; JSESSIONID=ABAAABAAAGFABEFA887FF2126C2345351E1CF33022A085A; _gid=GA1.2.295504001.1536894927; LGSID=20180914111529-6ee84ad5-b7cc-11e8-b939-5254005c3644; Hm_lvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1536894927; index_location_city=%E5%85%A8%E5%9B%BD; TG-TRACK-CODE=index_navigation; SEARCH_ID=f8b502632588469da5ea73ee9dd382a5; _gat=1; Hm_lpvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1536897145; LGRID=20180914115228-993585b5-b7d1-11e8-b939-5254005c3644', 'Host': 'www.lagou.com',",
"简书 \"headersJianShun\": { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Cache-Control': 'max-age=0',",
"'zh-CN,zh;q=0.9', 'Cache-Control': 'max-age=0', 'Connection': 'keep-alive', 'Cookie': 'GA1.2.151205434.1528702564; user_trace_token=<PASSWORD>1<PASSWORD>; LGUID=20180611153613-1e11da71-6d4a-11e8-9446-5254005c3644; JSESSIONID=ABAAABAAAGFABEFA887FF2126C2345351E1CF33022A085A; _gid=GA1.2.295504001.1536894927; LGSID=20180914111529-6ee84ad5-b7cc-11e8-b939-5254005c3644; Hm_lvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1536894927;",
"'GA1.2.151205434.1528702564; user_trace_token=<PASSWORD>1<PASSWORD>; LGUID=20180611153613-1e11da71-6d4a-11e8-9446-5254005c3644; JSESSIONID=ABAAABAAAGFABEFA887FF2126C2345351E1CF33022A085A; _gid=GA1.2.295504001.1536894927; LGSID=20180914111529-6ee84ad5-b7cc-11e8-b939-5254005c3644; Hm_lvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1536894927; index_location_city=%E5%85%A8%E5%9B%BD; TG-TRACK-CODE=index_navigation; SEARCH_ID=f8b502632588469da5ea73ee9dd382a5; _gat=1; Hm_lpvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1536897145; LGRID=20180914115228-993585b5-b7d1-11e8-b939-5254005c3644',",
"sys.path.append(r'your_path') sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..')) sys.path.append(\"..\") from BaseFile.UserAgent import UserAgent HEADERS =",
"Apache Licence @contact: <EMAIL> @software: PyCharm @file: HEADERS.py @time: 2018/9/26 17:31 @describe: 请求头集合--爬虫请求头信息在此配置",
"2018/9/26 17:31 @describe: 请求头集合--爬虫请求头信息在此配置 'User-Agent': '%s' % UserAgent.pc_agent() 启用轮换浏览器请求头 \"\"\" import os import",
"UserAgent HEADERS = { # 配置样例 \"heasers\": { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate,",
"'Connection': 'keep-alive', 'Cookie': 'GA1.2.151205434.1528702564; user_trace_token=<PASSWORD>1<PASSWORD>; LGUID=20180611153613-1e11da71-6d4a-11e8-9446-5254005c3644; JSESSIONID=ABAAABAAAGFABEFA887FF2126C2345351E1CF33022A085A; _gid=GA1.2.295504001.1536894927; LGSID=20180914111529-6ee84ad5-b7cc-11e8-b939-5254005c3644; Hm_lvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1536894927; index_location_city=%E5%85%A8%E5%9B%BD; TG-TRACK-CODE=index_navigation; SEARCH_ID=f8b502632588469da5ea73ee9dd382a5;",
"'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Cache-Control': 'max-age=0', 'Connection': 'keep-alive', 'Host': 'www.jianshu.com', 'Upgrade-Insecure-Requests': '1',",
"'Cache-Control': 'max-age=0', 'Connection': 'keep-alive', 'Host': 'www.jianshu.com', 'Upgrade-Insecure-Requests': '1', 'User-Agent': '%s' % UserAgent.pc_agent()}, }",
"PyCharm @file: HEADERS.py @time: 2018/9/26 17:31 @describe: 请求头集合--爬虫请求头信息在此配置 'User-Agent': '%s' % UserAgent.pc_agent() 启用轮换浏览器请求头",
"\"\"\" import os import sys sys.path.append(r'your_path') sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..')) sys.path.append(\"..\") from",
"'Host': 'www.jianshu.com', 'Upgrade-Insecure-Requests': '1', 'User-Agent': '%s' % UserAgent.pc_agent()}, } if __name__ == '__main__':",
"LGSID=20180914111529-6ee84ad5-b7cc-11e8-b939-5254005c3644; Hm_lvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1536894927; index_location_city=%E5%85%A8%E5%9B%BD; TG-TRACK-CODE=index_navigation; SEARCH_ID=f8b502632588469da5ea73ee9dd382a5; _gat=1; Hm_lpvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1536897145; LGRID=20180914115228-993585b5-b7d1-11e8-b939-5254005c3644', 'Host': 'www.lagou.com', # 'Referer': 'https://www.lagou.com/zhaopin/Java/?labelWords=label',",
"@author: W_H_J @license: Apache Licence @contact: <EMAIL> @software: PyCharm @file: HEADERS.py @time: 2018/9/26",
"'1', 'User-Agent': '%s' % UserAgent.pc_agent()}, # 简书 \"headersJianShun\": { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Encoding': 'gzip,",
"'https://www.lagou.com/zhaopin/Java/?labelWords=label', 'Upgrade-Insecure-Requests': '1', 'User-Agent': '%s' % UserAgent.pc_agent()}, # 简书 \"headersJianShun\": { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',",
"import os import sys sys.path.append(r'your_path') sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..')) sys.path.append(\"..\") from BaseFile.UserAgent",
"LGRID=20180914115228-993585b5-b7d1-11e8-b939-5254005c3644', 'Host': 'www.lagou.com', # 'Referer': 'https://www.lagou.com/zhaopin/Java/?labelWords=label', 'Upgrade-Insecure-Requests': '1', 'User-Agent': '%s' % UserAgent.pc_agent()}, #",
"deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Cache-Control': 'max-age=0', 'Connection': 'keep-alive', 'Cookie': 'GA1.2.151205434.1528702564; user_trace_token=<PASSWORD>1<PASSWORD>; LGUID=20180611153613-1e11da71-6d4a-11e8-9446-5254005c3644; JSESSIONID=ABAAABAAAGFABEFA887FF2126C2345351E1CF33022A085A;",
"import sys sys.path.append(r'your_path') sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..')) sys.path.append(\"..\") from BaseFile.UserAgent import UserAgent",
"UserAgent.pc_agent() 启用轮换浏览器请求头 \"\"\" import os import sys sys.path.append(r'your_path') sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..'))",
"启用轮换浏览器请求头 \"\"\" import os import sys sys.path.append(r'your_path') sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..')) sys.path.append(\"..\")",
"% UserAgent.pc_agent() 启用轮换浏览器请求头 \"\"\" import os import sys sys.path.append(r'your_path') sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' +",
"@file: HEADERS.py @time: 2018/9/26 17:31 @describe: 请求头集合--爬虫请求头信息在此配置 'User-Agent': '%s' % UserAgent.pc_agent() 启用轮换浏览器请求头 \"\"\"",
"os import sys sys.path.append(r'your_path') sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..')) sys.path.append(\"..\") from BaseFile.UserAgent import",
"'max-age=0', 'Connection': 'keep-alive', 'Host': 'www.jianshu.com', 'Upgrade-Insecure-Requests': '1', 'User-Agent': '%s' % UserAgent.pc_agent()}, } if",
"python # encoding: utf-8 \"\"\" @version: v1.0 @author: W_H_J @license: Apache Licence @contact:",
"JSESSIONID=ABAAABAAAGFABEFA887FF2126C2345351E1CF33022A085A; _gid=GA1.2.295504001.1536894927; LGSID=20180914111529-6ee84ad5-b7cc-11e8-b939-5254005c3644; Hm_lvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1536894927; index_location_city=%E5%85%A8%E5%9B%BD; TG-TRACK-CODE=index_navigation; SEARCH_ID=f8b502632588469da5ea73ee9dd382a5; _gat=1; Hm_lpvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1536897145; LGRID=20180914115228-993585b5-b7d1-11e8-b939-5254005c3644', 'Host': 'www.lagou.com', #",
"@contact: <EMAIL> @software: PyCharm @file: HEADERS.py @time: 2018/9/26 17:31 @describe: 请求头集合--爬虫请求头信息在此配置 'User-Agent': '%s'",
"encoding: utf-8 \"\"\" @version: v1.0 @author: W_H_J @license: Apache Licence @contact: <EMAIL> @software:",
"\"headersJianShun\": { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Cache-Control': 'max-age=0', 'Connection':",
"<EMAIL> @software: PyCharm @file: HEADERS.py @time: 2018/9/26 17:31 @describe: 请求头集合--爬虫请求头信息在此配置 'User-Agent': '%s' %",
"W_H_J @license: Apache Licence @contact: <EMAIL> @software: PyCharm @file: HEADERS.py @time: 2018/9/26 17:31",
"'%s' % UserAgent.pc_agent() 启用轮换浏览器请求头 \"\"\" import os import sys sys.path.append(r'your_path') sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/'",
"'Upgrade-Insecure-Requests': '1', 'User-Agent': '%s' % UserAgent.pc_agent()}, # 简书 \"headersJianShun\": { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Encoding':",
"'..')) sys.path.append(\"..\") from BaseFile.UserAgent import UserAgent HEADERS = { # 配置样例 \"heasers\": {",
"'keep-alive', 'Host': 'www.jianshu.com', 'Upgrade-Insecure-Requests': '1', 'User-Agent': '%s' % UserAgent.pc_agent()}, } if __name__ ==",
"请求头集合--爬虫请求头信息在此配置 'User-Agent': '%s' % UserAgent.pc_agent() 启用轮换浏览器请求头 \"\"\" import os import sys sys.path.append(r'your_path') sys.path.append(os.path.abspath(os.path.dirname(__file__)",
"+ '..')) sys.path.append(\"..\") from BaseFile.UserAgent import UserAgent HEADERS = { # 配置样例 \"heasers\":",
"'Accept-Language': 'zh-CN,zh;q=0.9', 'Cache-Control': 'max-age=0', 'Connection': 'keep-alive', 'Host': 'www.jianshu.com', 'Upgrade-Insecure-Requests': '1', 'User-Agent': '%s' %",
"% UserAgent.pc_agent()}, # 简书 \"headersJianShun\": { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language':",
"br', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Cache-Control': 'max-age=0', 'Connection': 'keep-alive', 'Cookie': 'GA1.2.151205434.1528702564; user_trace_token=<PASSWORD>1<PASSWORD>; LGUID=20180611153613-1e11da71-6d4a-11e8-9446-5254005c3644; JSESSIONID=ABAAABAAAGFABEFA887FF2126C2345351E1CF33022A085A; _gid=GA1.2.295504001.1536894927;",
"index_location_city=%E5%85%A8%E5%9B%BD; TG-TRACK-CODE=index_navigation; SEARCH_ID=f8b502632588469da5ea73ee9dd382a5; _gat=1; Hm_lpvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1536897145; LGRID=20180914115228-993585b5-b7d1-11e8-b939-5254005c3644', 'Host': 'www.lagou.com', # 'Referer': 'https://www.lagou.com/zhaopin/Java/?labelWords=label', 'Upgrade-Insecure-Requests': '1',",
"BaseFile.UserAgent import UserAgent HEADERS = { # 配置样例 \"heasers\": { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Encoding':",
"'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Cache-Control': 'max-age=0', 'Connection': 'keep-alive', 'Cookie': 'GA1.2.151205434.1528702564; user_trace_token=<PASSWORD>1<PASSWORD>; LGUID=20180611153613-1e11da71-6d4a-11e8-9446-5254005c3644;",
"'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Cache-Control': 'max-age=0', 'Connection': 'keep-alive', 'Host': 'www.jianshu.com', 'Upgrade-Insecure-Requests':",
"+ '/' + '..')) sys.path.append(\"..\") from BaseFile.UserAgent import UserAgent HEADERS = { #",
"sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..')) sys.path.append(\"..\") from BaseFile.UserAgent import UserAgent HEADERS = {",
"'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Cache-Control': 'max-age=0', 'Connection': 'keep-alive', 'Cookie': 'GA1.2.151205434.1528702564; user_trace_token=<PASSWORD>1<PASSWORD>;",
"HEADERS.py @time: 2018/9/26 17:31 @describe: 请求头集合--爬虫请求头信息在此配置 'User-Agent': '%s' % UserAgent.pc_agent() 启用轮换浏览器请求头 \"\"\" import",
"from BaseFile.UserAgent import UserAgent HEADERS = { # 配置样例 \"heasers\": { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',",
"'%s' % UserAgent.pc_agent()}, # 简书 \"headersJianShun\": { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, br',",
"_gat=1; Hm_lpvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1536897145; LGRID=20180914115228-993585b5-b7d1-11e8-b939-5254005c3644', 'Host': 'www.lagou.com', # 'Referer': 'https://www.lagou.com/zhaopin/Java/?labelWords=label', 'Upgrade-Insecure-Requests': '1', 'User-Agent': '%s' %",
"'zh-CN,zh;q=0.9', 'Cache-Control': 'max-age=0', 'Connection': 'keep-alive', 'Host': 'www.jianshu.com', 'Upgrade-Insecure-Requests': '1', 'User-Agent': '%s' % UserAgent.pc_agent()},",
"SEARCH_ID=f8b502632588469da5ea73ee9dd382a5; _gat=1; Hm_lpvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1536897145; LGRID=20180914115228-993585b5-b7d1-11e8-b939-5254005c3644', 'Host': 'www.lagou.com', # 'Referer': 'https://www.lagou.com/zhaopin/Java/?labelWords=label', 'Upgrade-Insecure-Requests': '1', 'User-Agent': '%s'",
"'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Cache-Control': 'max-age=0', 'Connection': 'keep-alive', 'Cookie':",
"'Accept-Language': 'zh-CN,zh;q=0.9', 'Cache-Control': 'max-age=0', 'Connection': 'keep-alive', 'Cookie': 'GA1.2.151205434.1528702564; user_trace_token=<PASSWORD>1<PASSWORD>; LGUID=20180611153613-1e11da71-6d4a-11e8-9446-5254005c3644; JSESSIONID=ABAAABAAAGFABEFA887FF2126C2345351E1CF33022A085A; _gid=GA1.2.295504001.1536894927; LGSID=20180914111529-6ee84ad5-b7cc-11e8-b939-5254005c3644;",
"TG-TRACK-CODE=index_navigation; SEARCH_ID=f8b502632588469da5ea73ee9dd382a5; _gat=1; Hm_lpvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1536897145; LGRID=20180914115228-993585b5-b7d1-11e8-b939-5254005c3644', 'Host': 'www.lagou.com', # 'Referer': 'https://www.lagou.com/zhaopin/Java/?labelWords=label', 'Upgrade-Insecure-Requests': '1', 'User-Agent':",
"{ 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Cache-Control': 'max-age=0', 'Connection': 'keep-alive',",
"'/' + '..')) sys.path.append(\"..\") from BaseFile.UserAgent import UserAgent HEADERS = { # 配置样例",
"配置样例 \"heasers\": { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Cache-Control': 'max-age=0',",
"'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Cache-Control': 'max-age=0', 'Connection': 'keep-alive', 'Host':",
"'Connection': 'keep-alive', 'Host': 'www.jianshu.com', 'Upgrade-Insecure-Requests': '1', 'User-Agent': '%s' % UserAgent.pc_agent()}, } if __name__",
"#!/usr/bin/env python # encoding: utf-8 \"\"\" @version: v1.0 @author: W_H_J @license: Apache Licence",
"Hm_lvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1536894927; index_location_city=%E5%85%A8%E5%9B%BD; TG-TRACK-CODE=index_navigation; SEARCH_ID=f8b502632588469da5ea73ee9dd382a5; _gat=1; Hm_lpvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1536897145; LGRID=20180914115228-993585b5-b7d1-11e8-b939-5254005c3644', 'Host': 'www.lagou.com', # 'Referer': 'https://www.lagou.com/zhaopin/Java/?labelWords=label', 'Upgrade-Insecure-Requests':",
"# encoding: utf-8 \"\"\" @version: v1.0 @author: W_H_J @license: Apache Licence @contact: <EMAIL>",
"# 简书 \"headersJianShun\": { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Cache-Control':",
"'Cache-Control': 'max-age=0', 'Connection': 'keep-alive', 'Cookie': 'GA1.2.151205434.1528702564; user_trace_token=<PASSWORD>1<PASSWORD>; LGUID=20180611153613-1e11da71-6d4a-11e8-9446-5254005c3644; JSESSIONID=ABAAABAAAGFABEFA887FF2126C2345351E1CF33022A085A; _gid=GA1.2.295504001.1536894927; LGSID=20180914111529-6ee84ad5-b7cc-11e8-b939-5254005c3644; Hm_lvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1536894927; index_location_city=%E5%85%A8%E5%9B%BD;",
"HEADERS = { # 配置样例 \"heasers\": { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, br',",
"'Referer': 'https://www.lagou.com/zhaopin/Java/?labelWords=label', 'Upgrade-Insecure-Requests': '1', 'User-Agent': '%s' % UserAgent.pc_agent()}, # 简书 \"headersJianShun\": { 'Accept':",
"= { # 配置样例 \"heasers\": { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language':"
] |
[
"!= 0 def test_3(): \"\"\" checks that the header has been poped \"\"\"",
"get_input() vch = VcfHeader(i) output = vch.get_raw_header() output_no_chrom = pop_header(output) return output_no_chrom def",
"that output is not empty \"\"\" assert len(get_no_chrom()) != 0 def test_3(): \"\"\"",
"the header has been poped \"\"\" header = VcfHeader(get_input()).extract_header() assert header not in",
"is list def test_2(): \"\"\" checks that output is not empty \"\"\" assert",
"<reponame>arontommi/VCFlat import os from vcflat.HeaderExtraction import VcfHeader, pop_header def get_input(): test_data_dir = os.path.join(os.path.dirname(__file__),",
"= vch.get_raw_header() output_no_chrom = pop_header(output) return output_no_chrom def test_1(): \"\"\" checks that output",
"def test_1(): \"\"\" checks that output is list \"\"\" assert type(get_no_chrom()) is list",
"def get_no_chrom(): i = get_input() vch = VcfHeader(i) output = vch.get_raw_header() output_no_chrom =",
"\"\"\" checks that output is not empty \"\"\" assert len(get_no_chrom()) != 0 def",
"is not empty \"\"\" assert len(get_no_chrom()) != 0 def test_3(): \"\"\" checks that",
"from vcflat.HeaderExtraction import VcfHeader, pop_header def get_input(): test_data_dir = os.path.join(os.path.dirname(__file__), \"..\", \"test_data\") i",
"\"\"\" checks that the header has been poped \"\"\" header = VcfHeader(get_input()).extract_header() assert",
"that the header has been poped \"\"\" header = VcfHeader(get_input()).extract_header() assert header not",
"os from vcflat.HeaderExtraction import VcfHeader, pop_header def get_input(): test_data_dir = os.path.join(os.path.dirname(__file__), \"..\", \"test_data\")",
"os.path.join(test_data_dir, \"test.snpeff.vcf\") return i def get_no_chrom(): i = get_input() vch = VcfHeader(i) output",
"is list \"\"\" assert type(get_no_chrom()) is list def test_2(): \"\"\" checks that output",
"\"test.snpeff.vcf\") return i def get_no_chrom(): i = get_input() vch = VcfHeader(i) output =",
"checks that output is not empty \"\"\" assert len(get_no_chrom()) != 0 def test_3():",
"output = vch.get_raw_header() output_no_chrom = pop_header(output) return output_no_chrom def test_1(): \"\"\" checks that",
"test_data_dir = os.path.join(os.path.dirname(__file__), \"..\", \"test_data\") i = os.path.join(test_data_dir, \"test.snpeff.vcf\") return i def get_no_chrom():",
"len(get_no_chrom()) != 0 def test_3(): \"\"\" checks that the header has been poped",
"pop_header(output) return output_no_chrom def test_1(): \"\"\" checks that output is list \"\"\" assert",
"test_3(): \"\"\" checks that the header has been poped \"\"\" header = VcfHeader(get_input()).extract_header()",
"\"\"\" checks that output is list \"\"\" assert type(get_no_chrom()) is list def test_2():",
"get_no_chrom(): i = get_input() vch = VcfHeader(i) output = vch.get_raw_header() output_no_chrom = pop_header(output)",
"checks that output is list \"\"\" assert type(get_no_chrom()) is list def test_2(): \"\"\"",
"pop_header def get_input(): test_data_dir = os.path.join(os.path.dirname(__file__), \"..\", \"test_data\") i = os.path.join(test_data_dir, \"test.snpeff.vcf\") return",
"test_2(): \"\"\" checks that output is not empty \"\"\" assert len(get_no_chrom()) != 0",
"empty \"\"\" assert len(get_no_chrom()) != 0 def test_3(): \"\"\" checks that the header",
"i = os.path.join(test_data_dir, \"test.snpeff.vcf\") return i def get_no_chrom(): i = get_input() vch =",
"VcfHeader(i) output = vch.get_raw_header() output_no_chrom = pop_header(output) return output_no_chrom def test_1(): \"\"\" checks",
"output_no_chrom def test_1(): \"\"\" checks that output is list \"\"\" assert type(get_no_chrom()) is",
"0 def test_3(): \"\"\" checks that the header has been poped \"\"\" header",
"i def get_no_chrom(): i = get_input() vch = VcfHeader(i) output = vch.get_raw_header() output_no_chrom",
"checks that the header has been poped \"\"\" header = VcfHeader(get_input()).extract_header() assert header",
"= os.path.join(test_data_dir, \"test.snpeff.vcf\") return i def get_no_chrom(): i = get_input() vch = VcfHeader(i)",
"\"\"\" assert len(get_no_chrom()) != 0 def test_3(): \"\"\" checks that the header has",
"return i def get_no_chrom(): i = get_input() vch = VcfHeader(i) output = vch.get_raw_header()",
"test_1(): \"\"\" checks that output is list \"\"\" assert type(get_no_chrom()) is list def",
"vch.get_raw_header() output_no_chrom = pop_header(output) return output_no_chrom def test_1(): \"\"\" checks that output is",
"\"..\", \"test_data\") i = os.path.join(test_data_dir, \"test.snpeff.vcf\") return i def get_no_chrom(): i = get_input()",
"that output is list \"\"\" assert type(get_no_chrom()) is list def test_2(): \"\"\" checks",
"not empty \"\"\" assert len(get_no_chrom()) != 0 def test_3(): \"\"\" checks that the",
"\"test_data\") i = os.path.join(test_data_dir, \"test.snpeff.vcf\") return i def get_no_chrom(): i = get_input() vch",
"= os.path.join(os.path.dirname(__file__), \"..\", \"test_data\") i = os.path.join(test_data_dir, \"test.snpeff.vcf\") return i def get_no_chrom(): i",
"= get_input() vch = VcfHeader(i) output = vch.get_raw_header() output_no_chrom = pop_header(output) return output_no_chrom",
"\"\"\" assert type(get_no_chrom()) is list def test_2(): \"\"\" checks that output is not",
"list def test_2(): \"\"\" checks that output is not empty \"\"\" assert len(get_no_chrom())",
"i = get_input() vch = VcfHeader(i) output = vch.get_raw_header() output_no_chrom = pop_header(output) return",
"import VcfHeader, pop_header def get_input(): test_data_dir = os.path.join(os.path.dirname(__file__), \"..\", \"test_data\") i = os.path.join(test_data_dir,",
"def test_3(): \"\"\" checks that the header has been poped \"\"\" header =",
"output is list \"\"\" assert type(get_no_chrom()) is list def test_2(): \"\"\" checks that",
"get_input(): test_data_dir = os.path.join(os.path.dirname(__file__), \"..\", \"test_data\") i = os.path.join(test_data_dir, \"test.snpeff.vcf\") return i def",
"def test_2(): \"\"\" checks that output is not empty \"\"\" assert len(get_no_chrom()) !=",
"VcfHeader, pop_header def get_input(): test_data_dir = os.path.join(os.path.dirname(__file__), \"..\", \"test_data\") i = os.path.join(test_data_dir, \"test.snpeff.vcf\")",
"os.path.join(os.path.dirname(__file__), \"..\", \"test_data\") i = os.path.join(test_data_dir, \"test.snpeff.vcf\") return i def get_no_chrom(): i =",
"output is not empty \"\"\" assert len(get_no_chrom()) != 0 def test_3(): \"\"\" checks",
"assert len(get_no_chrom()) != 0 def test_3(): \"\"\" checks that the header has been",
"vcflat.HeaderExtraction import VcfHeader, pop_header def get_input(): test_data_dir = os.path.join(os.path.dirname(__file__), \"..\", \"test_data\") i =",
"list \"\"\" assert type(get_no_chrom()) is list def test_2(): \"\"\" checks that output is",
"type(get_no_chrom()) is list def test_2(): \"\"\" checks that output is not empty \"\"\"",
"import os from vcflat.HeaderExtraction import VcfHeader, pop_header def get_input(): test_data_dir = os.path.join(os.path.dirname(__file__), \"..\",",
"def get_input(): test_data_dir = os.path.join(os.path.dirname(__file__), \"..\", \"test_data\") i = os.path.join(test_data_dir, \"test.snpeff.vcf\") return i",
"return output_no_chrom def test_1(): \"\"\" checks that output is list \"\"\" assert type(get_no_chrom())",
"= pop_header(output) return output_no_chrom def test_1(): \"\"\" checks that output is list \"\"\"",
"output_no_chrom = pop_header(output) return output_no_chrom def test_1(): \"\"\" checks that output is list",
"header has been poped \"\"\" header = VcfHeader(get_input()).extract_header() assert header not in get_no_chrom()",
"= VcfHeader(i) output = vch.get_raw_header() output_no_chrom = pop_header(output) return output_no_chrom def test_1(): \"\"\"",
"vch = VcfHeader(i) output = vch.get_raw_header() output_no_chrom = pop_header(output) return output_no_chrom def test_1():",
"assert type(get_no_chrom()) is list def test_2(): \"\"\" checks that output is not empty"
] |
[
"เช่น โชว์ Basic แต่เซฟด้วย B นะ ('B', 'Basic'), ('M', 'Medium'), ('A', 'Advance'), )",
"name = models.CharField(max_length=100) class Meta: verbose_name_plural = \"Category\" def __str__(self): return self.name class",
"allow tage เพื่อให้มันแปลความหมายของ tag ข้างบน def get_comment_count(self): return self.bookcomment_set.count() class BookComment(models.Model): book =",
"แต่เซฟด้วยชุดหน้า เช่น โชว์ Basic แต่เซฟด้วย B นะ ('B', 'Basic'), ('M', 'Medium'), ('A', 'Advance'),",
"('A', 'Advance'), ) class Category(models.Model): name = models.CharField(max_length=100) class Meta: verbose_name_plural = \"Category\"",
"format_html('<img src=\"' + self.image.url + '\" height=\"50px\">') return '' # เช็คว่ามีรูปไหม ถ้ามีก้อโชว ถ้าไม่มีก้อเอาค่าว่างๆออกไป",
"เช็คว่ามีรูปไหม ถ้ามีก้อโชว ถ้าไม่มีก้อเอาค่าว่างๆออกไป show_image.allow_tags = True # allow tage เพื่อให้มันแปลความหมายของ tag ข้างบน def",
"('M', 'Medium'), ('A', 'Advance'), ) class Category(models.Model): name = models.CharField(max_length=100) class Meta: verbose_name_plural",
"โชว์ชุดหลัง แต่เซฟด้วยชุดหน้า เช่น โชว์ Basic แต่เซฟด้วย B นะ ('B', 'Basic'), ('M', 'Medium'), ('A',",
"self.image.url + '\" height=\"50px\">') return '' # เช็คว่ามีรูปไหม ถ้ามีก้อโชว ถ้าไม่มีก้อเอาค่าว่างๆออกไป show_image.allow_tags = True",
"class Meta: verbose_name_plural = \"Author\" def __str__(self): return self.name class Book(models.Model): code =",
"= models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE) author = models.ManyToManyField(Author, blank=True) level = models.CharField(max_length=5, null=True,",
"height=\"50px\">') return '' # เช็คว่ามีรูปไหม ถ้ามีก้อโชว ถ้าไม่มีก้อเอาค่าว่างๆออกไป show_image.allow_tags = True # allow tage",
"price = models.FloatField(default=0) category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE) author = models.ManyToManyField(Author, blank=True)",
"จากข้างบนมาใช้ image = models.FileField(upload_to='upload', null=True, blank=True) # รูปจะถุกเก็บเข้า folder \"upload\" อัตโนมัติ published =",
"return format_html('<img src=\"' + self.image.url + '\" height=\"50px\">') return '' # เช็คว่ามีรูปไหม ถ้ามีก้อโชว",
"src=\"' + self.image.url + '\" height=\"50px\">') return '' # เช็คว่ามีรูปไหม ถ้ามีก้อโชว ถ้าไม่มีก้อเอาค่าว่างๆออกไป show_image.allow_tags",
"<gh_stars>0 from django.db import models from django.utils.html import format_html BOOK_LEVEL_CHOICE = ( #",
"เอา choices จากข้างบนมาใช้ image = models.FileField(upload_to='upload', null=True, blank=True) # รูปจะถุกเก็บเข้า folder \"upload\" อัตโนมัติ",
"def show_image(self): if self.image: return format_html('<img src=\"' + self.image.url + '\" height=\"50px\">') return",
"('B', 'Basic'), ('M', 'Medium'), ('A', 'Advance'), ) class Category(models.Model): name = models.CharField(max_length=100) class",
"null=True, blank=True, on_delete=models.CASCADE) author = models.ManyToManyField(Author, blank=True) level = models.CharField(max_length=5, null=True, blank=True, choices=BOOK_LEVEL_CHOICE)",
") class Category(models.Model): name = models.CharField(max_length=100) class Meta: verbose_name_plural = \"Category\" def __str__(self):",
"comment = models.CharField(max_length=100) rating = models.IntegerField(default=0) class Meta: ordering = ['id'] # เรียงตาม",
"name = models.CharField(max_length=100) class Meta: verbose_name_plural = \"Author\" def __str__(self): return self.name class",
"ข้างบน def get_comment_count(self): return self.bookcomment_set.count() class BookComment(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) comment =",
"self.name class Author(models.Model): name = models.CharField(max_length=100) class Meta: verbose_name_plural = \"Author\" def __str__(self):",
"return '' # เช็คว่ามีรูปไหม ถ้ามีก้อโชว ถ้าไม่มีก้อเอาค่าว่างๆออกไป show_image.allow_tags = True # allow tage เพื่อให้มันแปลความหมายของ",
"import models from django.utils.html import format_html BOOK_LEVEL_CHOICE = ( # โชว์ชุดหลัง แต่เซฟด้วยชุดหน้า เช่น",
"def __str__(self): return self.name class Book(models.Model): code = models.CharField(max_length=10, unique=True) slug = models.SlugField(max_length=200,",
"code = models.CharField(max_length=10, unique=True) slug = models.SlugField(max_length=200, unique=True) name = models.CharField(max_length=100) description =",
"'Advance'), ) class Category(models.Model): name = models.CharField(max_length=100) class Meta: verbose_name_plural = \"Category\" def",
"folder \"upload\" อัตโนมัติ published = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class",
"slug = models.SlugField(max_length=200, unique=True) name = models.CharField(max_length=100) description = models.TextField(null=True, blank=True) price =",
"= models.CharField(max_length=100) description = models.TextField(null=True, blank=True) price = models.FloatField(default=0) category = models.ForeignKey(Category, null=True,",
"self.name def show_image(self): if self.image: return format_html('<img src=\"' + self.image.url + '\" height=\"50px\">')",
"= \"Book\" def __str__(self): return self.name def show_image(self): if self.image: return format_html('<img src=\"'",
"models.IntegerField(default=0) class Meta: ordering = ['id'] # เรียงตาม id จากน้อยไปมาก (id ไม่มีใน Model",
"Category(models.Model): name = models.CharField(max_length=100) class Meta: verbose_name_plural = \"Category\" def __str__(self): return self.name",
"blank=True) # รูปจะถุกเก็บเข้า folder \"upload\" อัตโนมัติ published = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) updated",
"โชว์ Basic แต่เซฟด้วย B นะ ('B', 'Basic'), ('M', 'Medium'), ('A', 'Advance'), ) class",
"self.image: return format_html('<img src=\"' + self.image.url + '\" height=\"50px\">') return '' # เช็คว่ามีรูปไหม",
"= models.DateTimeField(auto_now=True) class Meta: ordering = ['-code'] # ถ้ามีติดลบนำหน้า คือเรียงจากมากไปน้อย verbose_name_plural = \"Book\"",
"= ['-code'] # ถ้ามีติดลบนำหน้า คือเรียงจากมากไปน้อย verbose_name_plural = \"Book\" def __str__(self): return self.name def",
"class BookComment(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) comment = models.CharField(max_length=100) rating = models.IntegerField(default=0) class",
"Basic แต่เซฟด้วย B นะ ('B', 'Basic'), ('M', 'Medium'), ('A', 'Advance'), ) class Category(models.Model):",
"return self.name class Author(models.Model): name = models.CharField(max_length=100) class Meta: verbose_name_plural = \"Author\" def",
"models.CharField(max_length=100) class Meta: verbose_name_plural = \"Category\" def __str__(self): return self.name class Author(models.Model): name",
"เรียงตาม id จากน้อยไปมาก (id ไม่มีใน Model แต่ Django สร้างให้เราแล้วนะ) verbose_name_plural = \"Book Comment\"",
"['id'] # เรียงตาม id จากน้อยไปมาก (id ไม่มีใน Model แต่ Django สร้างให้เราแล้วนะ) verbose_name_plural =",
"= models.CharField(max_length=5, null=True, blank=True, choices=BOOK_LEVEL_CHOICE) # เอา choices จากข้างบนมาใช้ image = models.FileField(upload_to='upload', null=True,",
"verbose_name_plural = \"Category\" def __str__(self): return self.name class Author(models.Model): name = models.CharField(max_length=100) class",
"= models.ManyToManyField(Author, blank=True) level = models.CharField(max_length=5, null=True, blank=True, choices=BOOK_LEVEL_CHOICE) # เอา choices จากข้างบนมาใช้",
"Author(models.Model): name = models.CharField(max_length=100) class Meta: verbose_name_plural = \"Author\" def __str__(self): return self.name",
"(id ไม่มีใน Model แต่ Django สร้างให้เราแล้วนะ) verbose_name_plural = \"Book Comment\" def __str__(self): return",
"from django.utils.html import format_html BOOK_LEVEL_CHOICE = ( # โชว์ชุดหลัง แต่เซฟด้วยชุดหน้า เช่น โชว์ Basic",
"= models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ['-code']",
"return self.name class Book(models.Model): code = models.CharField(max_length=10, unique=True) slug = models.SlugField(max_length=200, unique=True) name",
"= \"Author\" def __str__(self): return self.name class Book(models.Model): code = models.CharField(max_length=10, unique=True) slug",
"blank=True, choices=BOOK_LEVEL_CHOICE) # เอา choices จากข้างบนมาใช้ image = models.FileField(upload_to='upload', null=True, blank=True) # รูปจะถุกเก็บเข้า",
"models.ForeignKey(Book, on_delete=models.CASCADE) comment = models.CharField(max_length=100) rating = models.IntegerField(default=0) class Meta: ordering = ['id']",
"models from django.utils.html import format_html BOOK_LEVEL_CHOICE = ( # โชว์ชุดหลัง แต่เซฟด้วยชุดหน้า เช่น โชว์",
"models.TextField(null=True, blank=True) price = models.FloatField(default=0) category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE) author =",
"models.FileField(upload_to='upload', null=True, blank=True) # รูปจะถุกเก็บเข้า folder \"upload\" อัตโนมัติ published = models.BooleanField(default=False) created =",
"= models.TextField(null=True, blank=True) price = models.FloatField(default=0) category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE) author",
"= ( # โชว์ชุดหลัง แต่เซฟด้วยชุดหน้า เช่น โชว์ Basic แต่เซฟด้วย B นะ ('B', 'Basic'),",
"blank=True) level = models.CharField(max_length=5, null=True, blank=True, choices=BOOK_LEVEL_CHOICE) # เอา choices จากข้างบนมาใช้ image =",
"__str__(self): return self.name class Book(models.Model): code = models.CharField(max_length=10, unique=True) slug = models.SlugField(max_length=200, unique=True)",
"\"Author\" def __str__(self): return self.name class Book(models.Model): code = models.CharField(max_length=10, unique=True) slug =",
"= models.CharField(max_length=100) rating = models.IntegerField(default=0) class Meta: ordering = ['id'] # เรียงตาม id",
"models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE) author = models.ManyToManyField(Author, blank=True) level = models.CharField(max_length=5, null=True, blank=True,",
"level = models.CharField(max_length=5, null=True, blank=True, choices=BOOK_LEVEL_CHOICE) # เอา choices จากข้างบนมาใช้ image = models.FileField(upload_to='upload',",
"author = models.ManyToManyField(Author, blank=True) level = models.CharField(max_length=5, null=True, blank=True, choices=BOOK_LEVEL_CHOICE) # เอา choices",
"'\" height=\"50px\">') return '' # เช็คว่ามีรูปไหม ถ้ามีก้อโชว ถ้าไม่มีก้อเอาค่าว่างๆออกไป show_image.allow_tags = True # allow",
"['-code'] # ถ้ามีติดลบนำหน้า คือเรียงจากมากไปน้อย verbose_name_plural = \"Book\" def __str__(self): return self.name def show_image(self):",
"class Meta: verbose_name_plural = \"Category\" def __str__(self): return self.name class Author(models.Model): name =",
"from django.db import models from django.utils.html import format_html BOOK_LEVEL_CHOICE = ( # โชว์ชุดหลัง",
"self.name class Book(models.Model): code = models.CharField(max_length=10, unique=True) slug = models.SlugField(max_length=200, unique=True) name =",
"BookComment(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) comment = models.CharField(max_length=100) rating = models.IntegerField(default=0) class Meta:",
"+ self.image.url + '\" height=\"50px\">') return '' # เช็คว่ามีรูปไหม ถ้ามีก้อโชว ถ้าไม่มีก้อเอาค่าว่างๆออกไป show_image.allow_tags =",
"\"Category\" def __str__(self): return self.name class Author(models.Model): name = models.CharField(max_length=100) class Meta: verbose_name_plural",
"null=True, blank=True) # รูปจะถุกเก็บเข้า folder \"upload\" อัตโนมัติ published = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True)",
"unique=True) slug = models.SlugField(max_length=200, unique=True) name = models.CharField(max_length=100) description = models.TextField(null=True, blank=True) price",
"class Author(models.Model): name = models.CharField(max_length=100) class Meta: verbose_name_plural = \"Author\" def __str__(self): return",
"( # โชว์ชุดหลัง แต่เซฟด้วยชุดหน้า เช่น โชว์ Basic แต่เซฟด้วย B นะ ('B', 'Basic'), ('M',",
"Meta: verbose_name_plural = \"Category\" def __str__(self): return self.name class Author(models.Model): name = models.CharField(max_length=100)",
"'Medium'), ('A', 'Advance'), ) class Category(models.Model): name = models.CharField(max_length=100) class Meta: verbose_name_plural =",
"= models.FloatField(default=0) category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE) author = models.ManyToManyField(Author, blank=True) level",
"ordering = ['-code'] # ถ้ามีติดลบนำหน้า คือเรียงจากมากไปน้อย verbose_name_plural = \"Book\" def __str__(self): return self.name",
"unique=True) name = models.CharField(max_length=100) description = models.TextField(null=True, blank=True) price = models.FloatField(default=0) category =",
"id จากน้อยไปมาก (id ไม่มีใน Model แต่ Django สร้างให้เราแล้วนะ) verbose_name_plural = \"Book Comment\" def",
"คือเรียงจากมากไปน้อย verbose_name_plural = \"Book\" def __str__(self): return self.name def show_image(self): if self.image: return",
"+ '\" height=\"50px\">') return '' # เช็คว่ามีรูปไหม ถ้ามีก้อโชว ถ้าไม่มีก้อเอาค่าว่างๆออกไป show_image.allow_tags = True #",
"= models.IntegerField(default=0) class Meta: ordering = ['id'] # เรียงตาม id จากน้อยไปมาก (id ไม่มีใน",
"tag ข้างบน def get_comment_count(self): return self.bookcomment_set.count() class BookComment(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) comment",
"'Basic'), ('M', 'Medium'), ('A', 'Advance'), ) class Category(models.Model): name = models.CharField(max_length=100) class Meta:",
"BOOK_LEVEL_CHOICE = ( # โชว์ชุดหลัง แต่เซฟด้วยชุดหน้า เช่น โชว์ Basic แต่เซฟด้วย B นะ ('B',",
"# เอา choices จากข้างบนมาใช้ image = models.FileField(upload_to='upload', null=True, blank=True) # รูปจะถุกเก็บเข้า folder \"upload\"",
"= models.FileField(upload_to='upload', null=True, blank=True) # รูปจะถุกเก็บเข้า folder \"upload\" อัตโนมัติ published = models.BooleanField(default=False) created",
"อัตโนมัติ published = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering",
"นะ ('B', 'Basic'), ('M', 'Medium'), ('A', 'Advance'), ) class Category(models.Model): name = models.CharField(max_length=100)",
"__str__(self): return self.name def show_image(self): if self.image: return format_html('<img src=\"' + self.image.url +",
"choices จากข้างบนมาใช้ image = models.FileField(upload_to='upload', null=True, blank=True) # รูปจะถุกเก็บเข้า folder \"upload\" อัตโนมัติ published",
"= models.CharField(max_length=100) class Meta: verbose_name_plural = \"Author\" def __str__(self): return self.name class Book(models.Model):",
"\"upload\" อัตโนมัติ published = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta:",
"models.FloatField(default=0) category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE) author = models.ManyToManyField(Author, blank=True) level =",
"True # allow tage เพื่อให้มันแปลความหมายของ tag ข้างบน def get_comment_count(self): return self.bookcomment_set.count() class BookComment(models.Model):",
"= models.ForeignKey(Book, on_delete=models.CASCADE) comment = models.CharField(max_length=100) rating = models.IntegerField(default=0) class Meta: ordering =",
"Book(models.Model): code = models.CharField(max_length=10, unique=True) slug = models.SlugField(max_length=200, unique=True) name = models.CharField(max_length=100) description",
"= \"Category\" def __str__(self): return self.name class Author(models.Model): name = models.CharField(max_length=100) class Meta:",
"blank=True) price = models.FloatField(default=0) category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE) author = models.ManyToManyField(Author,",
"image = models.FileField(upload_to='upload', null=True, blank=True) # รูปจะถุกเก็บเข้า folder \"upload\" อัตโนมัติ published = models.BooleanField(default=False)",
"# เรียงตาม id จากน้อยไปมาก (id ไม่มีใน Model แต่ Django สร้างให้เราแล้วนะ) verbose_name_plural = \"Book",
"def get_comment_count(self): return self.bookcomment_set.count() class BookComment(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) comment = models.CharField(max_length=100)",
"verbose_name_plural = \"Book\" def __str__(self): return self.name def show_image(self): if self.image: return format_html('<img",
"self.bookcomment_set.count() class BookComment(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) comment = models.CharField(max_length=100) rating = models.IntegerField(default=0)",
"Meta: ordering = ['id'] # เรียงตาม id จากน้อยไปมาก (id ไม่มีใน Model แต่ Django",
"on_delete=models.CASCADE) author = models.ManyToManyField(Author, blank=True) level = models.CharField(max_length=5, null=True, blank=True, choices=BOOK_LEVEL_CHOICE) # เอา",
"django.utils.html import format_html BOOK_LEVEL_CHOICE = ( # โชว์ชุดหลัง แต่เซฟด้วยชุดหน้า เช่น โชว์ Basic แต่เซฟด้วย",
"แต่เซฟด้วย B นะ ('B', 'Basic'), ('M', 'Medium'), ('A', 'Advance'), ) class Category(models.Model): name",
"category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE) author = models.ManyToManyField(Author, blank=True) level = models.CharField(max_length=5,",
"models.CharField(max_length=5, null=True, blank=True, choices=BOOK_LEVEL_CHOICE) # เอา choices จากข้างบนมาใช้ image = models.FileField(upload_to='upload', null=True, blank=True)",
"ถ้าไม่มีก้อเอาค่าว่างๆออกไป show_image.allow_tags = True # allow tage เพื่อให้มันแปลความหมายของ tag ข้างบน def get_comment_count(self): return",
"if self.image: return format_html('<img src=\"' + self.image.url + '\" height=\"50px\">') return '' #",
"class Meta: ordering = ['id'] # เรียงตาม id จากน้อยไปมาก (id ไม่มีใน Model แต่",
"ordering = ['id'] # เรียงตาม id จากน้อยไปมาก (id ไม่มีใน Model แต่ Django สร้างให้เราแล้วนะ)",
"format_html BOOK_LEVEL_CHOICE = ( # โชว์ชุดหลัง แต่เซฟด้วยชุดหน้า เช่น โชว์ Basic แต่เซฟด้วย B นะ",
"class Book(models.Model): code = models.CharField(max_length=10, unique=True) slug = models.SlugField(max_length=200, unique=True) name = models.CharField(max_length=100)",
"= models.SlugField(max_length=200, unique=True) name = models.CharField(max_length=100) description = models.TextField(null=True, blank=True) price = models.FloatField(default=0)",
"= models.CharField(max_length=100) class Meta: verbose_name_plural = \"Category\" def __str__(self): return self.name class Author(models.Model):",
"models.CharField(max_length=10, unique=True) slug = models.SlugField(max_length=200, unique=True) name = models.CharField(max_length=100) description = models.TextField(null=True, blank=True)",
"'' # เช็คว่ามีรูปไหม ถ้ามีก้อโชว ถ้าไม่มีก้อเอาค่าว่างๆออกไป show_image.allow_tags = True # allow tage เพื่อให้มันแปลความหมายของ tag",
"tage เพื่อให้มันแปลความหมายของ tag ข้างบน def get_comment_count(self): return self.bookcomment_set.count() class BookComment(models.Model): book = models.ForeignKey(Book,",
"show_image.allow_tags = True # allow tage เพื่อให้มันแปลความหมายของ tag ข้างบน def get_comment_count(self): return self.bookcomment_set.count()",
"django.db import models from django.utils.html import format_html BOOK_LEVEL_CHOICE = ( # โชว์ชุดหลัง แต่เซฟด้วยชุดหน้า",
"blank=True, on_delete=models.CASCADE) author = models.ManyToManyField(Author, blank=True) level = models.CharField(max_length=5, null=True, blank=True, choices=BOOK_LEVEL_CHOICE) #",
"verbose_name_plural = \"Author\" def __str__(self): return self.name class Book(models.Model): code = models.CharField(max_length=10, unique=True)",
"# allow tage เพื่อให้มันแปลความหมายของ tag ข้างบน def get_comment_count(self): return self.bookcomment_set.count() class BookComment(models.Model): book",
"models.CharField(max_length=100) rating = models.IntegerField(default=0) class Meta: ordering = ['id'] # เรียงตาม id จากน้อยไปมาก",
"name = models.CharField(max_length=100) description = models.TextField(null=True, blank=True) price = models.FloatField(default=0) category = models.ForeignKey(Category,",
"# ถ้ามีติดลบนำหน้า คือเรียงจากมากไปน้อย verbose_name_plural = \"Book\" def __str__(self): return self.name def show_image(self): if",
"return self.name def show_image(self): if self.image: return format_html('<img src=\"' + self.image.url + '\"",
"จากน้อยไปมาก (id ไม่มีใน Model แต่ Django สร้างให้เราแล้วนะ) verbose_name_plural = \"Book Comment\" def __str__(self):",
"import format_html BOOK_LEVEL_CHOICE = ( # โชว์ชุดหลัง แต่เซฟด้วยชุดหน้า เช่น โชว์ Basic แต่เซฟด้วย B",
"published = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering =",
"models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ['-code'] # ถ้ามีติดลบนำหน้า คือเรียงจากมากไปน้อย verbose_name_plural",
"rating = models.IntegerField(default=0) class Meta: ordering = ['id'] # เรียงตาม id จากน้อยไปมาก (id",
"= True # allow tage เพื่อให้มันแปลความหมายของ tag ข้างบน def get_comment_count(self): return self.bookcomment_set.count() class",
"B นะ ('B', 'Basic'), ('M', 'Medium'), ('A', 'Advance'), ) class Category(models.Model): name =",
"updated = models.DateTimeField(auto_now=True) class Meta: ordering = ['-code'] # ถ้ามีติดลบนำหน้า คือเรียงจากมากไปน้อย verbose_name_plural =",
"created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ['-code'] # ถ้ามีติดลบนำหน้า",
"ถ้ามีก้อโชว ถ้าไม่มีก้อเอาค่าว่างๆออกไป show_image.allow_tags = True # allow tage เพื่อให้มันแปลความหมายของ tag ข้างบน def get_comment_count(self):",
"models.CharField(max_length=100) class Meta: verbose_name_plural = \"Author\" def __str__(self): return self.name class Book(models.Model): code",
"show_image(self): if self.image: return format_html('<img src=\"' + self.image.url + '\" height=\"50px\">') return ''",
"return self.bookcomment_set.count() class BookComment(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) comment = models.CharField(max_length=100) rating =",
"# เช็คว่ามีรูปไหม ถ้ามีก้อโชว ถ้าไม่มีก้อเอาค่าว่างๆออกไป show_image.allow_tags = True # allow tage เพื่อให้มันแปลความหมายของ tag ข้างบน",
"models.SlugField(max_length=200, unique=True) name = models.CharField(max_length=100) description = models.TextField(null=True, blank=True) price = models.FloatField(default=0) category",
"รูปจะถุกเก็บเข้า folder \"upload\" อัตโนมัติ published = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True)",
"class Meta: ordering = ['-code'] # ถ้ามีติดลบนำหน้า คือเรียงจากมากไปน้อย verbose_name_plural = \"Book\" def __str__(self):",
"get_comment_count(self): return self.bookcomment_set.count() class BookComment(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) comment = models.CharField(max_length=100) rating",
"def __str__(self): return self.name def show_image(self): if self.image: return format_html('<img src=\"' + self.image.url",
"= models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ['-code'] # ถ้ามีติดลบนำหน้า คือเรียงจากมากไปน้อย",
"เพื่อให้มันแปลความหมายของ tag ข้างบน def get_comment_count(self): return self.bookcomment_set.count() class BookComment(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE)",
"= ['id'] # เรียงตาม id จากน้อยไปมาก (id ไม่มีใน Model แต่ Django สร้างให้เราแล้วนะ) verbose_name_plural",
"models.DateTimeField(auto_now=True) class Meta: ordering = ['-code'] # ถ้ามีติดลบนำหน้า คือเรียงจากมากไปน้อย verbose_name_plural = \"Book\" def",
"models.CharField(max_length=100) description = models.TextField(null=True, blank=True) price = models.FloatField(default=0) category = models.ForeignKey(Category, null=True, blank=True,",
"Meta: ordering = ['-code'] # ถ้ามีติดลบนำหน้า คือเรียงจากมากไปน้อย verbose_name_plural = \"Book\" def __str__(self): return",
"= models.CharField(max_length=10, unique=True) slug = models.SlugField(max_length=200, unique=True) name = models.CharField(max_length=100) description = models.TextField(null=True,",
"book = models.ForeignKey(Book, on_delete=models.CASCADE) comment = models.CharField(max_length=100) rating = models.IntegerField(default=0) class Meta: ordering",
"# รูปจะถุกเก็บเข้า folder \"upload\" อัตโนมัติ published = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) updated =",
"on_delete=models.CASCADE) comment = models.CharField(max_length=100) rating = models.IntegerField(default=0) class Meta: ordering = ['id'] #",
"def __str__(self): return self.name class Author(models.Model): name = models.CharField(max_length=100) class Meta: verbose_name_plural =",
"models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ['-code'] #",
"choices=BOOK_LEVEL_CHOICE) # เอา choices จากข้างบนมาใช้ image = models.FileField(upload_to='upload', null=True, blank=True) # รูปจะถุกเก็บเข้า folder",
"ไม่มีใน Model แต่ Django สร้างให้เราแล้วนะ) verbose_name_plural = \"Book Comment\" def __str__(self): return self.comment",
"# โชว์ชุดหลัง แต่เซฟด้วยชุดหน้า เช่น โชว์ Basic แต่เซฟด้วย B นะ ('B', 'Basic'), ('M', 'Medium'),",
"\"Book\" def __str__(self): return self.name def show_image(self): if self.image: return format_html('<img src=\"' +",
"ถ้ามีติดลบนำหน้า คือเรียงจากมากไปน้อย verbose_name_plural = \"Book\" def __str__(self): return self.name def show_image(self): if self.image:",
"Meta: verbose_name_plural = \"Author\" def __str__(self): return self.name class Book(models.Model): code = models.CharField(max_length=10,",
"description = models.TextField(null=True, blank=True) price = models.FloatField(default=0) category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE)",
"null=True, blank=True, choices=BOOK_LEVEL_CHOICE) # เอา choices จากข้างบนมาใช้ image = models.FileField(upload_to='upload', null=True, blank=True) #",
"models.ManyToManyField(Author, blank=True) level = models.CharField(max_length=5, null=True, blank=True, choices=BOOK_LEVEL_CHOICE) # เอา choices จากข้างบนมาใช้ image",
"class Category(models.Model): name = models.CharField(max_length=100) class Meta: verbose_name_plural = \"Category\" def __str__(self): return",
"__str__(self): return self.name class Author(models.Model): name = models.CharField(max_length=100) class Meta: verbose_name_plural = \"Author\""
] |
[
"comments to # have as much context between the comments as possible. Everything",
"0.002% of the cases threshold = len(output) * 0.00002 chars_to_remove = [] for",
"text.strip() @profile def create_output(self): \"\"\"Generates one big cp1252 string\"\"\" output = ''.join(self.batches) #Remove",
"yield row def generate_dataset(args, config): cnx = mysql.connector.connect(user=config[\"database\"][\"user\"], password=config[\"database\"][\"password\"], host=config[\"database\"][\"host\"], database=config[\"database\"][\"db\"]) cursor =",
"[] self.vocab_counter = collections.Counter() def write(self, outfile): \"\"\"Writes the dataset to a text",
"[] for char, count in reversed(self.vocab_counter.most_common()): if count < threshold: chars_to_remove.append(char) else: break",
"== 'txt': with open(outfile, \"wb\") as f: f.write(output) # TODO add bzip else:",
"progressbar.ProgressBar(max_value=count) # This query groups comments by posts and places subcomments after their",
"{}\\n'.format(line) self.batches.append(txt) self.vocab_counter.update(txt) def remove_usernames(self, text, authors): \"\"\"Removing user names that the crawler",
"@profile def create_output(self): \"\"\"Generates one big cp1252 string\"\"\" output = ''.join(self.batches) #Remove all",
"user ON user.id = p.user JOIN post ON post.id = p.post WHERE p.parent_comment",
"= ''.join(self.batches) #Remove all characters that appear in less than 0.002% of the",
"data is written to') args = parser.parse_args() with open('config.yml', 'r') as c: config",
"'r') as c: config = yaml.load(c) generate_dataset(args, config) def iter_row(cursor, size=1000): while True:",
"comment_created_time, c.created_time as subcomment_created_time FROM comment c JOIN user ON user.id = c.user",
"output = self.create_output() ending = outfile.split('.')[-1] if ending == 'txt': with open(outfile, \"wb\")",
"people in subcomments, we collect the names of # all subcomment authors to",
"clean the comments\"\"\" lines = [] for comment in comments: lines.extend(comment.replace('\\r', '\\n').split('\\n')) txt",
"if ending == 'txt': with open(outfile, \"wb\") as f: f.write(output) # TODO add",
"ds = Dataset() # As people tend to reference other people in subcomments,",
"is parent ds.push(comments, authors) authors = {author} comments = [message] else: # is",
"UNION # Child comments SELECT c.message, user.name, post.created_time as post_created_time, p.created_time as comment_created_time,",
"post.created_time as post_created_time, p.created_time as comment_created_time, c.created_time as subcomment_created_time FROM comment c JOIN",
"# is child authors.add(author) comments.append(message) ds.write(args.out) class Dataset: def __init__(self): self.batches = []",
"bar(iter_row(cursor)): if subcomment_date is None: # is parent ds.push(comments, authors) authors = {author}",
"len(line) < 500: txt += '> {}\\n'.format(line) return txt if __name__ == '__main__':",
"subcomments after their parent comments to # have as much context between the",
"for char, count in reversed(self.vocab_counter.most_common()): if count < threshold: chars_to_remove.append(char) else: break output",
"= mysql.connector.connect(user=config[\"database\"][\"user\"], password=config[\"database\"][\"password\"], host=config[\"database\"][\"host\"], database=config[\"database\"][\"db\"]) cursor = cnx.cursor() cursor.execute('SELECT count(*) FROM comment') count",
"a string\"\"\" txt = '' for line in lines: line = self.clean_tags(line) if",
"generate_dataset(args, config) def iter_row(cursor, size=1000): while True: rows = cursor.fetchmany(size) if not rows:",
"comment p on p.id = c.parent_comment JOIN post ON post.id = p.post ORDER",
"comments: lines.extend(comment.replace('\\r', '\\n').split('\\n')) txt = '' authors = [re.escape(author) for author in authors]",
"''') print('Done') ds = Dataset() # As people tend to reference other people",
"all subcomment authors to remove them from the result in the end. authors",
"FROM comment p JOIN user ON user.id = p.user JOIN post ON post.id",
"'' if text[0] == '@': text = re.sub('@ ?.*?((:|,|\\.| {2})| .*?[:,. ])', '',",
"from the result in the end. authors = set() comments = [] for",
"and it's subcomments because they mainly reference each other text = re.sub('({})'.format('|'.join(authors)), '',",
"because they mainly reference each other text = re.sub('({})'.format('|'.join(authors)), '', text) return text.strip()",
"chars_to_remove.append(char) else: break output = re.sub('[' + re.escape(''.join(chars_to_remove)) + ']', '', output) return",
"set of authors ist used to further clean the comments\"\"\" lines = []",
"ON post.id = p.post ORDER BY post_created_time ASC, comment_created_time ASC, subcomment_created_time ASC LIMIT",
"* 0.00002 chars_to_remove = [] for char, count in reversed(self.vocab_counter.most_common()): if count <",
"'\\n').split('\\n')) txt = '' authors = [re.escape(author) for author in authors] for line",
"break output = re.sub('[' + re.escape(''.join(chars_to_remove)) + ']', '', output) return output.encode(\"cp1252\", errors=\"ignore\")",
"bar = progressbar.ProgressBar(max_value=count) # This query groups comments by posts and places subcomments",
"else: break output = re.sub('[' + re.escape(''.join(chars_to_remove)) + ']', '', output) return output.encode(\"cp1252\",",
"mysql.connector.connect(user=config[\"database\"][\"user\"], password=config[\"database\"][\"password\"], host=config[\"database\"][\"host\"], database=config[\"database\"][\"db\"]) cursor = cnx.cursor() cursor.execute('SELECT count(*) FROM comment') count =",
"# This query groups comments by posts and places subcomments after their parent",
"able to filter out because they were not returned in Graph API's message_tags\"\"\"",
"to be a .txt file') @profile def push(self, comments, authors): \"\"\"Adds a new",
"them from the result in the end. authors = set() comments = []",
"= progressbar.ProgressBar(max_value=count) # This query groups comments by posts and places subcomments after",
"'', text) return text.strip() @profile def create_output(self): \"\"\"Generates one big cp1252 string\"\"\" output",
"we collect the names of # all subcomment authors to remove them from",
"iter_row(cursor, size=1000): while True: rows = cursor.fetchmany(size) if not rows: break for row",
"and len(text.split(' ')) <= 3): return '' if text[0] == '@': text =",
"further clean the comments\"\"\" lines = [] for comment in comments: lines.extend(comment.replace('\\r', '\\n').split('\\n'))",
"return output.encode(\"cp1252\", errors=\"ignore\") def merge_lines(self, lines): \"\"\"Cleans and selects qualifying lines and merges",
"Everything is sorted ASC by date. print('Executing SQL query...') cursor.execute(''' # Parent comments",
"authors): \"\"\"Adds a new bathch of comments to the dataset. The set of",
"print('Executing SQL query...') cursor.execute(''' # Parent comments SELECT p.message, user.name, post.created_time as post_created_time,",
"The set of authors ist used to further clean the comments\"\"\" lines =",
"the names of all the authors from the comment and it's subcomments because",
"bathch of comments to the dataset. The set of authors ist used to",
"post.id = p.post WHERE p.parent_comment IS NULL UNION # Child comments SELECT c.message,",
"= c.user JOIN comment p on p.id = c.parent_comment JOIN post ON post.id",
"\"\"\"Generates one big cp1252 string\"\"\" output = ''.join(self.batches) #Remove all characters that appear",
"less than 0.002% of the cases threshold = len(output) * 0.00002 chars_to_remove =",
".txt file') @profile def push(self, comments, authors): \"\"\"Adds a new bathch of comments",
"argparse import yaml import re import collections def main(): parser = argparse.ArgumentParser() parser.add_argument('--out',",
"post ON post.id = p.post ORDER BY post_created_time ASC, comment_created_time ASC, subcomment_created_time ASC",
"len(output) * 0.00002 chars_to_remove = [] for char, count in reversed(self.vocab_counter.most_common()): if count",
"config): cnx = mysql.connector.connect(user=config[\"database\"][\"user\"], password=config[\"database\"][\"password\"], host=config[\"database\"][\"host\"], database=config[\"database\"][\"db\"]) cursor = cnx.cursor() cursor.execute('SELECT count(*) FROM",
"Parent comments SELECT p.message, user.name, post.created_time as post_created_time, p.created_time as comment_created_time, Null as",
"= [] for (message, author, post_date, comment_date, subcomment_date) in bar(iter_row(cursor)): if subcomment_date is",
"if count < threshold: chars_to_remove.append(char) else: break output = re.sub('[' + re.escape(''.join(chars_to_remove)) +",
"< threshold: chars_to_remove.append(char) else: break output = re.sub('[' + re.escape(''.join(chars_to_remove)) + ']', '',",
"c: config = yaml.load(c) generate_dataset(args, config) def iter_row(cursor, size=1000): while True: rows =",
"and places subcomments after their parent comments to # have as much context",
"= [message] else: # is child authors.add(author) comments.append(message) ds.write(args.out) class Dataset: def __init__(self):",
"text file\"\"\" output = self.create_output() ending = outfile.split('.')[-1] if ending == 'txt': with",
"'> {}\\n'.format(line) self.batches.append(txt) self.vocab_counter.update(txt) def remove_usernames(self, text, authors): \"\"\"Removing user names that the",
"comment c JOIN user ON user.id = c.user JOIN comment p on p.id",
"p on p.id = c.parent_comment JOIN post ON post.id = p.post ORDER BY",
"# As people tend to reference other people in subcomments, we collect the",
"in authors] for line in lines: line = self.remove_usernames(line, authors) if 4 <",
"a .txt file') @profile def push(self, comments, authors): \"\"\"Adds a new bathch of",
"rows: yield row def generate_dataset(args, config): cnx = mysql.connector.connect(user=config[\"database\"][\"user\"], password=config[\"database\"][\"password\"], host=config[\"database\"][\"host\"], database=config[\"database\"][\"db\"]) cursor",
"in subcomments, we collect the names of # all subcomment authors to remove",
"subcomment_created_time ASC LIMIT 300000 ''') print('Done') ds = Dataset() # As people tend",
"lines: line = self.clean_tags(line) if 4 < len(line) < 500: txt += '>",
"selects qualifying lines and merges them to a string\"\"\" txt = '' for",
"= '' authors = [re.escape(author) for author in authors] for line in lines:",
"re.escape(''.join(chars_to_remove)) + ']', '', output) return output.encode(\"cp1252\", errors=\"ignore\") def merge_lines(self, lines): \"\"\"Cleans and",
"that appear in less than 0.002% of the cases threshold = len(output) *",
"import argparse import yaml import re import collections def main(): parser = argparse.ArgumentParser()",
"comment') count = cursor.fetchone()[0] bar = progressbar.ProgressBar(max_value=count) # This query groups comments by",
"dataset. The set of authors ist used to further clean the comments\"\"\" lines",
"3): return '' if text[0] == '@': text = re.sub('@ ?.*?((:|,|\\.| {2})| .*?[:,.",
"= [] for char, count in reversed(self.vocab_counter.most_common()): if count < threshold: chars_to_remove.append(char) else:",
"user.id = p.user JOIN post ON post.id = p.post WHERE p.parent_comment IS NULL",
"subcomment_date) in bar(iter_row(cursor)): if subcomment_date is None: # is parent ds.push(comments, authors) authors",
"for line in lines: line = self.remove_usernames(line, authors) if 4 < len(line) <",
"= collections.Counter() def write(self, outfile): \"\"\"Writes the dataset to a text file\"\"\" output",
"string\"\"\" txt = '' for line in lines: line = self.clean_tags(line) if 4",
"to remove them from the result in the end. authors = set() comments",
"'', text) # Then the names of all the authors from the comment",
"with open('config.yml', 'r') as c: config = yaml.load(c) generate_dataset(args, config) def iter_row(cursor, size=1000):",
"parser.parse_args() with open('config.yml', 'r') as c: config = yaml.load(c) generate_dataset(args, config) def iter_row(cursor,",
"4 < len(line) < 500: txt += '> {}\\n'.format(line) self.batches.append(txt) self.vocab_counter.update(txt) def remove_usernames(self,",
"= self.remove_usernames(line, authors) if 4 < len(line) < 500: txt += '> {}\\n'.format(line)",
"by date. print('Executing SQL query...') cursor.execute(''' # Parent comments SELECT p.message, user.name, post.created_time",
"# all subcomment authors to remove them from the result in the end.",
"as f: f.write(output) # TODO add bzip else: raise ValueError('outfile has to be",
"their parent comments to # have as much context between the comments as",
"all the authors from the comment and it's subcomments because they mainly reference",
"default='data/racist/racist.txt', help='text file where the data is written to') args = parser.parse_args() with",
"ON post.id = p.post WHERE p.parent_comment IS NULL UNION # Child comments SELECT",
"to # have as much context between the comments as possible. Everything is",
"= re.sub('@ ?.*?((:|,|\\.| {2})| .*?[:,. ])', '', text) else: text = re.sub('@', '',",
"'' for line in lines: line = self.clean_tags(line) if 4 < len(line) <",
"for row in rows: yield row def generate_dataset(args, config): cnx = mysql.connector.connect(user=config[\"database\"][\"user\"], password=config[\"database\"][\"password\"],",
"reversed(self.vocab_counter.most_common()): if count < threshold: chars_to_remove.append(char) else: break output = re.sub('[' + re.escape(''.join(chars_to_remove))",
"dataset to a text file\"\"\" output = self.create_output() ending = outfile.split('.')[-1] if ending",
"\"\"\"Writes the dataset to a text file\"\"\" output = self.create_output() ending = outfile.split('.')[-1]",
"in lines: line = self.remove_usernames(line, authors) if 4 < len(line) < 500: txt",
"As people tend to reference other people in subcomments, we collect the names",
"collections def main(): parser = argparse.ArgumentParser() parser.add_argument('--out', type=str, default='data/racist/racist.txt', help='text file where the",
"yaml import re import collections def main(): parser = argparse.ArgumentParser() parser.add_argument('--out', type=str, default='data/racist/racist.txt',",
"= p.post ORDER BY post_created_time ASC, comment_created_time ASC, subcomment_created_time ASC LIMIT 300000 ''')",
"parent ds.push(comments, authors) authors = {author} comments = [message] else: # is child",
"the result in the end. authors = set() comments = [] for (message,",
"comments = [message] else: # is child authors.add(author) comments.append(message) ds.write(args.out) class Dataset: def",
"password=config[\"database\"][\"password\"], host=config[\"database\"][\"host\"], database=config[\"database\"][\"db\"]) cursor = cnx.cursor() cursor.execute('SELECT count(*) FROM comment') count = cursor.fetchone()[0]",
"< len(line) < 500: txt += '> {}\\n'.format(line) self.batches.append(txt) self.vocab_counter.update(txt) def remove_usernames(self, text,",
"than 0.002% of the cases threshold = len(output) * 0.00002 chars_to_remove = []",
"tend to reference other people in subcomments, we collect the names of #",
"user ON user.id = c.user JOIN comment p on p.id = c.parent_comment JOIN",
"on p.id = c.parent_comment JOIN post ON post.id = p.post ORDER BY post_created_time",
"user.name, post.created_time as post_created_time, p.created_time as comment_created_time, Null as subcomment_created_time FROM comment p",
"post.id = p.post ORDER BY post_created_time ASC, comment_created_time ASC, subcomment_created_time ASC LIMIT 300000",
"crawler was not able to filter out because they were not returned in",
"import mysql.connector import progressbar import argparse import yaml import re import collections def",
"collections.Counter() def write(self, outfile): \"\"\"Writes the dataset to a text file\"\"\" output =",
"= '' for line in lines: line = self.clean_tags(line) if 4 < len(line)",
"def write(self, outfile): \"\"\"Writes the dataset to a text file\"\"\" output = self.create_output()",
"ist used to further clean the comments\"\"\" lines = [] for comment in",
"comments = [] for (message, author, post_date, comment_date, subcomment_date) in bar(iter_row(cursor)): if subcomment_date",
"re import collections def main(): parser = argparse.ArgumentParser() parser.add_argument('--out', type=str, default='data/racist/racist.txt', help='text file",
"file where the data is written to') args = parser.parse_args() with open('config.yml', 'r')",
"# is parent ds.push(comments, authors) authors = {author} comments = [message] else: #",
"appear in less than 0.002% of the cases threshold = len(output) * 0.00002",
"authors) if 4 < len(line) < 500: txt += '> {}\\n'.format(line) self.batches.append(txt) self.vocab_counter.update(txt)",
"in the end. authors = set() comments = [] for (message, author, post_date,",
"text and len(text.split(' ')) <= 3): return '' if text[0] == '@': text",
"JOIN post ON post.id = p.post ORDER BY post_created_time ASC, comment_created_time ASC, subcomment_created_time",
"errors=\"ignore\") def merge_lines(self, lines): \"\"\"Cleans and selects qualifying lines and merges them to",
"re.sub('[' + re.escape(''.join(chars_to_remove)) + ']', '', output) return output.encode(\"cp1252\", errors=\"ignore\") def merge_lines(self, lines):",
"not rows: break for row in rows: yield row def generate_dataset(args, config): cnx",
"were not returned in Graph API's message_tags\"\"\" # First remove the old fashined",
"qualifying lines and merges them to a string\"\"\" txt = '' for line",
"p.created_time as comment_created_time, Null as subcomment_created_time FROM comment p JOIN user ON user.id",
"p.message, user.name, post.created_time as post_created_time, p.created_time as comment_created_time, Null as subcomment_created_time FROM comment",
"== 0 or ('@' in text and len(text.split(' ')) <= 3): return ''",
"ending = outfile.split('.')[-1] if ending == 'txt': with open(outfile, \"wb\") as f: f.write(output)",
"'', text) else: text = re.sub('@', '', text) # Then the names of",
"= cursor.fetchmany(size) if not rows: break for row in rows: yield row def",
"len(text) == 0 or ('@' in text and len(text.split(' ')) <= 3): return",
"<= 3): return '' if text[0] == '@': text = re.sub('@ ?.*?((:|,|\\.| {2})|",
"# have as much context between the comments as possible. Everything is sorted",
"comment_created_time, Null as subcomment_created_time FROM comment p JOIN user ON user.id = p.user",
"= [] for comment in comments: lines.extend(comment.replace('\\r', '\\n').split('\\n')) txt = '' authors =",
"else: # is child authors.add(author) comments.append(message) ds.write(args.out) class Dataset: def __init__(self): self.batches =",
"has to be a .txt file') @profile def push(self, comments, authors): \"\"\"Adds a",
"user names that the crawler was not able to filter out because they",
"in reversed(self.vocab_counter.most_common()): if count < threshold: chars_to_remove.append(char) else: break output = re.sub('[' +",
"subcomment_date is None: # is parent ds.push(comments, authors) authors = {author} comments =",
"Child comments SELECT c.message, user.name, post.created_time as post_created_time, p.created_time as comment_created_time, c.created_time as",
"to filter out because they were not returned in Graph API's message_tags\"\"\" #",
"ASC LIMIT 300000 ''') print('Done') ds = Dataset() # As people tend to",
"user.name, post.created_time as post_created_time, p.created_time as comment_created_time, c.created_time as subcomment_created_time FROM comment c",
"text = re.sub('({})'.format('|'.join(authors)), '', text) return text.strip() @profile def create_output(self): \"\"\"Generates one big",
"size=1000): while True: rows = cursor.fetchmany(size) if not rows: break for row in",
"rows = cursor.fetchmany(size) if not rows: break for row in rows: yield row",
"generate_dataset(args, config): cnx = mysql.connector.connect(user=config[\"database\"][\"user\"], password=config[\"database\"][\"password\"], host=config[\"database\"][\"host\"], database=config[\"database\"][\"db\"]) cursor = cnx.cursor() cursor.execute('SELECT count(*)",
"to a text file\"\"\" output = self.create_output() ending = outfile.split('.')[-1] if ending ==",
"= cursor.fetchone()[0] bar = progressbar.ProgressBar(max_value=count) # This query groups comments by posts and",
"\"\"\"Removing user names that the crawler was not able to filter out because",
"else: raise ValueError('outfile has to be a .txt file') @profile def push(self, comments,",
"as comment_created_time, Null as subcomment_created_time FROM comment p JOIN user ON user.id =",
"push(self, comments, authors): \"\"\"Adds a new bathch of comments to the dataset. The",
"in comments: lines.extend(comment.replace('\\r', '\\n').split('\\n')) txt = '' authors = [re.escape(author) for author in",
"def main(): parser = argparse.ArgumentParser() parser.add_argument('--out', type=str, default='data/racist/racist.txt', help='text file where the data",
"char, count in reversed(self.vocab_counter.most_common()): if count < threshold: chars_to_remove.append(char) else: break output =",
"?.*?((:|,|\\.| {2})| .*?[:,. ])', '', text) else: text = re.sub('@', '', text) #",
"import re import collections def main(): parser = argparse.ArgumentParser() parser.add_argument('--out', type=str, default='data/racist/racist.txt', help='text",
"= self.clean_tags(line) if 4 < len(line) < 500: txt += '> {}\\n'.format(line) return",
"them to a string\"\"\" txt = '' for line in lines: line =",
"cursor.fetchmany(size) if not rows: break for row in rows: yield row def generate_dataset(args,",
"places subcomments after their parent comments to # have as much context between",
"JOIN user ON user.id = p.user JOIN post ON post.id = p.post WHERE",
"TODO add bzip else: raise ValueError('outfile has to be a .txt file') @profile",
"f.write(output) # TODO add bzip else: raise ValueError('outfile has to be a .txt",
"txt = '' authors = [re.escape(author) for author in authors] for line in",
"filter out because they were not returned in Graph API's message_tags\"\"\" # First",
"post ON post.id = p.post WHERE p.parent_comment IS NULL UNION # Child comments",
"text) # Then the names of all the authors from the comment and",
"query...') cursor.execute(''' # Parent comments SELECT p.message, user.name, post.created_time as post_created_time, p.created_time as",
"if subcomment_date is None: # is parent ds.push(comments, authors) authors = {author} comments",
"self.batches = [] self.vocab_counter = collections.Counter() def write(self, outfile): \"\"\"Writes the dataset to",
"[message] else: # is child authors.add(author) comments.append(message) ds.write(args.out) class Dataset: def __init__(self): self.batches",
"where the data is written to') args = parser.parse_args() with open('config.yml', 'r') as",
"output.encode(\"cp1252\", errors=\"ignore\") def merge_lines(self, lines): \"\"\"Cleans and selects qualifying lines and merges them",
"NULL UNION # Child comments SELECT c.message, user.name, post.created_time as post_created_time, p.created_time as",
"user.id = c.user JOIN comment p on p.id = c.parent_comment JOIN post ON",
"= re.sub('({})'.format('|'.join(authors)), '', text) return text.strip() @profile def create_output(self): \"\"\"Generates one big cp1252",
"API's message_tags\"\"\" # First remove the old fashined @ tags if len(text) ==",
"comment_created_time ASC, subcomment_created_time ASC LIMIT 300000 ''') print('Done') ds = Dataset() # As",
"end. authors = set() comments = [] for (message, author, post_date, comment_date, subcomment_date)",
"comments to the dataset. The set of authors ist used to further clean",
"c.parent_comment JOIN post ON post.id = p.post ORDER BY post_created_time ASC, comment_created_time ASC,",
"for (message, author, post_date, comment_date, subcomment_date) in bar(iter_row(cursor)): if subcomment_date is None: #",
"open(outfile, \"wb\") as f: f.write(output) # TODO add bzip else: raise ValueError('outfile has",
"chars_to_remove = [] for char, count in reversed(self.vocab_counter.most_common()): if count < threshold: chars_to_remove.append(char)",
"ds.write(args.out) class Dataset: def __init__(self): self.batches = [] self.vocab_counter = collections.Counter() def write(self,",
"as much context between the comments as possible. Everything is sorted ASC by",
"import collections def main(): parser = argparse.ArgumentParser() parser.add_argument('--out', type=str, default='data/racist/racist.txt', help='text file where",
"open('config.yml', 'r') as c: config = yaml.load(c) generate_dataset(args, config) def iter_row(cursor, size=1000): while",
"p.created_time as comment_created_time, c.created_time as subcomment_created_time FROM comment c JOIN user ON user.id",
"text, authors): \"\"\"Removing user names that the crawler was not able to filter",
"subcomment authors to remove them from the result in the end. authors =",
"< len(line) < 500: txt += '> {}\\n'.format(line) return txt if __name__ ==",
"config) def iter_row(cursor, size=1000): while True: rows = cursor.fetchmany(size) if not rows: break",
"return '' if text[0] == '@': text = re.sub('@ ?.*?((:|,|\\.| {2})| .*?[:,. ])',",
"SELECT p.message, user.name, post.created_time as post_created_time, p.created_time as comment_created_time, Null as subcomment_created_time FROM",
"comments SELECT p.message, user.name, post.created_time as post_created_time, p.created_time as comment_created_time, Null as subcomment_created_time",
"0 or ('@' in text and len(text.split(' ')) <= 3): return '' if",
"'', output) return output.encode(\"cp1252\", errors=\"ignore\") def merge_lines(self, lines): \"\"\"Cleans and selects qualifying lines",
"args = parser.parse_args() with open('config.yml', 'r') as c: config = yaml.load(c) generate_dataset(args, config)",
"\"\"\"Cleans and selects qualifying lines and merges them to a string\"\"\" txt =",
"as subcomment_created_time FROM comment c JOIN user ON user.id = c.user JOIN comment",
"a text file\"\"\" output = self.create_output() ending = outfile.split('.')[-1] if ending == 'txt':",
"not able to filter out because they were not returned in Graph API's",
"'' authors = [re.escape(author) for author in authors] for line in lines: line",
"the dataset. The set of authors ist used to further clean the comments\"\"\"",
"line = self.remove_usernames(line, authors) if 4 < len(line) < 500: txt += '>",
"comment p JOIN user ON user.id = p.user JOIN post ON post.id =",
"in text and len(text.split(' ')) <= 3): return '' if text[0] == '@':",
"FROM comment') count = cursor.fetchone()[0] bar = progressbar.ProgressBar(max_value=count) # This query groups comments",
"cnx = mysql.connector.connect(user=config[\"database\"][\"user\"], password=config[\"database\"][\"password\"], host=config[\"database\"][\"host\"], database=config[\"database\"][\"db\"]) cursor = cnx.cursor() cursor.execute('SELECT count(*) FROM comment')",
"one big cp1252 string\"\"\" output = ''.join(self.batches) #Remove all characters that appear in",
"ds.push(comments, authors) authors = {author} comments = [message] else: # is child authors.add(author)",
"progressbar import argparse import yaml import re import collections def main(): parser =",
"tags if len(text) == 0 or ('@' in text and len(text.split(' ')) <=",
"outfile.split('.')[-1] if ending == 'txt': with open(outfile, \"wb\") as f: f.write(output) # TODO",
"be a .txt file') @profile def push(self, comments, authors): \"\"\"Adds a new bathch",
"they mainly reference each other text = re.sub('({})'.format('|'.join(authors)), '', text) return text.strip() @profile",
"of the cases threshold = len(output) * 0.00002 chars_to_remove = [] for char,",
"self.clean_tags(line) if 4 < len(line) < 500: txt += '> {}\\n'.format(line) return txt",
"authors = set() comments = [] for (message, author, post_date, comment_date, subcomment_date) in",
"re.sub('@', '', text) # Then the names of all the authors from the",
"SQL query...') cursor.execute(''' # Parent comments SELECT p.message, user.name, post.created_time as post_created_time, p.created_time",
"@profile def push(self, comments, authors): \"\"\"Adds a new bathch of comments to the",
"the names of # all subcomment authors to remove them from the result",
"if 4 < len(line) < 500: txt += '> {}\\n'.format(line) return txt if",
"string\"\"\" output = ''.join(self.batches) #Remove all characters that appear in less than 0.002%",
"the dataset to a text file\"\"\" output = self.create_output() ending = outfile.split('.')[-1] if",
"= outfile.split('.')[-1] if ending == 'txt': with open(outfile, \"wb\") as f: f.write(output) #",
"== '@': text = re.sub('@ ?.*?((:|,|\\.| {2})| .*?[:,. ])', '', text) else: text",
"the authors from the comment and it's subcomments because they mainly reference each",
"# Child comments SELECT c.message, user.name, post.created_time as post_created_time, p.created_time as comment_created_time, c.created_time",
"the crawler was not able to filter out because they were not returned",
"500: txt += '> {}\\n'.format(line) self.batches.append(txt) self.vocab_counter.update(txt) def remove_usernames(self, text, authors): \"\"\"Removing user",
"threshold = len(output) * 0.00002 chars_to_remove = [] for char, count in reversed(self.vocab_counter.most_common()):",
"{author} comments = [message] else: # is child authors.add(author) comments.append(message) ds.write(args.out) class Dataset:",
"raise ValueError('outfile has to be a .txt file') @profile def push(self, comments, authors):",
"authors = {author} comments = [message] else: # is child authors.add(author) comments.append(message) ds.write(args.out)",
"authors from the comment and it's subcomments because they mainly reference each other",
"date. print('Executing SQL query...') cursor.execute(''' # Parent comments SELECT p.message, user.name, post.created_time as",
"Then the names of all the authors from the comment and it's subcomments",
"ON user.id = p.user JOIN post ON post.id = p.post WHERE p.parent_comment IS",
"subcomments because they mainly reference each other text = re.sub('({})'.format('|'.join(authors)), '', text) return",
"used to further clean the comments\"\"\" lines = [] for comment in comments:",
"= [re.escape(author) for author in authors] for line in lines: line = self.remove_usernames(line,",
"in less than 0.002% of the cases threshold = len(output) * 0.00002 chars_to_remove",
"p.id = c.parent_comment JOIN post ON post.id = p.post ORDER BY post_created_time ASC,",
"']', '', output) return output.encode(\"cp1252\", errors=\"ignore\") def merge_lines(self, lines): \"\"\"Cleans and selects qualifying",
"merges them to a string\"\"\" txt = '' for line in lines: line",
"subcomment_created_time FROM comment c JOIN user ON user.id = c.user JOIN comment p",
"comment_date, subcomment_date) in bar(iter_row(cursor)): if subcomment_date is None: # is parent ds.push(comments, authors)",
"text = re.sub('@', '', text) # Then the names of all the authors",
"Dataset() # As people tend to reference other people in subcomments, we collect",
"big cp1252 string\"\"\" output = ''.join(self.batches) #Remove all characters that appear in less",
"with open(outfile, \"wb\") as f: f.write(output) # TODO add bzip else: raise ValueError('outfile",
"to a string\"\"\" txt = '' for line in lines: line = self.clean_tags(line)",
"possible. Everything is sorted ASC by date. print('Executing SQL query...') cursor.execute(''' # Parent",
"as post_created_time, p.created_time as comment_created_time, c.created_time as subcomment_created_time FROM comment c JOIN user",
"to further clean the comments\"\"\" lines = [] for comment in comments: lines.extend(comment.replace('\\r',",
"row in rows: yield row def generate_dataset(args, config): cnx = mysql.connector.connect(user=config[\"database\"][\"user\"], password=config[\"database\"][\"password\"], host=config[\"database\"][\"host\"],",
"ASC by date. print('Executing SQL query...') cursor.execute(''' # Parent comments SELECT p.message, user.name,",
"as post_created_time, p.created_time as comment_created_time, Null as subcomment_created_time FROM comment p JOIN user",
"authors] for line in lines: line = self.remove_usernames(line, authors) if 4 < len(line)",
"as possible. Everything is sorted ASC by date. print('Executing SQL query...') cursor.execute(''' #",
"yaml.load(c) generate_dataset(args, config) def iter_row(cursor, size=1000): while True: rows = cursor.fetchmany(size) if not",
"the end. authors = set() comments = [] for (message, author, post_date, comment_date,",
"import progressbar import argparse import yaml import re import collections def main(): parser",
"'@': text = re.sub('@ ?.*?((:|,|\\.| {2})| .*?[:,. ])', '', text) else: text =",
"@ tags if len(text) == 0 or ('@' in text and len(text.split(' '))",
"sorted ASC by date. print('Executing SQL query...') cursor.execute(''' # Parent comments SELECT p.message,",
"names of all the authors from the comment and it's subcomments because they",
"all characters that appear in less than 0.002% of the cases threshold =",
"output = ''.join(self.batches) #Remove all characters that appear in less than 0.002% of",
"JOIN comment p on p.id = c.parent_comment JOIN post ON post.id = p.post",
"threshold: chars_to_remove.append(char) else: break output = re.sub('[' + re.escape(''.join(chars_to_remove)) + ']', '', output)",
"if 4 < len(line) < 500: txt += '> {}\\n'.format(line) self.batches.append(txt) self.vocab_counter.update(txt) def",
"child authors.add(author) comments.append(message) ds.write(args.out) class Dataset: def __init__(self): self.batches = [] self.vocab_counter =",
"write(self, outfile): \"\"\"Writes the dataset to a text file\"\"\" output = self.create_output() ending",
"post.created_time as post_created_time, p.created_time as comment_created_time, Null as subcomment_created_time FROM comment p JOIN",
"cases threshold = len(output) * 0.00002 chars_to_remove = [] for char, count in",
"is written to') args = parser.parse_args() with open('config.yml', 'r') as c: config =",
"# Then the names of all the authors from the comment and it's",
"query groups comments by posts and places subcomments after their parent comments to",
"main(): parser = argparse.ArgumentParser() parser.add_argument('--out', type=str, default='data/racist/racist.txt', help='text file where the data is",
"remove the old fashined @ tags if len(text) == 0 or ('@' in",
"= re.sub('[' + re.escape(''.join(chars_to_remove)) + ']', '', output) return output.encode(\"cp1252\", errors=\"ignore\") def merge_lines(self,",
"300000 ''') print('Done') ds = Dataset() # As people tend to reference other",
"the comments\"\"\" lines = [] for comment in comments: lines.extend(comment.replace('\\r', '\\n').split('\\n')) txt =",
"re.sub('@ ?.*?((:|,|\\.| {2})| .*?[:,. ])', '', text) else: text = re.sub('@', '', text)",
"def push(self, comments, authors): \"\"\"Adds a new bathch of comments to the dataset.",
"comment and it's subcomments because they mainly reference each other text = re.sub('({})'.format('|'.join(authors)),",
"to reference other people in subcomments, we collect the names of # all",
"message_tags\"\"\" # First remove the old fashined @ tags if len(text) == 0",
"text = re.sub('@ ?.*?((:|,|\\.| {2})| .*?[:,. ])', '', text) else: text = re.sub('@',",
"output = re.sub('[' + re.escape(''.join(chars_to_remove)) + ']', '', output) return output.encode(\"cp1252\", errors=\"ignore\") def",
"= parser.parse_args() with open('config.yml', 'r') as c: config = yaml.load(c) generate_dataset(args, config) def",
"the cases threshold = len(output) * 0.00002 chars_to_remove = [] for char, count",
"and selects qualifying lines and merges them to a string\"\"\" txt = ''",
"+= '> {}\\n'.format(line) self.batches.append(txt) self.vocab_counter.update(txt) def remove_usernames(self, text, authors): \"\"\"Removing user names that",
"This query groups comments by posts and places subcomments after their parent comments",
"Null as subcomment_created_time FROM comment p JOIN user ON user.id = p.user JOIN",
"reference other people in subcomments, we collect the names of # all subcomment",
"None: # is parent ds.push(comments, authors) authors = {author} comments = [message] else:",
"count in reversed(self.vocab_counter.most_common()): if count < threshold: chars_to_remove.append(char) else: break output = re.sub('['",
"if text[0] == '@': text = re.sub('@ ?.*?((:|,|\\.| {2})| .*?[:,. ])', '', text)",
"lines and merges them to a string\"\"\" txt = '' for line in",
"# TODO add bzip else: raise ValueError('outfile has to be a .txt file')",
"cnx.cursor() cursor.execute('SELECT count(*) FROM comment') count = cursor.fetchone()[0] bar = progressbar.ProgressBar(max_value=count) # This",
"= Dataset() # As people tend to reference other people in subcomments, we",
"groups comments by posts and places subcomments after their parent comments to #",
"after their parent comments to # have as much context between the comments",
"def iter_row(cursor, size=1000): while True: rows = cursor.fetchmany(size) if not rows: break for",
"[] for comment in comments: lines.extend(comment.replace('\\r', '\\n').split('\\n')) txt = '' authors = [re.escape(author)",
"fashined @ tags if len(text) == 0 or ('@' in text and len(text.split('",
"Graph API's message_tags\"\"\" # First remove the old fashined @ tags if len(text)",
"+ ']', '', output) return output.encode(\"cp1252\", errors=\"ignore\") def merge_lines(self, lines): \"\"\"Cleans and selects",
"the data is written to') args = parser.parse_args() with open('config.yml', 'r') as c:",
"post_created_time, p.created_time as comment_created_time, c.created_time as subcomment_created_time FROM comment c JOIN user ON",
"])', '', text) else: text = re.sub('@', '', text) # Then the names",
"= p.user JOIN post ON post.id = p.post WHERE p.parent_comment IS NULL UNION",
"SELECT c.message, user.name, post.created_time as post_created_time, p.created_time as comment_created_time, c.created_time as subcomment_created_time FROM",
"c JOIN user ON user.id = c.user JOIN comment p on p.id =",
"(message, author, post_date, comment_date, subcomment_date) in bar(iter_row(cursor)): if subcomment_date is None: # is",
"[] for (message, author, post_date, comment_date, subcomment_date) in bar(iter_row(cursor)): if subcomment_date is None:",
"to') args = parser.parse_args() with open('config.yml', 'r') as c: config = yaml.load(c) generate_dataset(args,",
"other text = re.sub('({})'.format('|'.join(authors)), '', text) return text.strip() @profile def create_output(self): \"\"\"Generates one",
"config = yaml.load(c) generate_dataset(args, config) def iter_row(cursor, size=1000): while True: rows = cursor.fetchmany(size)",
"collect the names of # all subcomment authors to remove them from the",
"')) <= 3): return '' if text[0] == '@': text = re.sub('@ ?.*?((:|,|\\.|",
"ORDER BY post_created_time ASC, comment_created_time ASC, subcomment_created_time ASC LIMIT 300000 ''') print('Done') ds",
"# First remove the old fashined @ tags if len(text) == 0 or",
"because they were not returned in Graph API's message_tags\"\"\" # First remove the",
"file') @profile def push(self, comments, authors): \"\"\"Adds a new bathch of comments to",
"if not rows: break for row in rows: yield row def generate_dataset(args, config):",
"create_output(self): \"\"\"Generates one big cp1252 string\"\"\" output = ''.join(self.batches) #Remove all characters that",
"help='text file where the data is written to') args = parser.parse_args() with open('config.yml',",
"as c: config = yaml.load(c) generate_dataset(args, config) def iter_row(cursor, size=1000): while True: rows",
"line in lines: line = self.clean_tags(line) if 4 < len(line) < 500: txt",
"type=str, default='data/racist/racist.txt', help='text file where the data is written to') args = parser.parse_args()",
"mysql.connector import progressbar import argparse import yaml import re import collections def main():",
"authors): \"\"\"Removing user names that the crawler was not able to filter out",
"returned in Graph API's message_tags\"\"\" # First remove the old fashined @ tags",
"posts and places subcomments after their parent comments to # have as much",
"ValueError('outfile has to be a .txt file') @profile def push(self, comments, authors): \"\"\"Adds",
"\"\"\"Adds a new bathch of comments to the dataset. The set of authors",
"self.batches.append(txt) self.vocab_counter.update(txt) def remove_usernames(self, text, authors): \"\"\"Removing user names that the crawler was",
"+ re.escape(''.join(chars_to_remove)) + ']', '', output) return output.encode(\"cp1252\", errors=\"ignore\") def merge_lines(self, lines): \"\"\"Cleans",
"LIMIT 300000 ''') print('Done') ds = Dataset() # As people tend to reference",
"mainly reference each other text = re.sub('({})'.format('|'.join(authors)), '', text) return text.strip() @profile def",
"characters that appear in less than 0.002% of the cases threshold = len(output)",
"comments SELECT c.message, user.name, post.created_time as post_created_time, p.created_time as comment_created_time, c.created_time as subcomment_created_time",
"out because they were not returned in Graph API's message_tags\"\"\" # First remove",
"authors = [re.escape(author) for author in authors] for line in lines: line =",
"ending == 'txt': with open(outfile, \"wb\") as f: f.write(output) # TODO add bzip",
"c.user JOIN comment p on p.id = c.parent_comment JOIN post ON post.id =",
"is sorted ASC by date. print('Executing SQL query...') cursor.execute(''' # Parent comments SELECT",
"= p.post WHERE p.parent_comment IS NULL UNION # Child comments SELECT c.message, user.name,",
"def create_output(self): \"\"\"Generates one big cp1252 string\"\"\" output = ''.join(self.batches) #Remove all characters",
"in bar(iter_row(cursor)): if subcomment_date is None: # is parent ds.push(comments, authors) authors =",
"= len(output) * 0.00002 chars_to_remove = [] for char, count in reversed(self.vocab_counter.most_common()): if",
"cursor.execute(''' # Parent comments SELECT p.message, user.name, post.created_time as post_created_time, p.created_time as comment_created_time,",
"IS NULL UNION # Child comments SELECT c.message, user.name, post.created_time as post_created_time, p.created_time",
"row def generate_dataset(args, config): cnx = mysql.connector.connect(user=config[\"database\"][\"user\"], password=config[\"database\"][\"password\"], host=config[\"database\"][\"host\"], database=config[\"database\"][\"db\"]) cursor = cnx.cursor()",
"author in authors] for line in lines: line = self.remove_usernames(line, authors) if 4",
"a new bathch of comments to the dataset. The set of authors ist",
"subcomments, we collect the names of # all subcomment authors to remove them",
"line in lines: line = self.remove_usernames(line, authors) if 4 < len(line) < 500:",
"'txt': with open(outfile, \"wb\") as f: f.write(output) # TODO add bzip else: raise",
"not returned in Graph API's message_tags\"\"\" # First remove the old fashined @",
"f: f.write(output) # TODO add bzip else: raise ValueError('outfile has to be a",
"database=config[\"database\"][\"db\"]) cursor = cnx.cursor() cursor.execute('SELECT count(*) FROM comment') count = cursor.fetchone()[0] bar =",
"old fashined @ tags if len(text) == 0 or ('@' in text and",
"author, post_date, comment_date, subcomment_date) in bar(iter_row(cursor)): if subcomment_date is None: # is parent",
"p.user JOIN post ON post.id = p.post WHERE p.parent_comment IS NULL UNION #",
"is None: # is parent ds.push(comments, authors) authors = {author} comments = [message]",
"Dataset: def __init__(self): self.batches = [] self.vocab_counter = collections.Counter() def write(self, outfile): \"\"\"Writes",
"self.create_output() ending = outfile.split('.')[-1] if ending == 'txt': with open(outfile, \"wb\") as f:",
"= cnx.cursor() cursor.execute('SELECT count(*) FROM comment') count = cursor.fetchone()[0] bar = progressbar.ProgressBar(max_value=count) #",
"bzip else: raise ValueError('outfile has to be a .txt file') @profile def push(self,",
"was not able to filter out because they were not returned in Graph",
"break for row in rows: yield row def generate_dataset(args, config): cnx = mysql.connector.connect(user=config[\"database\"][\"user\"],",
"lines = [] for comment in comments: lines.extend(comment.replace('\\r', '\\n').split('\\n')) txt = '' authors",
"comments.append(message) ds.write(args.out) class Dataset: def __init__(self): self.batches = [] self.vocab_counter = collections.Counter() def",
"True: rows = cursor.fetchmany(size) if not rows: break for row in rows: yield",
"much context between the comments as possible. Everything is sorted ASC by date.",
"context between the comments as possible. Everything is sorted ASC by date. print('Executing",
"4 < len(line) < 500: txt += '> {}\\n'.format(line) return txt if __name__",
"file\"\"\" output = self.create_output() ending = outfile.split('.')[-1] if ending == 'txt': with open(outfile,",
"and merges them to a string\"\"\" txt = '' for line in lines:",
"argparse.ArgumentParser() parser.add_argument('--out', type=str, default='data/racist/racist.txt', help='text file where the data is written to') args",
"as subcomment_created_time FROM comment p JOIN user ON user.id = p.user JOIN post",
"parent comments to # have as much context between the comments as possible.",
"line = self.clean_tags(line) if 4 < len(line) < 500: txt += '> {}\\n'.format(line)",
"FROM comment c JOIN user ON user.id = c.user JOIN comment p on",
"BY post_created_time ASC, comment_created_time ASC, subcomment_created_time ASC LIMIT 300000 ''') print('Done') ds =",
"people tend to reference other people in subcomments, we collect the names of",
"txt += '> {}\\n'.format(line) self.batches.append(txt) self.vocab_counter.update(txt) def remove_usernames(self, text, authors): \"\"\"Removing user names",
"have as much context between the comments as possible. Everything is sorted ASC",
"they were not returned in Graph API's message_tags\"\"\" # First remove the old",
"c.created_time as subcomment_created_time FROM comment c JOIN user ON user.id = c.user JOIN",
"parser = argparse.ArgumentParser() parser.add_argument('--out', type=str, default='data/racist/racist.txt', help='text file where the data is written",
"WHERE p.parent_comment IS NULL UNION # Child comments SELECT c.message, user.name, post.created_time as",
"from the comment and it's subcomments because they mainly reference each other text",
"of comments to the dataset. The set of authors ist used to further",
"0.00002 chars_to_remove = [] for char, count in reversed(self.vocab_counter.most_common()): if count < threshold:",
"the comment and it's subcomments because they mainly reference each other text =",
"by posts and places subcomments after their parent comments to # have as",
"authors ist used to further clean the comments\"\"\" lines = [] for comment",
"for author in authors] for line in lines: line = self.remove_usernames(line, authors) if",
"('@' in text and len(text.split(' ')) <= 3): return '' if text[0] ==",
"= argparse.ArgumentParser() parser.add_argument('--out', type=str, default='data/racist/racist.txt', help='text file where the data is written to')",
"while True: rows = cursor.fetchmany(size) if not rows: break for row in rows:",
"remove_usernames(self, text, authors): \"\"\"Removing user names that the crawler was not able to",
"count(*) FROM comment') count = cursor.fetchone()[0] bar = progressbar.ProgressBar(max_value=count) # This query groups",
"authors.add(author) comments.append(message) ds.write(args.out) class Dataset: def __init__(self): self.batches = [] self.vocab_counter = collections.Counter()",
"< 500: txt += '> {}\\n'.format(line) self.batches.append(txt) self.vocab_counter.update(txt) def remove_usernames(self, text, authors): \"\"\"Removing",
"def remove_usernames(self, text, authors): \"\"\"Removing user names that the crawler was not able",
"of authors ist used to further clean the comments\"\"\" lines = [] for",
"= yaml.load(c) generate_dataset(args, config) def iter_row(cursor, size=1000): while True: rows = cursor.fetchmany(size) if",
"comment in comments: lines.extend(comment.replace('\\r', '\\n').split('\\n')) txt = '' authors = [re.escape(author) for author",
"\"wb\") as f: f.write(output) # TODO add bzip else: raise ValueError('outfile has to",
"text) else: text = re.sub('@', '', text) # Then the names of all",
"print('Done') ds = Dataset() # As people tend to reference other people in",
"rows: break for row in rows: yield row def generate_dataset(args, config): cnx =",
"if len(text) == 0 or ('@' in text and len(text.split(' ')) <= 3):",
"text) return text.strip() @profile def create_output(self): \"\"\"Generates one big cp1252 string\"\"\" output =",
"text[0] == '@': text = re.sub('@ ?.*?((:|,|\\.| {2})| .*?[:,. ])', '', text) else:",
"< 500: txt += '> {}\\n'.format(line) return txt if __name__ == '__main__': main()",
"p.post WHERE p.parent_comment IS NULL UNION # Child comments SELECT c.message, user.name, post.created_time",
"ON user.id = c.user JOIN comment p on p.id = c.parent_comment JOIN post",
"reference each other text = re.sub('({})'.format('|'.join(authors)), '', text) return text.strip() @profile def create_output(self):",
"as comment_created_time, c.created_time as subcomment_created_time FROM comment c JOIN user ON user.id =",
"subcomment_created_time FROM comment p JOIN user ON user.id = p.user JOIN post ON",
"to the dataset. The set of authors ist used to further clean the",
"p.post ORDER BY post_created_time ASC, comment_created_time ASC, subcomment_created_time ASC LIMIT 300000 ''') print('Done')",
"txt = '' for line in lines: line = self.clean_tags(line) if 4 <",
"count = cursor.fetchone()[0] bar = progressbar.ProgressBar(max_value=count) # This query groups comments by posts",
"post_created_time ASC, comment_created_time ASC, subcomment_created_time ASC LIMIT 300000 ''') print('Done') ds = Dataset()",
"outfile): \"\"\"Writes the dataset to a text file\"\"\" output = self.create_output() ending =",
"authors to remove them from the result in the end. authors = set()",
"each other text = re.sub('({})'.format('|'.join(authors)), '', text) return text.strip() @profile def create_output(self): \"\"\"Generates",
"ASC, subcomment_created_time ASC LIMIT 300000 ''') print('Done') ds = Dataset() # As people",
"len(line) < 500: txt += '> {}\\n'.format(line) self.batches.append(txt) self.vocab_counter.update(txt) def remove_usernames(self, text, authors):",
"def merge_lines(self, lines): \"\"\"Cleans and selects qualifying lines and merges them to a",
"import yaml import re import collections def main(): parser = argparse.ArgumentParser() parser.add_argument('--out', type=str,",
"the comments as possible. Everything is sorted ASC by date. print('Executing SQL query...')",
"cursor.execute('SELECT count(*) FROM comment') count = cursor.fetchone()[0] bar = progressbar.ProgressBar(max_value=count) # This query",
"is child authors.add(author) comments.append(message) ds.write(args.out) class Dataset: def __init__(self): self.batches = [] self.vocab_counter",
"self.vocab_counter.update(txt) def remove_usernames(self, text, authors): \"\"\"Removing user names that the crawler was not",
"#Remove all characters that appear in less than 0.002% of the cases threshold",
"for comment in comments: lines.extend(comment.replace('\\r', '\\n').split('\\n')) txt = '' authors = [re.escape(author) for",
"it's subcomments because they mainly reference each other text = re.sub('({})'.format('|'.join(authors)), '', text)",
"= c.parent_comment JOIN post ON post.id = p.post ORDER BY post_created_time ASC, comment_created_time",
"class Dataset: def __init__(self): self.batches = [] self.vocab_counter = collections.Counter() def write(self, outfile):",
"c.message, user.name, post.created_time as post_created_time, p.created_time as comment_created_time, c.created_time as subcomment_created_time FROM comment",
"ASC, comment_created_time ASC, subcomment_created_time ASC LIMIT 300000 ''') print('Done') ds = Dataset() #",
"{2})| .*?[:,. ])', '', text) else: text = re.sub('@', '', text) # Then",
"written to') args = parser.parse_args() with open('config.yml', 'r') as c: config = yaml.load(c)",
"''.join(self.batches) #Remove all characters that appear in less than 0.002% of the cases",
"other people in subcomments, we collect the names of # all subcomment authors",
"comments as possible. Everything is sorted ASC by date. print('Executing SQL query...') cursor.execute('''",
"merge_lines(self, lines): \"\"\"Cleans and selects qualifying lines and merges them to a string\"\"\"",
"host=config[\"database\"][\"host\"], database=config[\"database\"][\"db\"]) cursor = cnx.cursor() cursor.execute('SELECT count(*) FROM comment') count = cursor.fetchone()[0] bar",
"remove them from the result in the end. authors = set() comments =",
"count < threshold: chars_to_remove.append(char) else: break output = re.sub('[' + re.escape(''.join(chars_to_remove)) + ']',",
"JOIN user ON user.id = c.user JOIN comment p on p.id = c.parent_comment",
"comments by posts and places subcomments after their parent comments to # have",
"return text.strip() @profile def create_output(self): \"\"\"Generates one big cp1252 string\"\"\" output = ''.join(self.batches)",
"of all the authors from the comment and it's subcomments because they mainly",
"post_date, comment_date, subcomment_date) in bar(iter_row(cursor)): if subcomment_date is None: # is parent ds.push(comments,",
"of # all subcomment authors to remove them from the result in the",
"output) return output.encode(\"cp1252\", errors=\"ignore\") def merge_lines(self, lines): \"\"\"Cleans and selects qualifying lines and",
"[re.escape(author) for author in authors] for line in lines: line = self.remove_usernames(line, authors)",
"new bathch of comments to the dataset. The set of authors ist used",
"= {author} comments = [message] else: # is child authors.add(author) comments.append(message) ds.write(args.out) class",
"= [] self.vocab_counter = collections.Counter() def write(self, outfile): \"\"\"Writes the dataset to a",
"in rows: yield row def generate_dataset(args, config): cnx = mysql.connector.connect(user=config[\"database\"][\"user\"], password=config[\"database\"][\"password\"], host=config[\"database\"][\"host\"], database=config[\"database\"][\"db\"])",
"authors) authors = {author} comments = [message] else: # is child authors.add(author) comments.append(message)",
"comments\"\"\" lines = [] for comment in comments: lines.extend(comment.replace('\\r', '\\n').split('\\n')) txt = ''",
"the old fashined @ tags if len(text) == 0 or ('@' in text",
"add bzip else: raise ValueError('outfile has to be a .txt file') @profile def",
"cursor.fetchone()[0] bar = progressbar.ProgressBar(max_value=count) # This query groups comments by posts and places",
"in lines: line = self.clean_tags(line) if 4 < len(line) < 500: txt +=",
"result in the end. authors = set() comments = [] for (message, author,",
"or ('@' in text and len(text.split(' ')) <= 3): return '' if text[0]",
"post_created_time, p.created_time as comment_created_time, Null as subcomment_created_time FROM comment p JOIN user ON",
".*?[:,. ])', '', text) else: text = re.sub('@', '', text) # Then the",
"else: text = re.sub('@', '', text) # Then the names of all the",
"names of # all subcomment authors to remove them from the result in",
"self.vocab_counter = collections.Counter() def write(self, outfile): \"\"\"Writes the dataset to a text file\"\"\"",
"comments, authors): \"\"\"Adds a new bathch of comments to the dataset. The set",
"def __init__(self): self.batches = [] self.vocab_counter = collections.Counter() def write(self, outfile): \"\"\"Writes the",
"= set() comments = [] for (message, author, post_date, comment_date, subcomment_date) in bar(iter_row(cursor)):",
"p.parent_comment IS NULL UNION # Child comments SELECT c.message, user.name, post.created_time as post_created_time,",
"re.sub('({})'.format('|'.join(authors)), '', text) return text.strip() @profile def create_output(self): \"\"\"Generates one big cp1252 string\"\"\"",
"lines.extend(comment.replace('\\r', '\\n').split('\\n')) txt = '' authors = [re.escape(author) for author in authors] for",
"names that the crawler was not able to filter out because they were",
"lines: line = self.remove_usernames(line, authors) if 4 < len(line) < 500: txt +=",
"len(text.split(' ')) <= 3): return '' if text[0] == '@': text = re.sub('@",
"cursor = cnx.cursor() cursor.execute('SELECT count(*) FROM comment') count = cursor.fetchone()[0] bar = progressbar.ProgressBar(max_value=count)",
"cp1252 string\"\"\" output = ''.join(self.batches) #Remove all characters that appear in less than",
"JOIN post ON post.id = p.post WHERE p.parent_comment IS NULL UNION # Child",
"= self.create_output() ending = outfile.split('.')[-1] if ending == 'txt': with open(outfile, \"wb\") as",
"that the crawler was not able to filter out because they were not",
"between the comments as possible. Everything is sorted ASC by date. print('Executing SQL",
"= re.sub('@', '', text) # Then the names of all the authors from",
"p JOIN user ON user.id = p.user JOIN post ON post.id = p.post",
"lines): \"\"\"Cleans and selects qualifying lines and merges them to a string\"\"\" txt",
"First remove the old fashined @ tags if len(text) == 0 or ('@'",
"__init__(self): self.batches = [] self.vocab_counter = collections.Counter() def write(self, outfile): \"\"\"Writes the dataset",
"self.remove_usernames(line, authors) if 4 < len(line) < 500: txt += '> {}\\n'.format(line) self.batches.append(txt)",
"set() comments = [] for (message, author, post_date, comment_date, subcomment_date) in bar(iter_row(cursor)): if",
"# Parent comments SELECT p.message, user.name, post.created_time as post_created_time, p.created_time as comment_created_time, Null",
"for line in lines: line = self.clean_tags(line) if 4 < len(line) < 500:",
"parser.add_argument('--out', type=str, default='data/racist/racist.txt', help='text file where the data is written to') args =",
"def generate_dataset(args, config): cnx = mysql.connector.connect(user=config[\"database\"][\"user\"], password=config[\"database\"][\"password\"], host=config[\"database\"][\"host\"], database=config[\"database\"][\"db\"]) cursor = cnx.cursor() cursor.execute('SELECT",
"in Graph API's message_tags\"\"\" # First remove the old fashined @ tags if"
] |
[
"# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-09-15 12:47",
"models class Migration(migrations.Migration): dependencies = [ ('logger', '0002_auto_20161231_1740'), ] operations = [ migrations.AddField(",
"2017-09-15 12:47 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration):",
"import migrations, models class Migration(migrations.Migration): dependencies = [ ('logger', '0002_auto_20161231_1740'), ] operations =",
"<gh_stars>1-10 # -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-09-15",
"utf-8 -*- # Generated by Django 1.11.5 on 2017-09-15 12:47 from __future__ import",
"migrations, models class Migration(migrations.Migration): dependencies = [ ('logger', '0002_auto_20161231_1740'), ] operations = [",
"[ ('logger', '0002_auto_20161231_1740'), ] operations = [ migrations.AddField( model_name='requestlogger', name='sha1', field=models.CharField(blank=True, default=None, max_length=40,",
"('logger', '0002_auto_20161231_1740'), ] operations = [ migrations.AddField( model_name='requestlogger', name='sha1', field=models.CharField(blank=True, default=None, max_length=40, null=True,",
"on 2017-09-15 12:47 from __future__ import unicode_literals from django.db import migrations, models class",
"by Django 1.11.5 on 2017-09-15 12:47 from __future__ import unicode_literals from django.db import",
"12:47 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies",
"from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('logger', '0002_auto_20161231_1740'), ]",
"= [ ('logger', '0002_auto_20161231_1740'), ] operations = [ migrations.AddField( model_name='requestlogger', name='sha1', field=models.CharField(blank=True, default=None,",
"-*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-09-15 12:47 from",
"Migration(migrations.Migration): dependencies = [ ('logger', '0002_auto_20161231_1740'), ] operations = [ migrations.AddField( model_name='requestlogger', name='sha1',",
"Django 1.11.5 on 2017-09-15 12:47 from __future__ import unicode_literals from django.db import migrations,",
"coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-09-15 12:47 from __future__",
"class Migration(migrations.Migration): dependencies = [ ('logger', '0002_auto_20161231_1740'), ] operations = [ migrations.AddField( model_name='requestlogger',",
"'0002_auto_20161231_1740'), ] operations = [ migrations.AddField( model_name='requestlogger', name='sha1', field=models.CharField(blank=True, default=None, max_length=40, null=True, verbose_name='SHA1'),",
"# Generated by Django 1.11.5 on 2017-09-15 12:47 from __future__ import unicode_literals from",
"import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('logger',",
"-*- # Generated by Django 1.11.5 on 2017-09-15 12:47 from __future__ import unicode_literals",
"unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('logger', '0002_auto_20161231_1740'),",
"Generated by Django 1.11.5 on 2017-09-15 12:47 from __future__ import unicode_literals from django.db",
"from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies =",
"dependencies = [ ('logger', '0002_auto_20161231_1740'), ] operations = [ migrations.AddField( model_name='requestlogger', name='sha1', field=models.CharField(blank=True,",
"operations = [ migrations.AddField( model_name='requestlogger', name='sha1', field=models.CharField(blank=True, default=None, max_length=40, null=True, verbose_name='SHA1'), ), ]",
"django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('logger', '0002_auto_20161231_1740'), ] operations",
"1.11.5 on 2017-09-15 12:47 from __future__ import unicode_literals from django.db import migrations, models",
"__future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [",
"] operations = [ migrations.AddField( model_name='requestlogger', name='sha1', field=models.CharField(blank=True, default=None, max_length=40, null=True, verbose_name='SHA1'), ),"
] |
[
"forward(self, x): x = F.relu(self.conv_1(x)) x = F.relu(self.conv_2(x)) x = F.max_pool2d(x, 2) x",
"F.max_pool2d(x, 2) x = self.dropout(x) x = torch.flatten(x, 1) x = self.dropout(F.relu(self.fc_1(x))) out",
"nn.Conv2d(32, 64, 3, 1) self.dropout = nn.Dropout(p=0.5) self.fc_1 = nn.Linear(9216, 128) self.out =",
"= 10 mnist_input_shape = (28, 28, 1) class MnistModel(nn.Module): def __init__(self): super().__init__() self.conv_1",
"class MnistModel(nn.Module): def __init__(self): super().__init__() self.conv_1 = nn.Conv2d(1, 32, 3, 1) self.conv_2 =",
"self.conv_2 = nn.Conv2d(32, 64, 3, 1) self.dropout = nn.Dropout(p=0.5) self.fc_1 = nn.Linear(9216, 128)",
"torch.nn.functional as F N_CLASSES = 10 mnist_input_shape = (28, 28, 1) class MnistModel(nn.Module):",
"3, 1) self.conv_2 = nn.Conv2d(32, 64, 3, 1) self.dropout = nn.Dropout(p=0.5) self.fc_1 =",
"= nn.Conv2d(1, 32, 3, 1) self.conv_2 = nn.Conv2d(32, 64, 3, 1) self.dropout =",
"3, 1) self.dropout = nn.Dropout(p=0.5) self.fc_1 = nn.Linear(9216, 128) self.out = nn.Linear(128, N_CLASSES)",
"F N_CLASSES = 10 mnist_input_shape = (28, 28, 1) class MnistModel(nn.Module): def __init__(self):",
"= nn.Conv2d(32, 64, 3, 1) self.dropout = nn.Dropout(p=0.5) self.fc_1 = nn.Linear(9216, 128) self.out",
"import torch.nn as nn import torch.nn.functional as F N_CLASSES = 10 mnist_input_shape =",
"__init__(self): super().__init__() self.conv_1 = nn.Conv2d(1, 32, 3, 1) self.conv_2 = nn.Conv2d(32, 64, 3,",
"1) self.dropout = nn.Dropout(p=0.5) self.fc_1 = nn.Linear(9216, 128) self.out = nn.Linear(128, N_CLASSES) def",
"= nn.Linear(9216, 128) self.out = nn.Linear(128, N_CLASSES) def forward(self, x): x = F.relu(self.conv_1(x))",
"N_CLASSES) def forward(self, x): x = F.relu(self.conv_1(x)) x = F.relu(self.conv_2(x)) x = F.max_pool2d(x,",
"128) self.out = nn.Linear(128, N_CLASSES) def forward(self, x): x = F.relu(self.conv_1(x)) x =",
"= self.dropout(x) x = torch.flatten(x, 1) x = self.dropout(F.relu(self.fc_1(x))) out = F.log_softmax(self.out(x)) return",
"torch.nn as nn import torch.nn.functional as F N_CLASSES = 10 mnist_input_shape = (28,",
"28, 1) class MnistModel(nn.Module): def __init__(self): super().__init__() self.conv_1 = nn.Conv2d(1, 32, 3, 1)",
"x = F.max_pool2d(x, 2) x = self.dropout(x) x = torch.flatten(x, 1) x =",
"= F.max_pool2d(x, 2) x = self.dropout(x) x = torch.flatten(x, 1) x = self.dropout(F.relu(self.fc_1(x)))",
"N_CLASSES = 10 mnist_input_shape = (28, 28, 1) class MnistModel(nn.Module): def __init__(self): super().__init__()",
"self.fc_1 = nn.Linear(9216, 128) self.out = nn.Linear(128, N_CLASSES) def forward(self, x): x =",
"= (28, 28, 1) class MnistModel(nn.Module): def __init__(self): super().__init__() self.conv_1 = nn.Conv2d(1, 32,",
"10 mnist_input_shape = (28, 28, 1) class MnistModel(nn.Module): def __init__(self): super().__init__() self.conv_1 =",
"(28, 28, 1) class MnistModel(nn.Module): def __init__(self): super().__init__() self.conv_1 = nn.Conv2d(1, 32, 3,",
"import torch import torch.nn as nn import torch.nn.functional as F N_CLASSES = 10",
"MnistModel(nn.Module): def __init__(self): super().__init__() self.conv_1 = nn.Conv2d(1, 32, 3, 1) self.conv_2 = nn.Conv2d(32,",
"def __init__(self): super().__init__() self.conv_1 = nn.Conv2d(1, 32, 3, 1) self.conv_2 = nn.Conv2d(32, 64,",
"= F.relu(self.conv_2(x)) x = F.max_pool2d(x, 2) x = self.dropout(x) x = torch.flatten(x, 1)",
"import torch.nn.functional as F N_CLASSES = 10 mnist_input_shape = (28, 28, 1) class",
"F.relu(self.conv_2(x)) x = F.max_pool2d(x, 2) x = self.dropout(x) x = torch.flatten(x, 1) x",
"super().__init__() self.conv_1 = nn.Conv2d(1, 32, 3, 1) self.conv_2 = nn.Conv2d(32, 64, 3, 1)",
"torch import torch.nn as nn import torch.nn.functional as F N_CLASSES = 10 mnist_input_shape",
"nn.Linear(9216, 128) self.out = nn.Linear(128, N_CLASSES) def forward(self, x): x = F.relu(self.conv_1(x)) x",
"x): x = F.relu(self.conv_1(x)) x = F.relu(self.conv_2(x)) x = F.max_pool2d(x, 2) x =",
"<filename>experiments/models/mnist_torch_models.py import torch import torch.nn as nn import torch.nn.functional as F N_CLASSES =",
"64, 3, 1) self.dropout = nn.Dropout(p=0.5) self.fc_1 = nn.Linear(9216, 128) self.out = nn.Linear(128,",
"nn.Conv2d(1, 32, 3, 1) self.conv_2 = nn.Conv2d(32, 64, 3, 1) self.dropout = nn.Dropout(p=0.5)",
"self.dropout = nn.Dropout(p=0.5) self.fc_1 = nn.Linear(9216, 128) self.out = nn.Linear(128, N_CLASSES) def forward(self,",
"= nn.Dropout(p=0.5) self.fc_1 = nn.Linear(9216, 128) self.out = nn.Linear(128, N_CLASSES) def forward(self, x):",
"nn.Dropout(p=0.5) self.fc_1 = nn.Linear(9216, 128) self.out = nn.Linear(128, N_CLASSES) def forward(self, x): x",
"= F.relu(self.conv_1(x)) x = F.relu(self.conv_2(x)) x = F.max_pool2d(x, 2) x = self.dropout(x) x",
"mnist_input_shape = (28, 28, 1) class MnistModel(nn.Module): def __init__(self): super().__init__() self.conv_1 = nn.Conv2d(1,",
"as nn import torch.nn.functional as F N_CLASSES = 10 mnist_input_shape = (28, 28,",
"self.conv_1 = nn.Conv2d(1, 32, 3, 1) self.conv_2 = nn.Conv2d(32, 64, 3, 1) self.dropout",
"32, 3, 1) self.conv_2 = nn.Conv2d(32, 64, 3, 1) self.dropout = nn.Dropout(p=0.5) self.fc_1",
"nn.Linear(128, N_CLASSES) def forward(self, x): x = F.relu(self.conv_1(x)) x = F.relu(self.conv_2(x)) x =",
"2) x = self.dropout(x) x = torch.flatten(x, 1) x = self.dropout(F.relu(self.fc_1(x))) out =",
"self.out = nn.Linear(128, N_CLASSES) def forward(self, x): x = F.relu(self.conv_1(x)) x = F.relu(self.conv_2(x))",
"1) self.conv_2 = nn.Conv2d(32, 64, 3, 1) self.dropout = nn.Dropout(p=0.5) self.fc_1 = nn.Linear(9216,",
"x = F.relu(self.conv_2(x)) x = F.max_pool2d(x, 2) x = self.dropout(x) x = torch.flatten(x,",
"nn import torch.nn.functional as F N_CLASSES = 10 mnist_input_shape = (28, 28, 1)",
"= nn.Linear(128, N_CLASSES) def forward(self, x): x = F.relu(self.conv_1(x)) x = F.relu(self.conv_2(x)) x",
"x = F.relu(self.conv_1(x)) x = F.relu(self.conv_2(x)) x = F.max_pool2d(x, 2) x = self.dropout(x)",
"as F N_CLASSES = 10 mnist_input_shape = (28, 28, 1) class MnistModel(nn.Module): def",
"def forward(self, x): x = F.relu(self.conv_1(x)) x = F.relu(self.conv_2(x)) x = F.max_pool2d(x, 2)",
"self.dropout(x) x = torch.flatten(x, 1) x = self.dropout(F.relu(self.fc_1(x))) out = F.log_softmax(self.out(x)) return out",
"x = self.dropout(x) x = torch.flatten(x, 1) x = self.dropout(F.relu(self.fc_1(x))) out = F.log_softmax(self.out(x))",
"F.relu(self.conv_1(x)) x = F.relu(self.conv_2(x)) x = F.max_pool2d(x, 2) x = self.dropout(x) x =",
"1) class MnistModel(nn.Module): def __init__(self): super().__init__() self.conv_1 = nn.Conv2d(1, 32, 3, 1) self.conv_2"
] |
[
"enumerate(reader): for cindex, col in enumerate(row): try: worksheet.write(rindex,cindex, float(col)) except ValueError: worksheet.write(rindex, cindex,",
"= os.path.abspath(csvpath) if outname is None: filename = os.path.basename(directory_path + \".xlsx\") else: filename",
"cindex, col) workbook.close() def main(): args = arguments() wrap_csvs(args.path, args.outname) if __name__ ==",
"worksheet.write(rindex,cindex, float(col)) except ValueError: worksheet.write(rindex, cindex, col) workbook.close() def main(): args = arguments()",
"os.path.basename(directory_path + \".xlsx\") else: filename = outname workbook_name = os.path.join(directory_path, filename) workbook =",
"os.getcwd(), help = \"Path to CSV files\") parser.add_argument('--outname', default = None, help =",
"is None: filename = os.path.basename(directory_path + \".xlsx\") else: filename = outname workbook_name =",
"import Workbook def arguments(): parser = argparse.ArgumentParser() parser.add_argument('path', default = os.getcwd(), help =",
"\"*.csv\")): sheetname = os.path.basename(c[:c.rfind(\".\")]) print(\"Adding {} to {}\".format(c, workbook_name)) worksheet = workbook.add_worksheet(sheetname) with",
"reader = csv.reader(f) for rindex, row in enumerate(reader): for cindex, col in enumerate(row):",
"= os.getcwd(), help = \"Path to CSV files\") parser.add_argument('--outname', default = None, help",
"None, help = \"Name of output XLSX file\") return parser.parse_args() def wrap_csvs(csvpath, outname):",
"= csv.reader(f) for rindex, row in enumerate(reader): for cindex, col in enumerate(row): try:",
"{} to {}\".format(c, workbook_name)) worksheet = workbook.add_worksheet(sheetname) with open(c, 'r') as f: reader",
"of output XLSX file\") return parser.parse_args() def wrap_csvs(csvpath, outname): directory_path = os.path.abspath(csvpath) if",
"Workbook def arguments(): parser = argparse.ArgumentParser() parser.add_argument('path', default = os.getcwd(), help = \"Path",
"in enumerate(reader): for cindex, col in enumerate(row): try: worksheet.write(rindex,cindex, float(col)) except ValueError: worksheet.write(rindex,",
"filename = outname workbook_name = os.path.join(directory_path, filename) workbook = Workbook(workbook_name) for c in",
"xlsxwriter.workbook import Workbook def arguments(): parser = argparse.ArgumentParser() parser.add_argument('path', default = os.getcwd(), help",
"glob import csv import argparse from xlsxwriter.workbook import Workbook def arguments(): parser =",
"to CSV files\") parser.add_argument('--outname', default = None, help = \"Name of output XLSX",
"file\") return parser.parse_args() def wrap_csvs(csvpath, outname): directory_path = os.path.abspath(csvpath) if outname is None:",
"outname): directory_path = os.path.abspath(csvpath) if outname is None: filename = os.path.basename(directory_path + \".xlsx\")",
"csv import argparse from xlsxwriter.workbook import Workbook def arguments(): parser = argparse.ArgumentParser() parser.add_argument('path',",
"parser = argparse.ArgumentParser() parser.add_argument('path', default = os.getcwd(), help = \"Path to CSV files\")",
"as f: reader = csv.reader(f) for rindex, row in enumerate(reader): for cindex, col",
"'r') as f: reader = csv.reader(f) for rindex, row in enumerate(reader): for cindex,",
"return parser.parse_args() def wrap_csvs(csvpath, outname): directory_path = os.path.abspath(csvpath) if outname is None: filename",
"= \"Path to CSV files\") parser.add_argument('--outname', default = None, help = \"Name of",
"\".xlsx\") else: filename = outname workbook_name = os.path.join(directory_path, filename) workbook = Workbook(workbook_name) for",
"= \"Name of output XLSX file\") return parser.parse_args() def wrap_csvs(csvpath, outname): directory_path =",
"os.path.join(directory_path, filename) workbook = Workbook(workbook_name) for c in glob.glob(os.path.join(csvpath, \"*.csv\")): sheetname = os.path.basename(c[:c.rfind(\".\")])",
"default = None, help = \"Name of output XLSX file\") return parser.parse_args() def",
"+ \".xlsx\") else: filename = outname workbook_name = os.path.join(directory_path, filename) workbook = Workbook(workbook_name)",
"if outname is None: filename = os.path.basename(directory_path + \".xlsx\") else: filename = outname",
"= Workbook(workbook_name) for c in glob.glob(os.path.join(csvpath, \"*.csv\")): sheetname = os.path.basename(c[:c.rfind(\".\")]) print(\"Adding {} to",
"help = \"Path to CSV files\") parser.add_argument('--outname', default = None, help = \"Name",
"files\") parser.add_argument('--outname', default = None, help = \"Name of output XLSX file\") return",
"def arguments(): parser = argparse.ArgumentParser() parser.add_argument('path', default = os.getcwd(), help = \"Path to",
"cindex, col in enumerate(row): try: worksheet.write(rindex,cindex, float(col)) except ValueError: worksheet.write(rindex, cindex, col) workbook.close()",
"import argparse from xlsxwriter.workbook import Workbook def arguments(): parser = argparse.ArgumentParser() parser.add_argument('path', default",
"ValueError: worksheet.write(rindex, cindex, col) workbook.close() def main(): args = arguments() wrap_csvs(args.path, args.outname) if",
"def wrap_csvs(csvpath, outname): directory_path = os.path.abspath(csvpath) if outname is None: filename = os.path.basename(directory_path",
"float(col)) except ValueError: worksheet.write(rindex, cindex, col) workbook.close() def main(): args = arguments() wrap_csvs(args.path,",
"enumerate(row): try: worksheet.write(rindex,cindex, float(col)) except ValueError: worksheet.write(rindex, cindex, col) workbook.close() def main(): args",
"sheetname = os.path.basename(c[:c.rfind(\".\")]) print(\"Adding {} to {}\".format(c, workbook_name)) worksheet = workbook.add_worksheet(sheetname) with open(c,",
"for rindex, row in enumerate(reader): for cindex, col in enumerate(row): try: worksheet.write(rindex,cindex, float(col))",
"\"Name of output XLSX file\") return parser.parse_args() def wrap_csvs(csvpath, outname): directory_path = os.path.abspath(csvpath)",
"for c in glob.glob(os.path.join(csvpath, \"*.csv\")): sheetname = os.path.basename(c[:c.rfind(\".\")]) print(\"Adding {} to {}\".format(c, workbook_name))",
"None: filename = os.path.basename(directory_path + \".xlsx\") else: filename = outname workbook_name = os.path.join(directory_path,",
"glob.glob(os.path.join(csvpath, \"*.csv\")): sheetname = os.path.basename(c[:c.rfind(\".\")]) print(\"Adding {} to {}\".format(c, workbook_name)) worksheet = workbook.add_worksheet(sheetname)",
"except ValueError: worksheet.write(rindex, cindex, col) workbook.close() def main(): args = arguments() wrap_csvs(args.path, args.outname)",
"= os.path.basename(directory_path + \".xlsx\") else: filename = outname workbook_name = os.path.join(directory_path, filename) workbook",
"col) workbook.close() def main(): args = arguments() wrap_csvs(args.path, args.outname) if __name__ == \"__main__\":",
"else: filename = outname workbook_name = os.path.join(directory_path, filename) workbook = Workbook(workbook_name) for c",
"worksheet.write(rindex, cindex, col) workbook.close() def main(): args = arguments() wrap_csvs(args.path, args.outname) if __name__",
"argparse from xlsxwriter.workbook import Workbook def arguments(): parser = argparse.ArgumentParser() parser.add_argument('path', default =",
"= workbook.add_worksheet(sheetname) with open(c, 'r') as f: reader = csv.reader(f) for rindex, row",
"parser.add_argument('--outname', default = None, help = \"Name of output XLSX file\") return parser.parse_args()",
"{}\".format(c, workbook_name)) worksheet = workbook.add_worksheet(sheetname) with open(c, 'r') as f: reader = csv.reader(f)",
"col in enumerate(row): try: worksheet.write(rindex,cindex, float(col)) except ValueError: worksheet.write(rindex, cindex, col) workbook.close() def",
"workbook.close() def main(): args = arguments() wrap_csvs(args.path, args.outname) if __name__ == \"__main__\": main()",
"workbook_name)) worksheet = workbook.add_worksheet(sheetname) with open(c, 'r') as f: reader = csv.reader(f) for",
"directory_path = os.path.abspath(csvpath) if outname is None: filename = os.path.basename(directory_path + \".xlsx\") else:",
"= outname workbook_name = os.path.join(directory_path, filename) workbook = Workbook(workbook_name) for c in glob.glob(os.path.join(csvpath,",
"CSV files\") parser.add_argument('--outname', default = None, help = \"Name of output XLSX file\")",
"with open(c, 'r') as f: reader = csv.reader(f) for rindex, row in enumerate(reader):",
"import glob import csv import argparse from xlsxwriter.workbook import Workbook def arguments(): parser",
"= None, help = \"Name of output XLSX file\") return parser.parse_args() def wrap_csvs(csvpath,",
"in glob.glob(os.path.join(csvpath, \"*.csv\")): sheetname = os.path.basename(c[:c.rfind(\".\")]) print(\"Adding {} to {}\".format(c, workbook_name)) worksheet =",
"parser.add_argument('path', default = os.getcwd(), help = \"Path to CSV files\") parser.add_argument('--outname', default =",
"in enumerate(row): try: worksheet.write(rindex,cindex, float(col)) except ValueError: worksheet.write(rindex, cindex, col) workbook.close() def main():",
"XLSX file\") return parser.parse_args() def wrap_csvs(csvpath, outname): directory_path = os.path.abspath(csvpath) if outname is",
"import csv import argparse from xlsxwriter.workbook import Workbook def arguments(): parser = argparse.ArgumentParser()",
"workbook.add_worksheet(sheetname) with open(c, 'r') as f: reader = csv.reader(f) for rindex, row in",
"help = \"Name of output XLSX file\") return parser.parse_args() def wrap_csvs(csvpath, outname): directory_path",
"Workbook(workbook_name) for c in glob.glob(os.path.join(csvpath, \"*.csv\")): sheetname = os.path.basename(c[:c.rfind(\".\")]) print(\"Adding {} to {}\".format(c,",
"output XLSX file\") return parser.parse_args() def wrap_csvs(csvpath, outname): directory_path = os.path.abspath(csvpath) if outname",
"outname workbook_name = os.path.join(directory_path, filename) workbook = Workbook(workbook_name) for c in glob.glob(os.path.join(csvpath, \"*.csv\")):",
"os.path.abspath(csvpath) if outname is None: filename = os.path.basename(directory_path + \".xlsx\") else: filename =",
"filename) workbook = Workbook(workbook_name) for c in glob.glob(os.path.join(csvpath, \"*.csv\")): sheetname = os.path.basename(c[:c.rfind(\".\")]) print(\"Adding",
"\"Path to CSV files\") parser.add_argument('--outname', default = None, help = \"Name of output",
"= argparse.ArgumentParser() parser.add_argument('path', default = os.getcwd(), help = \"Path to CSV files\") parser.add_argument('--outname',",
"parser.parse_args() def wrap_csvs(csvpath, outname): directory_path = os.path.abspath(csvpath) if outname is None: filename =",
"csv.reader(f) for rindex, row in enumerate(reader): for cindex, col in enumerate(row): try: worksheet.write(rindex,cindex,",
"print(\"Adding {} to {}\".format(c, workbook_name)) worksheet = workbook.add_worksheet(sheetname) with open(c, 'r') as f:",
"arguments(): parser = argparse.ArgumentParser() parser.add_argument('path', default = os.getcwd(), help = \"Path to CSV",
"worksheet = workbook.add_worksheet(sheetname) with open(c, 'r') as f: reader = csv.reader(f) for rindex,",
"workbook_name = os.path.join(directory_path, filename) workbook = Workbook(workbook_name) for c in glob.glob(os.path.join(csvpath, \"*.csv\")): sheetname",
"default = os.getcwd(), help = \"Path to CSV files\") parser.add_argument('--outname', default = None,",
"import os import glob import csv import argparse from xlsxwriter.workbook import Workbook def",
"= os.path.basename(c[:c.rfind(\".\")]) print(\"Adding {} to {}\".format(c, workbook_name)) worksheet = workbook.add_worksheet(sheetname) with open(c, 'r')",
"wrap_csvs(csvpath, outname): directory_path = os.path.abspath(csvpath) if outname is None: filename = os.path.basename(directory_path +",
"= os.path.join(directory_path, filename) workbook = Workbook(workbook_name) for c in glob.glob(os.path.join(csvpath, \"*.csv\")): sheetname =",
"c in glob.glob(os.path.join(csvpath, \"*.csv\")): sheetname = os.path.basename(c[:c.rfind(\".\")]) print(\"Adding {} to {}\".format(c, workbook_name)) worksheet",
"try: worksheet.write(rindex,cindex, float(col)) except ValueError: worksheet.write(rindex, cindex, col) workbook.close() def main(): args =",
"argparse.ArgumentParser() parser.add_argument('path', default = os.getcwd(), help = \"Path to CSV files\") parser.add_argument('--outname', default",
"rindex, row in enumerate(reader): for cindex, col in enumerate(row): try: worksheet.write(rindex,cindex, float(col)) except",
"open(c, 'r') as f: reader = csv.reader(f) for rindex, row in enumerate(reader): for",
"to {}\".format(c, workbook_name)) worksheet = workbook.add_worksheet(sheetname) with open(c, 'r') as f: reader =",
"from xlsxwriter.workbook import Workbook def arguments(): parser = argparse.ArgumentParser() parser.add_argument('path', default = os.getcwd(),",
"f: reader = csv.reader(f) for rindex, row in enumerate(reader): for cindex, col in",
"outname is None: filename = os.path.basename(directory_path + \".xlsx\") else: filename = outname workbook_name",
"row in enumerate(reader): for cindex, col in enumerate(row): try: worksheet.write(rindex,cindex, float(col)) except ValueError:",
"workbook = Workbook(workbook_name) for c in glob.glob(os.path.join(csvpath, \"*.csv\")): sheetname = os.path.basename(c[:c.rfind(\".\")]) print(\"Adding {}",
"os import glob import csv import argparse from xlsxwriter.workbook import Workbook def arguments():",
"for cindex, col in enumerate(row): try: worksheet.write(rindex,cindex, float(col)) except ValueError: worksheet.write(rindex, cindex, col)",
"filename = os.path.basename(directory_path + \".xlsx\") else: filename = outname workbook_name = os.path.join(directory_path, filename)",
"os.path.basename(c[:c.rfind(\".\")]) print(\"Adding {} to {}\".format(c, workbook_name)) worksheet = workbook.add_worksheet(sheetname) with open(c, 'r') as"
] |
[
"user = context['request'].user.id tenant = context['request'].user.tenant_id keystone = get_admin_ksclient() if OPENSTACK_API_VERSIONS['identity'] == 3:",
"def allowed(self, context): # check if user has special signup role user =",
"horizon from openstack_dashboard.local.local_settings import SIGNUP_ROLES, OPENSTACK_API_VERSIONS from openstack_dashboard.dashboards.identity.signups.common import get_admin_ksclient class Signups(horizon.Panel): name",
"context): # check if user has special signup role user = context['request'].user.id tenant",
"keystone.roles.roles_for_user(user, tenant) for role in roles: if role.name in SIGNUP_ROLES or role.id in",
"# check if user has special signup role user = context['request'].user.id tenant =",
"user has special signup role user = context['request'].user.id tenant = context['request'].user.tenant_id keystone =",
"OPENSTACK_API_VERSIONS['identity'] == 3: roles = keystone.roles.list(user=user, project=tenant) else: roles = keystone.roles.roles_for_user(user, tenant) for",
"tenant) for role in roles: if role.name in SIGNUP_ROLES or role.id in SIGNUP_ROLES:",
"3: roles = keystone.roles.list(user=user, project=tenant) else: roles = keystone.roles.roles_for_user(user, tenant) for role in",
"keystone = get_admin_ksclient() if OPENSTACK_API_VERSIONS['identity'] == 3: roles = keystone.roles.list(user=user, project=tenant) else: roles",
"has special signup role user = context['request'].user.id tenant = context['request'].user.tenant_id keystone = get_admin_ksclient()",
"import SIGNUP_ROLES, OPENSTACK_API_VERSIONS from openstack_dashboard.dashboards.identity.signups.common import get_admin_ksclient class Signups(horizon.Panel): name = _(\"Signups\") slug",
"import get_admin_ksclient class Signups(horizon.Panel): name = _(\"Signups\") slug = 'signups' def allowed(self, context):",
"slug = 'signups' def allowed(self, context): # check if user has special signup",
"== 3: roles = keystone.roles.list(user=user, project=tenant) else: roles = keystone.roles.roles_for_user(user, tenant) for role",
"openstack_dashboard.local.local_settings import SIGNUP_ROLES, OPENSTACK_API_VERSIONS from openstack_dashboard.dashboards.identity.signups.common import get_admin_ksclient class Signups(horizon.Panel): name = _(\"Signups\")",
"import horizon from openstack_dashboard.local.local_settings import SIGNUP_ROLES, OPENSTACK_API_VERSIONS from openstack_dashboard.dashboards.identity.signups.common import get_admin_ksclient class Signups(horizon.Panel):",
"for role in roles: if role.name in SIGNUP_ROLES or role.id in SIGNUP_ROLES: return",
"from openstack_dashboard.local.local_settings import SIGNUP_ROLES, OPENSTACK_API_VERSIONS from openstack_dashboard.dashboards.identity.signups.common import get_admin_ksclient class Signups(horizon.Panel): name =",
"in roles: if role.name in SIGNUP_ROLES or role.id in SIGNUP_ROLES: return True return",
"from django.utils.translation import ugettext_lazy as _ import horizon from openstack_dashboard.local.local_settings import SIGNUP_ROLES, OPENSTACK_API_VERSIONS",
"signup role user = context['request'].user.id tenant = context['request'].user.tenant_id keystone = get_admin_ksclient() if OPENSTACK_API_VERSIONS['identity']",
"project=tenant) else: roles = keystone.roles.roles_for_user(user, tenant) for role in roles: if role.name in",
"= keystone.roles.list(user=user, project=tenant) else: roles = keystone.roles.roles_for_user(user, tenant) for role in roles: if",
"check if user has special signup role user = context['request'].user.id tenant = context['request'].user.tenant_id",
"OPENSTACK_API_VERSIONS from openstack_dashboard.dashboards.identity.signups.common import get_admin_ksclient class Signups(horizon.Panel): name = _(\"Signups\") slug = 'signups'",
"if user has special signup role user = context['request'].user.id tenant = context['request'].user.tenant_id keystone",
"from openstack_dashboard.dashboards.identity.signups.common import get_admin_ksclient class Signups(horizon.Panel): name = _(\"Signups\") slug = 'signups' def",
"class Signups(horizon.Panel): name = _(\"Signups\") slug = 'signups' def allowed(self, context): # check",
"Signups(horizon.Panel): name = _(\"Signups\") slug = 'signups' def allowed(self, context): # check if",
"name = _(\"Signups\") slug = 'signups' def allowed(self, context): # check if user",
"context['request'].user.tenant_id keystone = get_admin_ksclient() if OPENSTACK_API_VERSIONS['identity'] == 3: roles = keystone.roles.list(user=user, project=tenant) else:",
"special signup role user = context['request'].user.id tenant = context['request'].user.tenant_id keystone = get_admin_ksclient() if",
"role user = context['request'].user.id tenant = context['request'].user.tenant_id keystone = get_admin_ksclient() if OPENSTACK_API_VERSIONS['identity'] ==",
"= get_admin_ksclient() if OPENSTACK_API_VERSIONS['identity'] == 3: roles = keystone.roles.list(user=user, project=tenant) else: roles =",
"_ import horizon from openstack_dashboard.local.local_settings import SIGNUP_ROLES, OPENSTACK_API_VERSIONS from openstack_dashboard.dashboards.identity.signups.common import get_admin_ksclient class",
"allowed(self, context): # check if user has special signup role user = context['request'].user.id",
"ugettext_lazy as _ import horizon from openstack_dashboard.local.local_settings import SIGNUP_ROLES, OPENSTACK_API_VERSIONS from openstack_dashboard.dashboards.identity.signups.common import",
"= _(\"Signups\") slug = 'signups' def allowed(self, context): # check if user has",
"keystone.roles.list(user=user, project=tenant) else: roles = keystone.roles.roles_for_user(user, tenant) for role in roles: if role.name",
"as _ import horizon from openstack_dashboard.local.local_settings import SIGNUP_ROLES, OPENSTACK_API_VERSIONS from openstack_dashboard.dashboards.identity.signups.common import get_admin_ksclient",
"= context['request'].user.id tenant = context['request'].user.tenant_id keystone = get_admin_ksclient() if OPENSTACK_API_VERSIONS['identity'] == 3: roles",
"role in roles: if role.name in SIGNUP_ROLES or role.id in SIGNUP_ROLES: return True",
"roles = keystone.roles.roles_for_user(user, tenant) for role in roles: if role.name in SIGNUP_ROLES or",
"= 'signups' def allowed(self, context): # check if user has special signup role",
"if OPENSTACK_API_VERSIONS['identity'] == 3: roles = keystone.roles.list(user=user, project=tenant) else: roles = keystone.roles.roles_for_user(user, tenant)",
"tenant = context['request'].user.tenant_id keystone = get_admin_ksclient() if OPENSTACK_API_VERSIONS['identity'] == 3: roles = keystone.roles.list(user=user,",
"get_admin_ksclient class Signups(horizon.Panel): name = _(\"Signups\") slug = 'signups' def allowed(self, context): #",
"= context['request'].user.tenant_id keystone = get_admin_ksclient() if OPENSTACK_API_VERSIONS['identity'] == 3: roles = keystone.roles.list(user=user, project=tenant)",
"django.utils.translation import ugettext_lazy as _ import horizon from openstack_dashboard.local.local_settings import SIGNUP_ROLES, OPENSTACK_API_VERSIONS from",
"roles: if role.name in SIGNUP_ROLES or role.id in SIGNUP_ROLES: return True return False",
"else: roles = keystone.roles.roles_for_user(user, tenant) for role in roles: if role.name in SIGNUP_ROLES",
"get_admin_ksclient() if OPENSTACK_API_VERSIONS['identity'] == 3: roles = keystone.roles.list(user=user, project=tenant) else: roles = keystone.roles.roles_for_user(user,",
"_(\"Signups\") slug = 'signups' def allowed(self, context): # check if user has special",
"context['request'].user.id tenant = context['request'].user.tenant_id keystone = get_admin_ksclient() if OPENSTACK_API_VERSIONS['identity'] == 3: roles =",
"= keystone.roles.roles_for_user(user, tenant) for role in roles: if role.name in SIGNUP_ROLES or role.id",
"import ugettext_lazy as _ import horizon from openstack_dashboard.local.local_settings import SIGNUP_ROLES, OPENSTACK_API_VERSIONS from openstack_dashboard.dashboards.identity.signups.common",
"SIGNUP_ROLES, OPENSTACK_API_VERSIONS from openstack_dashboard.dashboards.identity.signups.common import get_admin_ksclient class Signups(horizon.Panel): name = _(\"Signups\") slug =",
"roles = keystone.roles.list(user=user, project=tenant) else: roles = keystone.roles.roles_for_user(user, tenant) for role in roles:",
"openstack_dashboard.dashboards.identity.signups.common import get_admin_ksclient class Signups(horizon.Panel): name = _(\"Signups\") slug = 'signups' def allowed(self,",
"'signups' def allowed(self, context): # check if user has special signup role user"
] |
[
"answer=input_number(\"What is \" + str(num1) + \" x \" + str(num2) + \"?\")",
"break except ValueError: print(\"Oops! That wasn't a valid number. Try again.\") return number",
"\" x \" + str(num2) + \"?\") if answer==num1*num2: print(\"Correct!\") return True else:",
"int(duration), \"seconds\") print(\"This means you scored\", int(score), \"points!\") print() # Main game loop",
"correct, \"sums correct in\", int(duration), \"seconds\") print(\"This means you scored\", int(score), \"points!\") print()",
"a valid number. Try again.\") return number def ask_times_table(num1, num2): answer=input_number(\"What is \"",
"print(\"Correct!\") return True else: print(\"Wrong, the answer is\", num1*num2) return False def do_times_table_test(table):",
"score_multiplier=1+3*(60-duration)/60 else: score_multiplier=1 score=correct*score_multiplier print() print(\"You got\", correct, \"sums correct in\", int(duration), \"seconds\")",
"score_multiplier=1 score=correct*score_multiplier print() print(\"You got\", correct, \"sums correct in\", int(duration), \"seconds\") print(\"This means",
"False def do_times_table_test(table): questions=list(range(1, 13)) random.shuffle(questions) correct=0 start_time=time.time() for question in questions: print()",
"you scored\", int(score), \"points!\") print() # Main game loop while True: table=input_number(\"Which times",
"the answer is\", num1*num2) return False def do_times_table_test(table): questions=list(range(1, 13)) random.shuffle(questions) correct=0 start_time=time.time()",
"That wasn't a valid number. Try again.\") return number def ask_times_table(num1, num2): answer=input_number(\"What",
"return True else: print(\"Wrong, the answer is\", num1*num2) return False def do_times_table_test(table): questions=list(range(1,",
"print(prompt) number=int(input(\"> \")) break except ValueError: print(\"Oops! That wasn't a valid number. Try",
"num1*num2) return False def do_times_table_test(table): questions=list(range(1, 13)) random.shuffle(questions) correct=0 start_time=time.time() for question in",
"def do_times_table_test(table): questions=list(range(1, 13)) random.shuffle(questions) correct=0 start_time=time.time() for question in questions: print() if",
"ValueError: print(\"Oops! That wasn't a valid number. Try again.\") return number def ask_times_table(num1,",
"valid number. Try again.\") return number def ask_times_table(num1, num2): answer=input_number(\"What is \" +",
"duration=end_time-start_time # Bonus score if you took less than 60 seconds if duration<60:",
"print(\"You got\", correct, \"sums correct in\", int(duration), \"seconds\") print(\"This means you scored\", int(score),",
"True: try: print(prompt) number=int(input(\"> \")) break except ValueError: print(\"Oops! That wasn't a valid",
"print() print(\"You got\", correct, \"sums correct in\", int(duration), \"seconds\") print(\"This means you scored\",",
"questions: print() if ask_times_table(table, question): correct=correct+1 end_time=time.time() duration=end_time-start_time # Bonus score if you",
"# Bonus score if you took less than 60 seconds if duration<60: score_multiplier=1+3*(60-duration)/60",
"try: print(prompt) number=int(input(\"> \")) break except ValueError: print(\"Oops! That wasn't a valid number.",
"took less than 60 seconds if duration<60: score_multiplier=1+3*(60-duration)/60 else: score_multiplier=1 score=correct*score_multiplier print() print(\"You",
"number. Try again.\") return number def ask_times_table(num1, num2): answer=input_number(\"What is \" + str(num1)",
"import random import time def input_number(prompt): while True: try: print(prompt) number=int(input(\"> \")) break",
"\"sums correct in\", int(duration), \"seconds\") print(\"This means you scored\", int(score), \"points!\") print() #",
"60 seconds if duration<60: score_multiplier=1+3*(60-duration)/60 else: score_multiplier=1 score=correct*score_multiplier print() print(\"You got\", correct, \"sums",
"duration<60: score_multiplier=1+3*(60-duration)/60 else: score_multiplier=1 score=correct*score_multiplier print() print(\"You got\", correct, \"sums correct in\", int(duration),",
"seconds if duration<60: score_multiplier=1+3*(60-duration)/60 else: score_multiplier=1 score=correct*score_multiplier print() print(\"You got\", correct, \"sums correct",
"Main game loop while True: table=input_number(\"Which times table do you want to try?\")",
"+ \" x \" + str(num2) + \"?\") if answer==num1*num2: print(\"Correct!\") return True",
"else: print(\"Wrong, the answer is\", num1*num2) return False def do_times_table_test(table): questions=list(range(1, 13)) random.shuffle(questions)",
"if you took less than 60 seconds if duration<60: score_multiplier=1+3*(60-duration)/60 else: score_multiplier=1 score=correct*score_multiplier",
"\")) break except ValueError: print(\"Oops! That wasn't a valid number. Try again.\") return",
"is \" + str(num1) + \" x \" + str(num2) + \"?\") if",
"in questions: print() if ask_times_table(table, question): correct=correct+1 end_time=time.time() duration=end_time-start_time # Bonus score if",
"while True: try: print(prompt) number=int(input(\"> \")) break except ValueError: print(\"Oops! That wasn't a",
"for question in questions: print() if ask_times_table(table, question): correct=correct+1 end_time=time.time() duration=end_time-start_time # Bonus",
"print(\"Wrong, the answer is\", num1*num2) return False def do_times_table_test(table): questions=list(range(1, 13)) random.shuffle(questions) correct=0",
"questions=list(range(1, 13)) random.shuffle(questions) correct=0 start_time=time.time() for question in questions: print() if ask_times_table(table, question):",
"game loop while True: table=input_number(\"Which times table do you want to try?\") do_times_table_test(table)",
"less than 60 seconds if duration<60: score_multiplier=1+3*(60-duration)/60 else: score_multiplier=1 score=correct*score_multiplier print() print(\"You got\",",
"scored\", int(score), \"points!\") print() # Main game loop while True: table=input_number(\"Which times table",
"num2): answer=input_number(\"What is \" + str(num1) + \" x \" + str(num2) +",
"wasn't a valid number. Try again.\") return number def ask_times_table(num1, num2): answer=input_number(\"What is",
"correct=correct+1 end_time=time.time() duration=end_time-start_time # Bonus score if you took less than 60 seconds",
"True else: print(\"Wrong, the answer is\", num1*num2) return False def do_times_table_test(table): questions=list(range(1, 13))",
"means you scored\", int(score), \"points!\") print() # Main game loop while True: table=input_number(\"Which",
"answer==num1*num2: print(\"Correct!\") return True else: print(\"Wrong, the answer is\", num1*num2) return False def",
"str(num2) + \"?\") if answer==num1*num2: print(\"Correct!\") return True else: print(\"Wrong, the answer is\",",
"score=correct*score_multiplier print() print(\"You got\", correct, \"sums correct in\", int(duration), \"seconds\") print(\"This means you",
"print(\"Oops! That wasn't a valid number. Try again.\") return number def ask_times_table(num1, num2):",
"print() # Main game loop while True: table=input_number(\"Which times table do you want",
"\" + str(num1) + \" x \" + str(num2) + \"?\") if answer==num1*num2:",
"\"points!\") print() # Main game loop while True: table=input_number(\"Which times table do you",
"you took less than 60 seconds if duration<60: score_multiplier=1+3*(60-duration)/60 else: score_multiplier=1 score=correct*score_multiplier print()",
"Try again.\") return number def ask_times_table(num1, num2): answer=input_number(\"What is \" + str(num1) +",
"# Main game loop while True: table=input_number(\"Which times table do you want to",
"if duration<60: score_multiplier=1+3*(60-duration)/60 else: score_multiplier=1 score=correct*score_multiplier print() print(\"You got\", correct, \"sums correct in\",",
"Bonus score if you took less than 60 seconds if duration<60: score_multiplier=1+3*(60-duration)/60 else:",
"again.\") return number def ask_times_table(num1, num2): answer=input_number(\"What is \" + str(num1) + \"",
"except ValueError: print(\"Oops! That wasn't a valid number. Try again.\") return number def",
"if ask_times_table(table, question): correct=correct+1 end_time=time.time() duration=end_time-start_time # Bonus score if you took less",
"+ str(num2) + \"?\") if answer==num1*num2: print(\"Correct!\") return True else: print(\"Wrong, the answer",
"\" + str(num2) + \"?\") if answer==num1*num2: print(\"Correct!\") return True else: print(\"Wrong, the",
"correct in\", int(duration), \"seconds\") print(\"This means you scored\", int(score), \"points!\") print() # Main",
"return number def ask_times_table(num1, num2): answer=input_number(\"What is \" + str(num1) + \" x",
"correct=0 start_time=time.time() for question in questions: print() if ask_times_table(table, question): correct=correct+1 end_time=time.time() duration=end_time-start_time",
"print() if ask_times_table(table, question): correct=correct+1 end_time=time.time() duration=end_time-start_time # Bonus score if you took",
"end_time=time.time() duration=end_time-start_time # Bonus score if you took less than 60 seconds if",
"x \" + str(num2) + \"?\") if answer==num1*num2: print(\"Correct!\") return True else: print(\"Wrong,",
"ask_times_table(num1, num2): answer=input_number(\"What is \" + str(num1) + \" x \" + str(num2)",
"ask_times_table(table, question): correct=correct+1 end_time=time.time() duration=end_time-start_time # Bonus score if you took less than",
"input_number(prompt): while True: try: print(prompt) number=int(input(\"> \")) break except ValueError: print(\"Oops! That wasn't",
"got\", correct, \"sums correct in\", int(duration), \"seconds\") print(\"This means you scored\", int(score), \"points!\")",
"number=int(input(\"> \")) break except ValueError: print(\"Oops! That wasn't a valid number. Try again.\")",
"in\", int(duration), \"seconds\") print(\"This means you scored\", int(score), \"points!\") print() # Main game",
"+ \"?\") if answer==num1*num2: print(\"Correct!\") return True else: print(\"Wrong, the answer is\", num1*num2)",
"\"?\") if answer==num1*num2: print(\"Correct!\") return True else: print(\"Wrong, the answer is\", num1*num2) return",
"print(\"This means you scored\", int(score), \"points!\") print() # Main game loop while True:",
"int(score), \"points!\") print() # Main game loop while True: table=input_number(\"Which times table do",
"start_time=time.time() for question in questions: print() if ask_times_table(table, question): correct=correct+1 end_time=time.time() duration=end_time-start_time #",
"def ask_times_table(num1, num2): answer=input_number(\"What is \" + str(num1) + \" x \" +",
"import time def input_number(prompt): while True: try: print(prompt) number=int(input(\"> \")) break except ValueError:",
"do_times_table_test(table): questions=list(range(1, 13)) random.shuffle(questions) correct=0 start_time=time.time() for question in questions: print() if ask_times_table(table,",
"\"seconds\") print(\"This means you scored\", int(score), \"points!\") print() # Main game loop while",
"<filename>lesson5/times_table_challenge.py import random import time def input_number(prompt): while True: try: print(prompt) number=int(input(\"> \"))",
"13)) random.shuffle(questions) correct=0 start_time=time.time() for question in questions: print() if ask_times_table(table, question): correct=correct+1",
"else: score_multiplier=1 score=correct*score_multiplier print() print(\"You got\", correct, \"sums correct in\", int(duration), \"seconds\") print(\"This",
"return False def do_times_table_test(table): questions=list(range(1, 13)) random.shuffle(questions) correct=0 start_time=time.time() for question in questions:",
"if answer==num1*num2: print(\"Correct!\") return True else: print(\"Wrong, the answer is\", num1*num2) return False",
"def input_number(prompt): while True: try: print(prompt) number=int(input(\"> \")) break except ValueError: print(\"Oops! That",
"than 60 seconds if duration<60: score_multiplier=1+3*(60-duration)/60 else: score_multiplier=1 score=correct*score_multiplier print() print(\"You got\", correct,",
"random.shuffle(questions) correct=0 start_time=time.time() for question in questions: print() if ask_times_table(table, question): correct=correct+1 end_time=time.time()",
"time def input_number(prompt): while True: try: print(prompt) number=int(input(\"> \")) break except ValueError: print(\"Oops!",
"is\", num1*num2) return False def do_times_table_test(table): questions=list(range(1, 13)) random.shuffle(questions) correct=0 start_time=time.time() for question",
"str(num1) + \" x \" + str(num2) + \"?\") if answer==num1*num2: print(\"Correct!\") return",
"answer is\", num1*num2) return False def do_times_table_test(table): questions=list(range(1, 13)) random.shuffle(questions) correct=0 start_time=time.time() for",
"question): correct=correct+1 end_time=time.time() duration=end_time-start_time # Bonus score if you took less than 60",
"number def ask_times_table(num1, num2): answer=input_number(\"What is \" + str(num1) + \" x \"",
"+ str(num1) + \" x \" + str(num2) + \"?\") if answer==num1*num2: print(\"Correct!\")",
"random import time def input_number(prompt): while True: try: print(prompt) number=int(input(\"> \")) break except",
"question in questions: print() if ask_times_table(table, question): correct=correct+1 end_time=time.time() duration=end_time-start_time # Bonus score",
"score if you took less than 60 seconds if duration<60: score_multiplier=1+3*(60-duration)/60 else: score_multiplier=1"
] |
[
"a non reviewer to review if (self.request.user.userprofile not in review.reviewers.all()) and (not review.public):",
"review.reviewers.all()) and (not review.public): messages.add_message( self.request, messages.WARNING, _('Sorry, you do not have access",
"messages.WARNING, _(\"You need to be logged in to review\")) return redirect('dashboard') elif Answer.objects.filter(userprofile=self.request.user.userprofile).filter(review=review).exists():",
"import Answer class ReviewMixin(object): \"\"\" Control who can take a review \"\"\" def",
"not have access to that section')) return redirect('dashboard') # not more than one",
"answers.models import Answer class ReviewMixin(object): \"\"\" Control who can take a review \"\"\"",
"from django.shortcuts import redirect from django.contrib import messages from django.utils.translation import ugettext as",
"if (self.request.user.userprofile not in review.reviewers.all()) and (not review.public): messages.add_message( self.request, messages.WARNING, _('Sorry, you",
"logged in to review\")) return redirect('dashboard') elif Answer.objects.filter(userprofile=self.request.user.userprofile).filter(review=review).exists(): messages.add_message( self.request, messages.WARNING, _(\"You can",
"django.shortcuts import redirect from django.contrib import messages from django.utils.translation import ugettext as _",
"be logged in to review\")) return redirect('dashboard') elif Answer.objects.filter(userprofile=self.request.user.userprofile).filter(review=review).exists(): messages.add_message( self.request, messages.WARNING, _(\"You",
"import messages from django.utils.translation import ugettext as _ from answers.models import Answer class",
"and (not review.public): messages.add_message( self.request, messages.WARNING, _('Sorry, you do not have access to",
"ReviewMixin(object): \"\"\" Control who can take a review \"\"\" def dispatch(self, *args, **kwargs):",
"review \"\"\" def dispatch(self, *args, **kwargs): review = self.get_object() # dont allow a",
"return redirect('dashboard') # not more than one reviews if review.quiz.single_attempt: if not self.request.user.is_authenticated():",
"can take a review \"\"\" def dispatch(self, *args, **kwargs): review = self.get_object() #",
"messages from django.utils.translation import ugettext as _ from answers.models import Answer class ReviewMixin(object):",
"one reviews if review.quiz.single_attempt: if not self.request.user.is_authenticated(): messages.add_message( self.request, messages.WARNING, _(\"You need to",
"self.request, messages.WARNING, _('Sorry, you do not have access to that section')) return redirect('dashboard')",
"from answers.models import Answer class ReviewMixin(object): \"\"\" Control who can take a review",
"class ReviewMixin(object): \"\"\" Control who can take a review \"\"\" def dispatch(self, *args,",
"review.public): messages.add_message( self.request, messages.WARNING, _('Sorry, you do not have access to that section'))",
"_('Sorry, you do not have access to that section')) return redirect('dashboard') # not",
"not self.request.user.is_authenticated(): messages.add_message( self.request, messages.WARNING, _(\"You need to be logged in to review\"))",
"to that section')) return redirect('dashboard') # not more than one reviews if review.quiz.single_attempt:",
"if review.quiz.single_attempt: if not self.request.user.is_authenticated(): messages.add_message( self.request, messages.WARNING, _(\"You need to be logged",
"take a review \"\"\" def dispatch(self, *args, **kwargs): review = self.get_object() # dont",
"(self.request.user.userprofile not in review.reviewers.all()) and (not review.public): messages.add_message( self.request, messages.WARNING, _('Sorry, you do",
"need to be logged in to review\")) return redirect('dashboard') elif Answer.objects.filter(userprofile=self.request.user.userprofile).filter(review=review).exists(): messages.add_message( self.request,",
"have access to that section')) return redirect('dashboard') # not more than one reviews",
"access to that section')) return redirect('dashboard') # not more than one reviews if",
"review\")) return redirect('dashboard') elif Answer.objects.filter(userprofile=self.request.user.userprofile).filter(review=review).exists(): messages.add_message( self.request, messages.WARNING, _(\"You can only review once\"))",
"who can take a review \"\"\" def dispatch(self, *args, **kwargs): review = self.get_object()",
"messages.add_message( self.request, messages.WARNING, _(\"You need to be logged in to review\")) return redirect('dashboard')",
"if not self.request.user.is_authenticated(): messages.add_message( self.request, messages.WARNING, _(\"You need to be logged in to",
"review = self.get_object() # dont allow a non reviewer to review if (self.request.user.userprofile",
"self.request, messages.WARNING, _(\"You can only review once\")) return redirect('dashboard') return super(ReviewMixin, self).dispatch(*args, **kwargs)",
"as _ from answers.models import Answer class ReviewMixin(object): \"\"\" Control who can take",
"**kwargs): review = self.get_object() # dont allow a non reviewer to review if",
"self.request.user.is_authenticated(): messages.add_message( self.request, messages.WARNING, _(\"You need to be logged in to review\")) return",
"self.get_object() # dont allow a non reviewer to review if (self.request.user.userprofile not in",
"to be logged in to review\")) return redirect('dashboard') elif Answer.objects.filter(userprofile=self.request.user.userprofile).filter(review=review).exists(): messages.add_message( self.request, messages.WARNING,",
"import redirect from django.contrib import messages from django.utils.translation import ugettext as _ from",
"reviews if review.quiz.single_attempt: if not self.request.user.is_authenticated(): messages.add_message( self.request, messages.WARNING, _(\"You need to be",
"in review.reviewers.all()) and (not review.public): messages.add_message( self.request, messages.WARNING, _('Sorry, you do not have",
"<reponame>moshthepitt/answers from django.shortcuts import redirect from django.contrib import messages from django.utils.translation import ugettext",
"allow a non reviewer to review if (self.request.user.userprofile not in review.reviewers.all()) and (not",
"reviewer to review if (self.request.user.userprofile not in review.reviewers.all()) and (not review.public): messages.add_message( self.request,",
"# not more than one reviews if review.quiz.single_attempt: if not self.request.user.is_authenticated(): messages.add_message( self.request,",
"in to review\")) return redirect('dashboard') elif Answer.objects.filter(userprofile=self.request.user.userprofile).filter(review=review).exists(): messages.add_message( self.request, messages.WARNING, _(\"You can only",
"from django.utils.translation import ugettext as _ from answers.models import Answer class ReviewMixin(object): \"\"\"",
"\"\"\" Control who can take a review \"\"\" def dispatch(self, *args, **kwargs): review",
"= self.get_object() # dont allow a non reviewer to review if (self.request.user.userprofile not",
"Control who can take a review \"\"\" def dispatch(self, *args, **kwargs): review =",
"redirect from django.contrib import messages from django.utils.translation import ugettext as _ from answers.models",
"dispatch(self, *args, **kwargs): review = self.get_object() # dont allow a non reviewer to",
"than one reviews if review.quiz.single_attempt: if not self.request.user.is_authenticated(): messages.add_message( self.request, messages.WARNING, _(\"You need",
"from django.contrib import messages from django.utils.translation import ugettext as _ from answers.models import",
"ugettext as _ from answers.models import Answer class ReviewMixin(object): \"\"\" Control who can",
"redirect('dashboard') elif Answer.objects.filter(userprofile=self.request.user.userprofile).filter(review=review).exists(): messages.add_message( self.request, messages.WARNING, _(\"You can only review once\")) return redirect('dashboard')",
"to review if (self.request.user.userprofile not in review.reviewers.all()) and (not review.public): messages.add_message( self.request, messages.WARNING,",
"self.request, messages.WARNING, _(\"You need to be logged in to review\")) return redirect('dashboard') elif",
"a review \"\"\" def dispatch(self, *args, **kwargs): review = self.get_object() # dont allow",
"more than one reviews if review.quiz.single_attempt: if not self.request.user.is_authenticated(): messages.add_message( self.request, messages.WARNING, _(\"You",
"Answer class ReviewMixin(object): \"\"\" Control who can take a review \"\"\" def dispatch(self,",
"_(\"You need to be logged in to review\")) return redirect('dashboard') elif Answer.objects.filter(userprofile=self.request.user.userprofile).filter(review=review).exists(): messages.add_message(",
"(not review.public): messages.add_message( self.request, messages.WARNING, _('Sorry, you do not have access to that",
"not in review.reviewers.all()) and (not review.public): messages.add_message( self.request, messages.WARNING, _('Sorry, you do not",
"to review\")) return redirect('dashboard') elif Answer.objects.filter(userprofile=self.request.user.userprofile).filter(review=review).exists(): messages.add_message( self.request, messages.WARNING, _(\"You can only review",
"non reviewer to review if (self.request.user.userprofile not in review.reviewers.all()) and (not review.public): messages.add_message(",
"return redirect('dashboard') elif Answer.objects.filter(userprofile=self.request.user.userprofile).filter(review=review).exists(): messages.add_message( self.request, messages.WARNING, _(\"You can only review once\")) return",
"\"\"\" def dispatch(self, *args, **kwargs): review = self.get_object() # dont allow a non",
"django.utils.translation import ugettext as _ from answers.models import Answer class ReviewMixin(object): \"\"\" Control",
"messages.add_message( self.request, messages.WARNING, _('Sorry, you do not have access to that section')) return",
"# dont allow a non reviewer to review if (self.request.user.userprofile not in review.reviewers.all())",
"messages.add_message( self.request, messages.WARNING, _(\"You can only review once\")) return redirect('dashboard') return super(ReviewMixin, self).dispatch(*args,",
"not more than one reviews if review.quiz.single_attempt: if not self.request.user.is_authenticated(): messages.add_message( self.request, messages.WARNING,",
"review.quiz.single_attempt: if not self.request.user.is_authenticated(): messages.add_message( self.request, messages.WARNING, _(\"You need to be logged in",
"_ from answers.models import Answer class ReviewMixin(object): \"\"\" Control who can take a",
"django.contrib import messages from django.utils.translation import ugettext as _ from answers.models import Answer",
"messages.WARNING, _('Sorry, you do not have access to that section')) return redirect('dashboard') #",
"import ugettext as _ from answers.models import Answer class ReviewMixin(object): \"\"\" Control who",
"*args, **kwargs): review = self.get_object() # dont allow a non reviewer to review",
"def dispatch(self, *args, **kwargs): review = self.get_object() # dont allow a non reviewer",
"that section')) return redirect('dashboard') # not more than one reviews if review.quiz.single_attempt: if",
"you do not have access to that section')) return redirect('dashboard') # not more",
"redirect('dashboard') # not more than one reviews if review.quiz.single_attempt: if not self.request.user.is_authenticated(): messages.add_message(",
"review if (self.request.user.userprofile not in review.reviewers.all()) and (not review.public): messages.add_message( self.request, messages.WARNING, _('Sorry,",
"elif Answer.objects.filter(userprofile=self.request.user.userprofile).filter(review=review).exists(): messages.add_message( self.request, messages.WARNING, _(\"You can only review once\")) return redirect('dashboard') return",
"Answer.objects.filter(userprofile=self.request.user.userprofile).filter(review=review).exists(): messages.add_message( self.request, messages.WARNING, _(\"You can only review once\")) return redirect('dashboard') return super(ReviewMixin,",
"dont allow a non reviewer to review if (self.request.user.userprofile not in review.reviewers.all()) and",
"section')) return redirect('dashboard') # not more than one reviews if review.quiz.single_attempt: if not",
"do not have access to that section')) return redirect('dashboard') # not more than"
] |
[
"var, new_var): \"\"\"Finds the difference between the current and previous variable. Requires a",
"= [] for direct in (\"A\", \"B\", \"R\", \"L\"): tups = generate_clone_tuples(cl_corn, direct)",
"string else string def to_24_hour(datetime): \"\"\"Converts datetime.datetime type to 24 hour float type.",
"min(H, max(geometry[0, :])) min_x = max(0, min(geometry[1, :])) max_x = min(W, max(geometry[1, :]))",
"jpg_paths = find_imgs(dirpath) print(f\"{len(jpg_paths)} images found.\") jpg_data = attach_exif(jpg_paths, parse_tags) jpg_data.sort(key=sort_key) if process_options",
"str_ = ''.join(x for x in str(raw) if x in string.digits) return dt.strptime(str_,",
"= [ (\"RESP\", 0.08, 0, 100, mod, \"%.2e\"), (\"TRANS\", 0.06, 0, 120, self.plt_vals[\"trans_thresh\"],",
"<= self.plt_vals[\"smooth_time\"]) prev = curr else: nudge = int(self.plt_vals[\"smooth_time\"]) master_set = set() for",
"= os.path.join(dir_, filename) output.append({ \"filename\": filename, \"filepath\": filepath }) return output def attach_exif(jpg_data,",
"image_pano(event.xdata) elif event.key == \".\": self.user_edits = {} def off_key(event): try: if event.xdata",
"\"\"\"Returns a cropped image with an equalized histogram. Parameters ---------- image : numpy.ndarray",
": int, in range(0, 256) Parameter to be passed to the cv2.threshold() function.",
"the absolute difference to be taken. prev : numpy.ndarray Like curr. The second",
"hist_median(jpg) if not thresh_init: threshold = row[\"median\"]*1.05 try: row[\"count\"] = method(curr, prev, threshold,",
"prev, threshold, ksize=11, min_area=100): \"\"\"Slower, but powerful frame differencing method. Takes two images,",
"the Gallery tab. \"\"\" self.resp_var = resp_var self.plt_vals = DEFAULT_PLOT_PARAMS self.lines = {}",
"or b > H or c < 0 or d > W): trials.append((tups,",
"plot() method. To reset these values, re- assign DEFAULT_PLOT_PARAMS to this attribute. Methods",
"hi_W = (0 - W // scale), (W + W // scale) lo_H,",
"seconds. Returns ------- str Right justified 2 spaces, filled with zeros. \"\"\" d",
"hi_H = (0 - H // scale), (H + H // scale) gs",
"variable. Requires a list of dictionaries. \"\"\" prev = self.jpg_data[0][var] for row in",
"is easily provided by find_imgs() prior to this function. export_dir : str Directory",
"area. Returns ------- pair of tuples Matches the format for the clone parameter",
"threshold, 255, cv2.THRESH_BINARY) return cv2.countNonZero(mask) # Difference, blur (amount changes with ksize), mask",
"anon(tags[key][tag]) output.append(row) return output def hist_median(image): \"\"\"Quickly finds the median tone of a",
"clone_to : tuple Format is (y1, y2, x1, x2), just like slicing images",
"{ \"drawtype\": \"box\", \"useblit\": True, \"button\": [1, 3], \"minspanx\": 5, \"minspany\": 5, \"spancoords\":",
"images read from jpg_data filepaths before being passed on to frame differencing methods",
"any(n >= self.length for n in array): array -= 1 else: break stack",
"list of dictionaries. \"\"\" prev = self.jpg_data[0][var] for row in self.jpg_data: curr =",
"for row in self.jpg_data: row[\"24hr\"] = to_24_hour(row[\"datetime\"]) row[\"td_minutes\"] = round( row[\"timedelta\"].total_seconds() / 60,",
"(\"TRANS\", 0.06, 0, 120, self.plt_vals[\"trans_thresh\"], \"%.1f\"), (\"SMOOTH\", 0.04, 0, 10, self.plt_vals[\"smooth_time\"], \"%.1f\"), (\"NIGHT\",",
"# This way, someone can load() older, processed data. if jpg_data: self.jpg_data =",
"to format. fmt : str Contains format calls to days, hours, minutes, and",
"images. First, images are identified as being selected or not. Then, events are",
"low), min(self.length, high+1)) if event.key in \"zx\": new_edits = {i: self.press[0] for i",
"thumb_dir is not None: row[\"thumbpath\"] = os.path.join(thumb_dir, row[\"filename\"]) else: row[\"thumbpath\"] = row[\"filepath\"] row[\"count\"]",
"choose.append((sum(cv2.sumElems(diff)), direct, test)) choose.sort() if choose: _, directs, imgs = list(zip(*choose)) mem.clone_directs =",
"max_y, min_x, max_x))), ignore def RS_event(eclick, erelease): x1, y1 = eclick.xdata, eclick.ydata x2,",
"in exporting, parameters for graphing, and plot function. class Cam(): \"\"\" A class",
"else: self.jpg_data[i][kind] = True self.jpg_data[i-1][kind] = True def update_counts(self): \"\"\"Updates jpg_data with new",
"a response, but alternatives like \"median\" can be used to plot jpgs without",
"for deep_row in jpg_data: row = deep_row.copy() tags = piexif.load(row[\"filepath\"]) for (key, tag),",
"self.recent_folder = os.path.expanduser(\"~\") # Cam objects don\"t need to have data to initialize.",
"= index in night_indices def save(self, filename): \"\"\"Dumps a JSON object with jpg_data,",
"f: variables = sorted(write_data[0].keys(), key=sort_cols) for i, row in enumerate(write_data): if i !=",
"= fig.add_axes([0.125, pos, 0.8, 0.02]) self.sliders[name] = Slider( slider_ax, name, minv, maxv, valinit=init,",
"timer[0] == 0: stop_watch(i, timer) jpg = cv2.imread(row[\"filepath\"], 0) curr = preprocess(jpg, crop,",
"is desired from EXIF tags. sort_key : function, optional By default, dictionaries within",
"pass plt.rc(\"font\", **{\"size\": 8}) plt.rcParams[\"keymap.back\"] = \"left, backspace\" fig = plt.figure() ax =",
"module, the interactive plot() method. A simply initialization could be: Cam(construct_jpg_data()). After filtering",
"noisy, but fast. Parameters ---------- curr : numpy.ndarray Image array, typically from cv2.imread().",
"new events. \"\"\" def __init__(self, jpg_data=False, resp_var=\"count\", thumb_dir=None): \"\"\" Parameters ---------- jpg_data :",
"temp_data: if \"datetime\" in row.keys(): row[\"datetime\"] = dt.strftime( row[\"datetime\"], \"%Y-%m-%d %H:%M:%S\") if \"timedelta\"",
"min(500, self.length)]) ax.set_xlabel(\"Frame\") ax.set_ylabel(\"Response\") plt.yticks(rotation=45) for name in (\"count\", \"threshold\", \"selected\", \"edited\"): self.lines[name]",
"\"%Y%m%dT%H%M%S\" ) else: dt_ISO = str(i) new_name = \"_\".join((dt_ISO, row[\"filename\"])) new_path = os.path.join(directory,",
"scale) gs = gridspec.GridSpec(2, 2, height_ratios=[1, 1.25]) fig = plt.figure() fig.canvas.set_window_title(\"Crop and Clone",
"store, plot, filter, and export image data. Contains the heart of this module,",
"= datetime.time() return time.hour + time.minute / 60 + time.second / 3600 def",
"JSON object with jpg_data, plot_params, and user_edits. \"\"\" temp_data = [ {k: v",
"as f: self.plt_vals = json.loads(next(f)) self.plt_vals[\"resp_thresh\"] = ( self.plt_vals[\"resp_thresh\"] ** (1 / RESP_NUM))",
"not (prev[\"user_edit\"] and curr[\"user_edit\"])) if boo: if not is_neg: lapse = curr[\"td_minutes\"] else:",
"being passed on to frame differencing methods that generate a response metric. This",
"r[\"user_edit\"] for r in self.jpg_data], facecolor=\"#D8BFAA\", alpha=0.5) self.lines[\"selected\"] = ax.fill_between( np.arange(0, self.length) +",
"file path for an initial save.\") cam.save(input_filename()) print(\"→ Use the interactive plot to",
"tuples, optional By default, only Image DateTime is retrieved from EXIF data using",
"func == operator.sub: master_set.add(ind) break else: master_set.add(ind) except IndexError: pass for i in",
"w = b - a, d - c h_or_w = np.array([h, h, w,",
"sort_cols(var_name): if var_name in COL_ORDER: return COL_ORDER.index(var_name) else: return BIG_NUM def input_filename(): while",
"cv2.countNonZero(mask) # Difference, blur (amount changes with ksize), mask and sum. def BLURRED(curr,",
"ksize : int, unused Used in the BLURRED() and CONTOURS() functions, but retained",
"preprocess(jpg, crop, clone) elif i % timer[0] == 0: stop_watch(i, timer) jpg =",
"For simplicity, use generate_clone_tuples() to generate this object. threshold : int, in range(0,",
"alpha=0.5) self.sliders[name].on_changed(on_slide) fig.canvas.mpl_connect(\"key_press_event\", on_key) fig.canvas.mpl_connect(\"key_release_event\", off_key) fig.canvas.mpl_connect(\"button_press_event\", on_click) ax.fill_between( np.arange(0, self.length) + 0.5,",
"jpg_data : list of dictionaries, optional Typically requires the output of process_jpgs(). Can",
"not clone: preprocess = CROP_EQUALIZE else: preprocess = CROP_CLONE_EQUALIZE output = [] timer",
"(0, 0, -1, -1) } COL_ORDER = [ \"old_name\", \"old_path\", \"filename\", \"filepath\", \"shape\",",
"self.user_edits.pop(i, None) self.press = [None, None] update() except TypeError: pass plt.rc(\"font\", **{\"size\": 8})",
"ind = func(i, j) try: row = self.jpg_data[ind] if row[\"new_count\"] < 0: if",
"a .csv file to specified directory. \"\"\" if not os.path.exists(directory): os.makedirs(directory) write_data =",
"# Cam objects don\"t need to have data to initialize. # This way,",
"plot_params, and user_edits. \"\"\" temp_data = [ {k: v for k, v in",
"min(geometry[0, :])) max_y = min(H, max(geometry[0, :])) min_x = max(0, min(geometry[1, :])) max_x",
"from left to right based on increasing accuracy, decreasing speed. crop : tuple",
"if type(processed_data) is not tuple: cam = Cam(processed_data) print(\"→ Please input a file",
"of 100 pixels. Larger numbers decreases sensitivity. Returns ------- list of dictionaries Same",
"function. Default is 11. Must be positive, odd number. min_area : int, unused",
"\"%Y%m%d%H%M%S\") def SORT_BY_DT(row): \"\"\"Default sort for construct_jpg_data(). \"\"\" return row[\"datetime\"] DEFAULT_PARSE = [",
"\"\"\" if i == 0: self.jpg_data[i][kind] = True else: self.jpg_data[i][kind] = True self.jpg_data[i-1][kind]",
"like slicing images as np.arrays. \"\"\" y1, y2, x1, x2 = crop return",
"difference, threshold, 255, cv2.THRESH_BINARY) return cv2.countNonZero(mask) # Difference, blur (amount changes with ksize),",
"\"selected\"), facecolor=\"#F00314\") self.lines[\"count\"] = ax.fill_between( range(self.length), 0, np_counts, facecolor=\"black\") self.lines[\"threshold\"] = ax.axhline( self.plt_vals[\"resp_thresh\"],",
"0.02 self.plt_vals[\"resp_thresh\"] = self.plt_vals[\"ceiling\"] / 2 self.attach_diffs(\"median\", \"med_diff\") for row in self.jpg_data: if",
"False self.buffer = [[None] * 64, [None] * 64] self.recent_folder = os.path.expanduser(\"~\") #",
"\"L\"): tups = generate_clone_tuples(cl_corn, direct) a, b, c, d = tups[1] if not",
"h * w * 0.02 self.plt_vals[\"resp_thresh\"] = self.plt_vals[\"ceiling\"] / 2 self.attach_diffs(\"median\", \"med_diff\") for",
"if not threshold: thresh_init = False if not clone: preprocess = CROP_EQUALIZE else:",
"move): curr = self.jpg_data[i] boo = (not curr[\"selected\"] and prev[\"selected\"] and not (prev[\"user_edit\"]",
"DEFAULT_PARSE. Examine DEFAULT_PARSE as an example parameter to pass to attach_exif(), if more",
"to fill pixels within the clone_to area. Neighboring pixels from \"[A]bove,\" \"[B]elow,\" \"[R]ight,\"",
"clone} print(\"Started processing...\") output = process_jpgs(jpg_data, **process_options) print(\"Done!\") return output # THE MEAT",
"row[\"median\"]*1.05 try: row[\"count\"] = method(curr, prev, threshold, ksize, min_area) except cv2.error as inst:",
"dictionaries Same as incoming jpg_data, but now with the median image tone and",
"gallery. x - Hold and release to INCREASE response value to Inf. z",
"array): array -= 1 else: break stack = [] for n in array:",
"self.plt_vals[\"resp_thresh\"] ** (1 / RESP_NUM)) temp_data = json.loads(next(f)) temp_dict = json.loads(next(f)) for row",
"a contiguous sequence of images. First, images are identified as being selected or",
"h, w, w]) clone_from = clone_to + (h_or_w * mults) return (tuple(clone_to), tuple(clone_from))",
"(a, b), (c, d) = curr.shape[:2], prev.shape[:2] h, w = min(a, c), min(b,",
"\"timedelta\" in row.keys(): row[\"timedelta\"] = row[\"timedelta\"].total_seconds() if \"selected\" in row.keys(): row[\"selected\"] = int(row[\"selected\"])",
"diff = cv2.absdiff(test, image) choose.append((sum(cv2.sumElems(diff)), direct, test)) choose.sort() if choose: _, directs, imgs",
"cv2.absdiff(curr, prev) blurred = cv2.medianBlur(difference, ksize) _, mask = cv2.threshold( blurred, threshold, 255,",
"(self.length * move) - is_neg, move): curr = self.jpg_data[i] boo = (not curr[\"selected\"]",
"row[\"thumbpath\"] = os.path.join(thumb_dir, row[\"filename\"]) else: row[\"thumbpath\"] = row[\"filepath\"] row[\"count\"] = row[self.resp_var] row[\"med_diff\"] =",
"enumerate(hist): tally += count if tally > threshold: return i def generate_clone_tuples(clone_to, fill_from):",
"function. export_dir : str Directory path that is used for exporting thumbnails. long_edge",
": tuple Format is (y1, y2, x1, x2), just like slicing images as",
"not os.path.exists(export_dir): os.makedirs(export_dir) timer = (len(jpg_data) // 10, time.time()) for i, jpg in",
"while True: directory = input(\"DIRPATH > \") if os.path.isdir(directory): return directory else: print(\"Directory",
"median tone of a grayscale image. \"\"\" px_count = image.shape[0] * image.shape[1] hist",
"in enumerate(write_data): if i != 0: f.write(\"\\n\") else: f.write(\",\".join(variables) + \"\\n\") f.write(\",\".join(csv_safe(row[v]) for",
"for graphing, and plot function. class Cam(): \"\"\" A class used to store,",
"\"edited\"): self.lines[name] = ax.axhline() for name, pos, minv, maxv, init, fmt in SLIDER_PARAMS:",
"-BIG_NUM, BIG_NUM, where=[r[\"trans_edit\"] or r[\"user_edit\"] for r in self.jpg_data], facecolor=\"#D8BFAA\", alpha=0.5) self.lines[\"selected\"] =",
"two images for the absolute difference to be taken. prev : numpy.ndarray Like",
"once again, so changes are recorded.\") cam.save(input_filename()) print(\"→ Finally, choose a location for",
"1.25]) fig = plt.figure() fig.canvas.set_window_title(\"Crop and Clone Preview\") ax_crop = fig.add_subplot(gs[0, 0]) ax_clone",
"Minimum contour area to count as a response (movement). Default is an area",
"prev[\"selected\"] = ( prev[\"new_count\"] > self.plt_vals[\"resp_thresh\"] or curr[\"new_count\"] > self.plt_vals[\"resp_thresh\"]) if i ==",
"import KMeans from datetime import datetime as dt, timedelta as td from matplotlib",
"= ( prev[\"new_count\"] > self.plt_vals[\"resp_thresh\"] or curr[\"new_count\"] > self.plt_vals[\"resp_thresh\"]) if i == self.length-1:",
"choose.sort() if choose: _, directs, imgs = list(zip(*choose)) mem.clone_directs = directs mod =",
"cv2 import piexif import numpy as np from sklearn.cluster import KMeans from datetime",
"\"\"\" jpg_paths = find_imgs(dirpath) print(f\"{len(jpg_paths)} images found.\") jpg_data = attach_exif(jpg_paths, parse_tags) jpg_data.sort(key=sort_key) if",
"re- assign DEFAULT_PLOT_PARAMS to this attribute. Methods ------- attach_diffs(var, new_var) Finds the difference",
"in process_jpgs(). \"\"\" clone_to = np.array(clone_to) mults = np.array(DIRECTION_MULTS[fill_from[0].upper()]) a, b, c, d",
"method. Takes two images, then finds their absolute difference. Prior to thresholding, the",
"on [i]ndex. \"\"\" if i == 0: self.jpg_data[i][kind] = True else: self.jpg_data[i][kind] =",
"-1, -1) } COL_ORDER = [ \"old_name\", \"old_path\", \"filename\", \"filepath\", \"shape\", \"datetime\", \"24hr\",",
"enumerate(jpg_data): row = deep_row.copy() if i == 0: jpg = cv2.imread(row[\"filepath\"], 0) h,",
"( self.plt_vals[\"night_mult\"] * row[\"is_night\"]) row[\"new_count\"] = new_count for i, shift in self.user_edits.items(): self.jpg_data[i][\"new_count\"]",
"ax_crop.set_title(\"Crop\") ax_clone.set_title(\"Clone\") ax_mod.set_title(\"Result\") for axe in (ax_crop, ax_clone): axe.set_xticklabels([]) axe.set_yticklabels([]) axe.set_xlim(lo_W, hi_W) axe.set_ylim(hi_H,",
"ksize=11, min_area=100): \"\"\"Slower, but powerful frame differencing method. Takes two images, then finds",
"def process_jpgs( jpg_data, method=CONTOURS, crop=False, clone=False, threshold=False, ksize=11, min_area=100 ): \"\"\"Generates a response",
"object with jpg_data, plot_params, and user_edits. \"\"\" temp_data = [ {k: v for",
"on increasing accuracy, decreasing speed. crop : tuple Format is (y1, y2, x1,",
"count # JPG PROCESSING def process_jpgs( jpg_data, method=CONTOURS, crop=False, clone=False, threshold=False, ksize=11, min_area=100",
"that this parameter is mappable. Returns ------- list of dictionaries Each row contains",
"not. Then, events are lumped based on time since last image (SMOOTH slider",
"of images. First, images are identified as being selected or not. Then, events",
"cv2.imread(row[\"filepath\"], 0) h, w = jpg.shape if not crop: crop = (0, h,",
"gs = gridspec.GridSpec(2, 2, height_ratios=[1, 1.25]) fig = plt.figure() fig.canvas.set_window_title(\"Crop and Clone Preview\")",
"This can be changed if images don\"t have a datetime, but do have",
"need to have data to initialize. # This way, someone can load() older,",
"img = cv2.imread(self.jpg_data[n][\"thumbpath\"]) self.buffer[0] = self.buffer[0][1:] + [n] self.buffer[1] = self.buffer[1][1:] + [img]",
"sorted by their \"Image DateTime\" EXIF tag. This can be changed if images",
"= \"datetime\" in self.jpg_data[0].keys() h, w = jpg_data[0][\"shape\"] self.plt_vals[\"ceiling\"] = h * w",
"- Press to RESET ALL EDITS. v - Press for EQUALIZED image (for",
"\"\"\" output = [] for deep_row in jpg_data: row = deep_row.copy() tags =",
"\"\"\" mem = Mem() mem.crop_tuple = False mem.clone_tuple = False mem.clone_directs = False",
"if clone_RS.active: clone_RS.update() def safe_corners(geometry): min_y = max(0, min(geometry[0, :])) max_y = min(H,",
"could be: Cam(construct_jpg_data()). After filtering images with the plot, save() and export() should",
"-1): is_neg = move < 0 prev = self.jpg_data[-is_neg] for i in range(-is_neg,",
"images from response spike. def image_pano(xdata): i = int(round(xdata)) if i != self.pano_i:",
"unused Used in the BLURRED() and CONTOURS() functions, but retained here to shorten",
"row in temp_data: if \"datetime\" in row.keys(): row[\"datetime\"] = dt.strptime( row[\"datetime\"], \"%Y-%m-%d %H:%M:%S\"",
"self.plt_vals[\"resp_thresh\"], color=\"#14B37D\") fig.canvas.draw_idle() def on_slide(val): for key in self.plt_vals.keys(): if key != \"ceiling\":",
"along paramters to the process_jpgs() function. By default, no options are specified. Make",
"string. Parameters ---------- jpg_data : list of dictionaries Requires that \"filepath\" and \"filename\"",
"older, processed data. if jpg_data: self.jpg_data = list(jpg_data) self.length = len(self.jpg_data) self.dt_present =",
"pano.shape cv2.namedWindow(\"Gallery\", cv2.WINDOW_NORMAL) cv2.imshow(\"Gallery\", cv2.resize(pano, (w // 2, h // 2))) cv2.waitKey(1) def",
"px_count / 2 for i, count in enumerate(hist): tally += count if tally",
"Path to an image-containing directory. img_type : tuple, optional By default, finds JPG",
"\"old_name\", \"old_path\", \"filename\", \"filepath\", \"shape\", \"datetime\", \"24hr\", \"is_night\", \"timedelta\", \"td_minutes\", \"median\", \"med_diff\", \"count\",",
"Useful for cloning out timestamps, aids in histogram equalization. Parameters ---------- clone_to :",
"os.makedirs(directory) write_data = [] for i, row in enumerate(self.jpg_data): write_row = row.copy() if",
"DIFFERENCING METHODS # Bare-bones. Take difference, threshold, and sum the mask. def SIMPLE(curr,",
"processed_data = process_jpgs(jpg_data, crop=crop, clone=clone) if type(processed_data) is not tuple: cam = Cam(processed_data)",
"f.write(\",\".join(csv_safe(row[v]) for v in variables)) else: raise ValueError(\"No images selected for export.\") def",
"\"pixels\", \"interactive\": True } # GENERAL FUNCTIONS class Mem(): def __init__(self): pass def",
"a .sav file, the Cam() object is now identical to the last. \"\"\"",
": datetime.timedelta Timedelta object to format. fmt : str Contains format calls to",
"i == 0: jpg = cv2.imread(row[\"filepath\"], 0) h, w = jpg.shape if not",
"row[\"datetime\"] = dt.strftime( row[\"datetime\"], \"%Y-%m-%d %H:%M:%S\") if \"timedelta\" in row.keys(): row[\"timedelta\"] = row[\"timedelta\"].total_seconds()",
"not None and event.key in \"zx,\": i = int(round(event.xdata)) low, high = sorted((self.press[1],",
"erelease): x1, y1 = eclick.xdata, eclick.ydata x2, y2 = erelease.xdata, erelease.ydata cr_corn, cr_ig",
"mem.crop_tuple = cr_corn y1, y2, x1, x2 = cr_corn mod = mod[y1:y2, x1:x2]",
"what is inputted, but includes variables denoting selection, edits, event, etc. plot_params :",
"to shorten the process_jpgs() function. \"\"\" difference = cv2.absdiff(curr, prev) blurred = cv2.medianBlur(difference,",
"function. class Cam(): \"\"\" A class used to store, plot, filter, and export",
"elif i % timer[0] == 0: stop_watch(i, timer) jpg = cv2.imread(row[\"filepath\"], 0) curr",
"False new_count = row[\"count\"] if row[\"med_diff\"] > self.plt_vals[\"trans_thresh\"]: new_count = 0 self.mark_edits(i, \"trans_edit\")",
"set() for i, row in enumerate(self.jpg_data): if row[\"selected\"]: for func in (operator.add, operator.sub):",
"rint(w * scale) new_h = rint(h * scale) return cv2.resize(im, (new_w, new_h)) def",
"not None: image_pano(event.xdata) def on_key(event): if event.xdata is not None: if self.press[0] is",
"image. Parameters ---------- image : numpy.ndarray Image array, typically from cv2.imread(). crop :",
"threshold, and sum the mask. def SIMPLE(curr, prev, threshold, ksize=None, min_area=None): \"\"\"Most basic",
"0) return tuple(map( lambda x: int(round(x)), (min_y, max_y, min_x, max_x))), ignore def RS_event(eclick,",
"0.5, -BIG_NUM, BIG_NUM, where=[r[\"trans_edit\"] or r[\"user_edit\"] for r in self.jpg_data], facecolor=\"#D8BFAA\", alpha=0.5) self.lines[\"selected\"]",
"(1 / RESP_NUM) SLIDER_PARAMS = [ (\"RESP\", 0.08, 0, 100, mod, \"%.2e\"), (\"TRANS\",",
"return row[\"datetime\"] DEFAULT_PARSE = [ ((\"0th\", 306), \"datetime\", PARSE_DT) ] DEFAULT_PLOT_PARAMS = {",
"export_dir, long_edge=1024): \"\"\"Formats a timedelta object as a string. Parameters ---------- jpg_data :",
"image types, but can be changed if camera exports a different filetype. Returns",
"default, only Image DateTime is retrieved from EXIF data using DEFAULT_PARSE. Examine DEFAULT_PARSE",
"to select images for export. QUICK GUIDE: c - Hold to VIEW IMAGES",
"> self.plt_vals[\"trans_thresh\"]: new_count = 0 self.mark_edits(i, \"trans_edit\") if self.dt_present: new_count *= 1 +",
"plot, filter, and export image data. Contains the heart of this module, the",
"optional A key found in jpg_data, typically the \"count\" variable is used as",
"files in os.walk(dirpath): if \"_selected\" not in dir_: found = ( f for",
"x in str(raw) if x in string.digits) return dt.strptime(str_, \"%Y%m%d%H%M%S\") def SORT_BY_DT(row): \"\"\"Default",
"\"\"\"Converts datetime.datetime type to 24 hour float type. \"\"\" time = datetime.time() return",
"directs = crop_clone_preview( cv2.imread(jpg_data[len(jpg_data) // 2][\"filepath\"])) clone = (generate_clone_tuples(clone_to, directs[0]) if clone_to else",
"median image tone and a count variable, which respresents how many pixels have",
"keys, which is easily provided by find_imgs() prior to this function. export_dir :",
"= dt.strptime( row[\"datetime\"], \"%Y-%m-%d %H:%M:%S\" ) self.dt_present = True else: self.dt_present = False",
"file. update_counts() Updates jpg_data attribute with new counts. update_events() Updates jpg_data attribute with",
"self.dt_present = True else: self.dt_present = False if \"timedelta\" in row.keys(): try: row[\"timedelta\"]",
"are filtered out based on slider. Counts taken at with nighttime are multiplied",
"BIG_NUM, where=extract_var(self.jpg_data, \"selected\"), facecolor=\"#F00314\") self.lines[\"count\"] = ax.fill_between( range(self.length), 0, np_counts, facecolor=\"black\") self.lines[\"threshold\"] =",
"the format ((clone_to), (clone_from)). For simplicity, use generate_clone_tuples() to generate this object. threshold",
"positive, odd number. min_area : int Minimum contour area to count as a",
"thresholding. \"\"\" if not threshold: thresh_init = False if not clone: preprocess =",
"save(filename) Dumps a JSON object as a .sav file. update_counts() Updates jpg_data attribute",
"dirpath : str Path to an image-containing directory. img_type : tuple, optional By",
"Cam(). Parameters ---------- dirpath : str Path to an image-containing directory. parse_tags :",
"attach_exif(jpg_paths, parse_tags) jpg_data.sort(key=sort_key) if process_options == {}: print(\"Crop and clone image as desired.\")",
"temp_data: if \"datetime\" in row.keys(): row[\"datetime\"] = dt.strptime( row[\"datetime\"], \"%Y-%m-%d %H:%M:%S\" ) self.dt_present",
"name, pos, minv, maxv, init, fmt in SLIDER_PARAMS: slider_ax = fig.add_axes([0.125, pos, 0.8,",
"REMOVE EDITS. . - Press to RESET ALL EDITS. v - Press for",
"0 for n in array): array += 1 elif any(n >= self.length for",
"\"\"\" for i, row in enumerate(self.jpg_data): row[\"user_edit\"] = False row[\"trans_edit\"] = False new_count",
"self.toggle: gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img = cv2.cv2.equalizeHist(gray) stack.append(img) min_y = min(img.shape[0] for",
"but fast. Parameters ---------- curr : numpy.ndarray Image array, typically from cv2.imread(). One",
"\"smooth_time\": 1, \"night_mult\": 0 } DIRECTION_MULTS = { \"A\": (-1, -1, 0, 0),",
"-BIG_NUM, BIG_NUM, where=extract_var(self.jpg_data, \"selected\"), facecolor=\"#F00314\") self.lines[\"count\"] = ax.fill_between( range(self.length), 0, np_counts, facecolor=\"black\") self.lines[\"threshold\"]",
"with jpg_data, plot_params, and user_edits. \"\"\" temp_data = [ {k: v for k,",
"EXIF data. Useful for cloning out timestamps, aids in histogram equalization. Parameters ----------",
"passed on to frame differencing methods that generate a response metric. This is",
"= ax.fill_between( np.arange(0, self.length) + 0.5, -BIG_NUM, BIG_NUM, where=[r[\"trans_edit\"] or r[\"user_edit\"] for r",
"= size / h new_w = rint(w * scale) new_h = rint(h *",
"if choose: _, directs, imgs = list(zip(*choose)) mem.clone_directs = directs mod = imgs[0]",
"255, cv2.THRESH_BINARY) contours, _ = cv2.findContours( mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2:] count = 0 for",
"interactive plot() method. A simply initialization could be: Cam(construct_jpg_data()). After filtering images with",
"by find_imgs() prior to this function. export_dir : str Directory path that is",
"for img in stack]) h, w, *_ = pano.shape cv2.namedWindow(\"Gallery\", cv2.WINDOW_NORMAL) cv2.imshow(\"Gallery\", cv2.resize(pano,",
"elif event.key == \",\": for i in lo_to_hi: self.user_edits.pop(i, None) self.press = [None,",
"DateTime is retrieved from EXIF data using DEFAULT_PARSE. Examine DEFAULT_PARSE as an example",
"def CROPPER(image, crop): \"\"\"Returns a cropped image. Parameters ---------- image : numpy.ndarray Image",
"64, [None] * 64] self.recent_folder = os.path.expanduser(\"~\") # Cam objects don\"t need to",
"> min_area: count += area return count # JPG PROCESSING def process_jpgs( jpg_data,",
"CROP_CLONE_EQUALIZE output = [] timer = (len(jpg_data) // 10, time.time()) for i, deep_row",
"Returns ------- list of dictionaries Same as jpg_data, but now with desired EXIF",
"in variables)) else: raise ValueError(\"No images selected for export.\") def attach_diffs(self, var, new_var):",
"COL_ORDER: return COL_ORDER.index(var_name) else: return BIG_NUM def input_filename(): while True: filename = input(\"FILEPATH",
"have been edited. plot() Interactive plot used to select images for export. save(filename)",
"i + 2)) while True: if any(n < 0 for n in array):",
"way, someone can load() older, processed data. if jpg_data: self.jpg_data = list(jpg_data) self.length",
"fill pixels within the clone_to area. Neighboring pixels from \"[A]bove,\" \"[B]elow,\" \"[R]ight,\" and",
"preprocess = CROP_CLONE_EQUALIZE output = [] timer = (len(jpg_data) // 10, time.time()) for",
"if thumb_dir is not None: row[\"thumbpath\"] = os.path.join(thumb_dir, row[\"filename\"]) else: row[\"thumbpath\"] = row[\"filepath\"]",
"k, v in temp_dict.items()} def export(self, directory): \"\"\"Exports selected images and a .csv",
"or min_x > W or max_x < 0) return tuple(map( lambda x: int(round(x)),",
"all files ending in img_type. Parameters ---------- dirpath : str Path to an",
"generate_clone_tuples(clone_to, directs[0]) if clone_to else False print(\"→ Images are being processed.\") processed_data =",
"dt, timedelta as td from matplotlib import pyplot as plt from matplotlib.widgets import",
"8}) plt.rcParams[\"keymap.back\"] = \"left, backspace\" fig = plt.figure() ax = fig.add_subplot(111) fig.canvas.set_window_title(\"Response Filtering\")",
"def strfdelta(tdelta, fmt): \"\"\"Formats a timedelta object as a string. Parameters ---------- tdelta",
"= attach_exif(jpg_paths, parse_tags) jpg_data.sort(key=sort_key) if process_options == {}: print(\"Crop and clone image as",
"= (0 - H // scale), (H + H // scale) gs =",
"\"\"\" difference = cv2.absdiff(curr, prev) blurred = cv2.medianBlur(difference, ksize) _, mask = cv2.threshold(",
"\"datetime\" in row.keys(): row[\"datetime\"] = dt.strftime( row[\"datetime\"], \"%Y-%m-%d %H:%M:%S\") if \"timedelta\" in row.keys():",
"from \"[A]bove,\" \"[B]elow,\" \"[R]ight,\" and \"[L]eft\" are used for filling the area. Returns",
"objects don\"t need to have data to initialize. # This way, someone can",
"high = sorted((self.press[1], i)) lo_to_hi = range(max(0, low), min(self.length, high+1)) if event.key in",
"crop_RS.active: crop_RS.update() if clone_RS.active: clone_RS.update() def safe_corners(geometry): min_y = max(0, min(geometry[0, :])) max_y",
"rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) H, W, *_ = image.shape scale = 10 lo_W,",
"ax_mod.set_title(\"Result\") for axe in (ax_crop, ax_clone): axe.set_xticklabels([]) axe.set_yticklabels([]) axe.set_xlim(lo_W, hi_W) axe.set_ylim(hi_H, lo_H) ax_crop.imshow(rgb)",
"cv2.threshold() function. ksize : int Parameter to be passed to the cv2.medianBlur() function.",
"cv2.cvtColor(mod, cv2.COLOR_BGR2RGB) ax_mod.imshow(mod) fig.canvas.draw_idle() rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) H, W, *_ = image.shape",
"pixels. Larger numbers decreases sensitivity. Returns ------- list of dictionaries Same as incoming",
"// scale) gs = gridspec.GridSpec(2, 2, height_ratios=[1, 1.25]) fig = plt.figure() fig.canvas.set_window_title(\"Crop and",
"'\"' + string + '\"' if \",\" in string else string def to_24_hour(datetime):",
"i == self.length-1: curr[\"selected\"] = ( curr[\"new_count\"] > self.plt_vals[\"resp_thresh\"]) prev = curr if",
"next two images from response spike. def image_pano(xdata): i = int(round(xdata)) if i",
"\"\"\"Performs all necessary steps to make jpg_data feedable to Cam(). Parameters ---------- dirpath",
"thumb_dir : str, optional If the interactive plot is laggy, use resize_with_exif() on",
"object. threshold : int, in range(0, 256) Parameter to be passed to the",
"* scale) return cv2.resize(im, (new_w, new_h)) def generate_thumbnails(jpg_data, export_dir, long_edge=1024): \"\"\"Formats a timedelta",
"key in self.plt_vals.keys(): if key != \"ceiling\": slider_key = key[:key.find(\"_\")].upper() if key ==",
"EDITS. . - Press to RESET ALL EDITS. v - Press for EQUALIZED",
"image is blurred to reduce noise. After thresholding, contours are drawn around the",
"W or max_x < 0) return tuple(map( lambda x: int(round(x)), (min_y, max_y, min_x,",
"(y1, y2, x1, x2), just like slicing images as np.arrays. \"\"\" y1, y2,",
"sensitivity. Returns ------- list of dictionaries Same as incoming jpg_data, but now with",
"ksize, min_area) except cv2.error as inst: if \"(-209:Sizes\" in str(inst): (a, b), (c,",
"(for dark images). \"\"\" try: self.jpg_data except AttributeError as inst: raise inst mod",
"self.lines[name] = ax.axhline() for name, pos, minv, maxv, init, fmt in SLIDER_PARAMS: slider_ax",
"directs[0]) if clone_to else False print(\"→ Images are being processed.\") processed_data = process_jpgs(jpg_data,",
"generate_clone_tuples() to generate this object. \"\"\" (a, b, c, d), (e, f, g,",
"= os.path.join(export_dir, jpg[\"filename\"]) im = cv2.imread(from_path) resized = resize_long_edge(im, long_edge) cv2.imwrite(to_path, resized) piexif.transplant(from_path,",
"color=\"#003459\", alpha=0.5) self.sliders[name].on_changed(on_slide) fig.canvas.mpl_connect(\"key_press_event\", on_key) fig.canvas.mpl_connect(\"key_release_event\", off_key) fig.canvas.mpl_connect(\"button_press_event\", on_click) ax.fill_between( np.arange(0, self.length) +",
"histogram equalization. Parameters ---------- clone_to : tuple Format is (y1, y2, x1, x2),",
"= row[self.resp_var] row[\"med_diff\"] = abs(row[\"med_diff\"]) row[\"selected\"] = False row[\"user_edit\"] = False row[\"trans_edit\"] =",
"by find_imgs() prior to this function. method : function, {SIMPLE, BLURRED, COUNTOURS} Determines",
"return image[y1:y2, x1:x2] def CROP_EQUALIZE(image, crop, clone=None): \"\"\"Returns a cropped image with an",
"dt.strftime( row[\"datetime\"], \"%Y-%m-%d %H:%M:%S\") if \"timedelta\" in row.keys(): row[\"timedelta\"] = row[\"timedelta\"].total_seconds() if \"selected\"",
"i = int(round(xdata)) if i != self.pano_i: self.pano_i = i array = np.array(range(i",
"hist = cv2.calcHist([image], [0], None, [256], [0, 256]) tally = 0 threshold =",
"(a, b, c, d), (e, f, g, h) = clone image[a:b, c:d] =",
"be omitted if a empty Cam() object is desired for a load() method",
"denoting selection, edits, event, etc. plot_params : dictionary Parameters used in the plot()",
"counts. update_events() Updates jpg_data attribute with new events. \"\"\" def __init__(self, jpg_data=False, resp_var=\"count\",",
"self.sliders[name] = Slider( slider_ax, name, minv, maxv, valinit=init, valfmt=fmt, color=\"#003459\", alpha=0.5) self.sliders[name].on_changed(on_slide) fig.canvas.mpl_connect(\"key_press_event\",",
"0, 0), \"R\": (0, 0, 1, 1), \"L\": (0, 0, -1, -1) }",
"(len(jpg_data) // 10, time.time()) for i, deep_row in enumerate(jpg_data): row = deep_row.copy() if",
"x1, x2), just like slicing images as np.arrays. clone : pair of tuples,",
"resulting white pixels. If the contours are above the min_area parameter, they are",
"area of 100 pixels. Larger numbers decreases sensitivity. \"\"\" difference = cv2.absdiff(curr, prev)",
"def SORT_BY_DT(row): \"\"\"Default sort for construct_jpg_data(). \"\"\" return row[\"datetime\"] DEFAULT_PARSE = [ ((\"0th\",",
"to label as edited based on [i]ndex. \"\"\" if i == 0: self.jpg_data[i][kind]",
"through jpg_data, reading filepaths and attaching EXIF data. Useful for cloning out timestamps,",
"< 0 or min_x > W or max_x < 0) return tuple(map( lambda",
"ax.set_ylim([0, self.plt_vals[\"ceiling\"]]) ax.set_xlim([0, min(500, self.length)]) ax.set_xlabel(\"Frame\") ax.set_ylabel(\"Response\") plt.yticks(rotation=45) for name in (\"count\", \"threshold\",",
"curr[\"selected\"] = ( curr[\"new_count\"] > self.plt_vals[\"resp_thresh\"]) prev = curr if self.dt_present: for move",
"boo = (not curr[\"selected\"] and prev[\"selected\"] and not (prev[\"user_edit\"] and curr[\"user_edit\"])) if boo:",
"use \"generate_clone_tuples(clone_to, directs[0])\" to get the clone parameter, or any other direction in",
"to_24_hour(row[\"datetime\"]) row[\"td_minutes\"] = round( row[\"timedelta\"].total_seconds() / 60, 2) day_hr = extract_var(self.jpg_data, \"24hr\") #",
"methods that generate a response metric. This is the last step before the",
"to night transitions are filtered out based on slider. Counts taken at with",
"edge of the image. Smaller sizes speed up performance, but decrease acuity. \"\"\"",
"if i == self.length-1: curr[\"selected\"] = ( curr[\"new_count\"] > self.plt_vals[\"resp_thresh\"]) prev = curr",
"= True def update_counts(self): \"\"\"Updates jpg_data with new counts (response metric). Variable new_count",
"equalization. Parameters ---------- clone_to : tuple Format is (y1, y2, x1, x2), just",
"processing...\") output = process_jpgs(jpg_data, **process_options) print(\"Done!\") return output # THE MEAT AND POTATOES",
"like to make it?\") answer = input(\"Y / N > \") if answer.lower()",
"output.append(row) return output def hist_median(image): \"\"\"Quickly finds the median tone of a grayscale",
"(\"RESP\", 0.08, 0, 100, mod, \"%.2e\"), (\"TRANS\", 0.06, 0, 120, self.plt_vals[\"trans_thresh\"], \"%.1f\"), (\"SMOOTH\",",
"be resized to 1024 pixels on the long edge of the image. Smaller",
"\",\": for i in lo_to_hi: self.user_edits.pop(i, None) self.press = [None, None] update() except",
"EXIF tags. sort_key : function, optional By default, dictionaries within the jpg_data list",
"\"\"\"Finds the difference between the current and previous variable. Requires a list of",
"slicing images as np.arrays. clone : pair of tuples Matches the format ((clone_to),",
"enumerate(self.jpg_data): write_row = row.copy() if row[\"selected\"]: if self.dt_present: dt_ISO = dt.strftime( row[\"datetime\"], \"%Y%m%dT%H%M%S\"",
"data] def stop_watch(i, timer): progress = (i * 10) // timer[0] elapsed =",
"attach_exif(jpg_data, parse_tags=DEFAULT_PARSE): \"\"\"Loops through jpg_data, reading filepaths and attaching EXIF data. Parameters ----------",
"last image (SMOOTH slider value). \"\"\" self.pano_i = 0 prev = self.jpg_data[0] for",
"[ (\"RESP\", 0.08, 0, 100, mod, \"%.2e\"), (\"TRANS\", 0.06, 0, 120, self.plt_vals[\"trans_thresh\"], \"%.1f\"),",
"= input(\"Y / N > \") if answer.lower() in (\"y\", \"yes\"): os.makedirs(directory) return",
"Take difference, threshold, and sum the mask. def SIMPLE(curr, prev, threshold, ksize=None, min_area=None):",
"Dumps a JSON object as a .sav file. update_counts() Updates jpg_data attribute with",
"True } # GENERAL FUNCTIONS class Mem(): def __init__(self): pass def rint(n): return",
"= {i: self.press[0] for i in lo_to_hi} self.user_edits = {**self.user_edits, **new_edits} elif event.key",
"print(\"Started processing...\") output = process_jpgs(jpg_data, **process_options) print(\"Done!\") return output # THE MEAT AND",
"cropped image, with specified cloning and equalization. Parameters ---------- image : numpy.ndarray Image",
"is blurred to reduce noise. After thresholding, contours are drawn around the resulting",
"be changed if images don\"t have a datetime, but do have a variable",
"self.plt_vals = DEFAULT_PLOT_PARAMS self.lines = {} self.sliders = {} self.user_edits = {} self.press",
"difference to be taken. prev : numpy.ndarray Like curr. The second image to",
"data. if jpg_data: self.jpg_data = list(jpg_data) self.length = len(self.jpg_data) self.dt_present = \"datetime\" in",
"tag), var, anon in parse_tags: row[var] = anon(tags[key][tag]) output.append(row) return output def hist_median(image):",
"cv2.cvtColor(image, cv2.COLOR_BGR2RGB) H, W, *_ = image.shape scale = 10 lo_W, hi_W =",
"return cv2.equalizeHist(image) def crop_clone_preview(image): \"\"\"Interactive viewer to quickly get crop and clone parameters.",
"(not curr[\"selected\"] and prev[\"selected\"] and not (prev[\"user_edit\"] and curr[\"user_edit\"])) if boo: if not",
"specified directory. \"\"\" if not os.path.exists(directory): os.makedirs(directory) write_data = [] for i, row",
"\"zx\": new_edits = {i: self.press[0] for i in lo_to_hi} self.user_edits = {**self.user_edits, **new_edits}",
"scale) new_h = rint(h * scale) return cv2.resize(im, (new_w, new_h)) def generate_thumbnails(jpg_data, export_dir,",
"Parameters ---------- clone_to : tuple Format is (y1, y2, x1, x2), just like",
"else: return BIG_NUM def input_filename(): while True: filename = input(\"FILEPATH > \") if",
"blurred to reduce noise. After thresholding, contours are drawn around the resulting white",
"Image DateTime is retrieved from EXIF data using DEFAULT_PARSE. Examine DEFAULT_PARSE as an",
"Parameter to be passed to the cv2.medianBlur() function. Default is 11. Must be",
"str Path to an image-containing directory. img_type : tuple, optional By default, finds",
"output = process_jpgs(jpg_data, **process_options) print(\"Done!\") return output # THE MEAT AND POTATOES #",
"Right justified 2 spaces, filled with zeros. \"\"\" d = {\"days\": tdelta.days} d[\"hours\"],",
"incoming jpg_data, but now with the median image tone and a count variable,",
"process_jpgs() function. \"\"\" difference = cv2.absdiff(curr, prev) _, mask = cv2.threshold( difference, threshold,",
"edits are applied. \"\"\" for i, row in enumerate(self.jpg_data): row[\"user_edit\"] = False row[\"trans_edit\"]",
"= [ ((\"0th\", 306), \"datetime\", PARSE_DT) ] DEFAULT_PLOT_PARAMS = { \"ceiling\": 40000, \"resp_thresh\":",
"EXIF \"Image DateTime\" tag. \"\"\" str_ = ''.join(x for x in str(raw) if",
"def input_directory(): while True: directory = input(\"DIRPATH > \") if os.path.isdir(directory): return directory",
"a directory path with camera-trapping images.\") jpg_paths = find_imgs(input_directory()) jpg_data = attach_exif(jpg_paths) jpg_data.sort(key=lambda",
"1, 0, 0), \"R\": (0, 0, 1, 1), \"L\": (0, 0, -1, -1)",
"\"r\") as f: self.plt_vals = json.loads(next(f)) self.plt_vals[\"resp_thresh\"] = ( self.plt_vals[\"resp_thresh\"] ** (1 /",
"Neighboring pixels from \"[A]bove,\" \"[B]elow,\" \"[R]ight,\" and \"[L]eft\" are used for filling the",
"to select images for export. save(filename) Dumps a JSON object as a .sav",
"Parameters ---------- curr : numpy.ndarray Image array, typically from cv2.imread(). One of the",
"== \"__main__\": print(\"→ Please input a directory path with camera-trapping images.\") jpg_paths =",
"is (crop, clone_to, clone_directs). The crop_tuple variable can be fed directly into process_jpgs().",
"new_count = row[\"count\"] if row[\"med_diff\"] > self.plt_vals[\"trans_thresh\"]: new_count = 0 self.mark_edits(i, \"trans_edit\") if",
"used for filling the area. Returns ------- pair of tuples Matches the format",
"= image.shape[0] * image.shape[1] hist = cv2.calcHist([image], [0], None, [256], [0, 256]) tally",
"2) day_hr = extract_var(self.jpg_data, \"24hr\") # meds = extract_var(self.jpg_data, \"median\") X = np.array(day_hr).reshape(-1,",
"mask = cv2.threshold( blurred, threshold, 255, cv2.THRESH_BINARY) return cv2.countNonZero(mask) # Like BLURRED, but",
"f, g, h) = tups test[a:b, c:d] = test[e:f, g:h] diff = cv2.absdiff(test,",
"filename elif filename: return filename def input_directory(): while True: directory = input(\"DIRPATH >",
"= row.copy() if row[\"selected\"]: if self.dt_present: dt_ISO = dt.strftime( row[\"datetime\"], \"%Y%m%dT%H%M%S\" ) else:",
"= ( curr[\"new_count\"] > self.plt_vals[\"resp_thresh\"]) prev = curr if self.dt_present: for move in",
"** (1 / RESP_NUM) SLIDER_PARAMS = [ (\"RESP\", 0.08, 0, 100, mod, \"%.2e\"),",
"clone=False, threshold=False, ksize=11, min_area=100 ): \"\"\"Generates a response (movement) metric between images. Works",
"in array): array += 1 elif any(n >= self.length for n in array):",
"is not tuple: cam = Cam(processed_data) print(\"→ Please input a file path for",
"image) choose.append((sum(cv2.sumElems(diff)), direct, test)) choose.sort() if choose: _, directs, imgs = list(zip(*choose)) mem.clone_directs",
"w = jpg.shape if not crop: crop = (0, h, 0, w) prev",
"y2, x1, x2), just like slicing images as np.arrays. \"\"\" y1, y2, x1,",
"the output of process_jpgs(). Can be omitted if a empty Cam() object is",
"= self.plt_vals[\"ceiling\"] / 2 self.attach_diffs(\"median\", \"med_diff\") for row in self.jpg_data: if thumb_dir is",
"The second image to be differenced. threshold : int, in range(0, 256) Parameter",
"self.jpg_data[i][\"selected\"] = True def plot(self): \"\"\"Interactive plot used to select images for export.",
"in temp_data: if \"datetime\" in row.keys(): row[\"datetime\"] = dt.strptime( row[\"datetime\"], \"%Y-%m-%d %H:%M:%S\" )",
"if event.dblclick and event.xdata is not None: image_pano(event.xdata) def on_key(event): if event.xdata is",
"the frame differencing method to use. Ordered from left to right based on",
"------- list of dictionaries Each row contains everything that is needed to feed",
"Gallery tab. \"\"\" self.resp_var = resp_var self.plt_vals = DEFAULT_PLOT_PARAMS self.lines = {} self.sliders",
"the interactive plot to select images for export.\") help(Cam.plot) cam.plot() print(\"→ Save once",
"area = cv2.contourArea(cnt) if area > min_area: count += area return count #",
"os.path.exists(directory): os.makedirs(directory) write_data = [] for i, row in enumerate(self.jpg_data): write_row = row.copy()",
"in enumerate(self.jpg_data): prev[\"selected\"] = ( prev[\"new_count\"] > self.plt_vals[\"resp_thresh\"] or curr[\"new_count\"] > self.plt_vals[\"resp_thresh\"]) if",
"row.keys(): row[\"timedelta\"] = row[\"timedelta\"].total_seconds() if \"selected\" in row.keys(): row[\"selected\"] = int(row[\"selected\"]) with open(filename,",
"new directory path.\") def csv_safe(obj): \"\"\"Puts quotes around strings with commas in them.",
"\"%Y-%m-%d %H:%M:%S\" ) self.dt_present = True else: self.dt_present = False if \"timedelta\" in",
"fig = plt.figure() fig.canvas.set_window_title(\"Crop and Clone Preview\") ax_crop = fig.add_subplot(gs[0, 0]) ax_clone =",
"blur (amount changes with ksize), mask and sum. def BLURRED(curr, prev, threshold, ksize=11,",
"with new counts. update_events() Updates jpg_data attribute with new events. \"\"\" def __init__(self,",
"= \"left, backspace\" fig = plt.figure() ax = fig.add_subplot(111) fig.canvas.set_window_title(\"Response Filtering\") fig.subplots_adjust(0.07, 0.18,",
"row.copy() if row[\"selected\"]: if self.dt_present: dt_ISO = dt.strftime( row[\"datetime\"], \"%Y%m%dT%H%M%S\" ) else: dt_ISO",
"\"\"\" difference = cv2.absdiff(curr, prev) _, mask = cv2.threshold( difference, threshold, 255, cv2.THRESH_BINARY)",
"ax_crop, RS_event, **RS_PARAMS) clone_RS = RectangleSelector( ax_clone, RS_event, **RS_PARAMS) ax_crop.set_title(\"Crop\") ax_clone.set_title(\"Clone\") ax_mod.set_title(\"Result\") for",
"or max_y < 0 or min_x > W or max_x < 0) return",
"piexif import numpy as np from sklearn.cluster import KMeans from datetime import datetime",
"includes variables denoting selection, edits, event, etc. plot_params : dictionary Parameters used in",
"to be differenced. threshold : int, in range(0, 256) Parameter to be passed",
"pos, minv, maxv, init, fmt in SLIDER_PARAMS: slider_ax = fig.add_axes([0.125, pos, 0.8, 0.02])",
"and specify the export directory here. These smaller images will be displayed in",
"numpy.ndarray Like curr. The second image to be differenced. threshold : int, in",
"Parameters ---------- image : numpy.ndarray Image array, typically from cv2.imread(). Returns ------- tuple",
"the clone parameter, or any other direction in the directs list (all have",
"[0, 256]) tally = 0 threshold = px_count / 2 for i, count",
"self.length = len(self.jpg_data) self.dt_present = \"datetime\" in self.jpg_data[0].keys() h, w = jpg_data[0][\"shape\"] self.plt_vals[\"ceiling\"]",
"to this attribute. Methods ------- attach_diffs(var, new_var) Finds the difference between the current",
"x in data] def stop_watch(i, timer): progress = (i * 10) // timer[0]",
"list (all have been checked for bounds, unlike generate_clone_tuples). \"\"\" mem = Mem()",
"with open(filename, \"r\") as f: self.plt_vals = json.loads(next(f)) self.plt_vals[\"resp_thresh\"] = ( self.plt_vals[\"resp_thresh\"] **",
"== \"v\": self.toggle = not self.toggle image_pano(event.xdata) elif event.key == \".\": self.user_edits =",
"plt.yticks(rotation=45) for name in (\"count\", \"threshold\", \"selected\", \"edited\"): self.lines[name] = ax.axhline() for name,",
"metric. This is the last step before the jpg_data list can be fed",
"format calls to days, hours, minutes, and seconds. Returns ------- str Right justified",
"cropping, cloning, and histogram equalization on images read from jpg_data filepaths before being",
"cv2.resize(im, (new_w, new_h)) def generate_thumbnails(jpg_data, export_dir, long_edge=1024): \"\"\"Formats a timedelta object as a",
"sure that this parameter is mappable. Returns ------- list of dictionaries Each row",
"if event.xdata is not None and event.key in \"zx,\": i = int(round(event.xdata)) low,",
"22}, {\"name\": \"Eve\", \"age\": 7}] >>> extract_var(data=foo, var=\"name\") [\"Shane\", \"Eve\"] \"\"\" return [x[var]",
"x1, x2), just like slicing images as np.arrays. fill_from : {\"A\", \"B\", \"R\",",
"frame differencing method to use. Ordered from left to right based on increasing",
"directory path.\") def csv_safe(obj): \"\"\"Puts quotes around strings with commas in them. \"\"\"",
"\"datetime\", \"24hr\", \"is_night\", \"timedelta\", \"td_minutes\", \"median\", \"med_diff\", \"count\", \"new_count\", \"selected\", \"user_edit\", \"trans_edit\" ]",
"exports a different filetype. Returns ------- list of dictionaries Contains filenames and filepaths.",
"H or c < 0 or d > W): trials.append((tups, direct)) choose =",
"Default is 11. Must be positive, odd number. min_area : int Minimum contour",
"np.arrays. \"\"\" y1, y2, x1, x2 = crop return image[y1:y2, x1:x2] def CROP_EQUALIZE(image,",
"of dictionaries. \"\"\" prev = self.jpg_data[0][var] for row in self.jpg_data: curr = row[var]",
"cv2.resize(pano, (w // 2, h // 2))) cv2.waitKey(1) def on_click(event): if event.dblclick and",
"new_name write_row[\"filepath\"] = new_path write_row[\"old_name\"] = row[\"filename\"] write_row[\"old_path\"] = row[\"filepath\"] shutil.copy2(row[\"filepath\"], new_path) write_data.append(write_row)",
"slider_ax = fig.add_axes([0.125, pos, 0.8, 0.02]) self.sliders[name] = Slider( slider_ax, name, minv, maxv,",
"range(max(0, low), min(self.length, high+1)) if event.key in \"zx\": new_edits = {i: self.press[0] for",
"clone : pair of tuples, optional Matches the format ((clone_to), (clone_from)). For simplicity,",
"between the current and previous variable. Requires a list of dictionaries. \"\"\" prev",
"crop, clone) elif i % timer[0] == 0: stop_watch(i, timer) jpg = cv2.imread(row[\"filepath\"],",
"= 0 prev = self.jpg_data[0] for i, curr in enumerate(self.jpg_data): prev[\"selected\"] = (",
"/ 2 self.attach_diffs(\"median\", \"med_diff\") for row in self.jpg_data: if thumb_dir is not None:",
"than others. Parameters ---------- curr : numpy.ndarray Image array, typically from cv2.imread(). One",
"return cv2.countNonZero(mask) # Difference, blur (amount changes with ksize), mask and sum. def",
"export image data. Contains the heart of this module, the interactive plot() method.",
"Typically requires the output of process_jpgs(). Can be omitted if a empty Cam()",
"\"timedelta\" in row.keys(): try: row[\"timedelta\"] = td(seconds=row[\"timedelta\"]) except AttributeError: pass if \"selected\" in",
"scale) lo_H, hi_H = (0 - H // scale), (H + H //",
"< 0 for n in array): array += 1 elif any(n >= self.length",
"{\"name\": \"Eve\", \"age\": 7}] >>> extract_var(data=foo, var=\"name\") [\"Shane\", \"Eve\"] \"\"\" return [x[var] for",
"from cv2.imread(). crop : tuple Format is (y1, y2, x1, x2), just like",
"plot() Interactive plot used to select images for export. save(filename) Dumps a JSON",
"td(seconds=row[\"timedelta\"]) except AttributeError: pass if \"selected\" in row.keys(): row[\"selected\"] = bool(row[\"selected\"]) self.jpg_data =",
"in enumerate(hist): tally += count if tally > threshold: return i def generate_clone_tuples(clone_to,",
"rint(h * scale) return cv2.resize(im, (new_w, new_h)) def generate_thumbnails(jpg_data, export_dir, long_edge=1024): \"\"\"Formats a",
"BLURRED() and CONTOURS() functions, but retained here to shorten the process_jpgs() function. min_area",
"for x in data] def stop_watch(i, timer): progress = (i * 10) //",
"limit. def CONTOURS(curr, prev, threshold, ksize=11, min_area=100): \"\"\"Slower, but powerful frame differencing method.",
"variables denoting selection, edits, event, etc. plot_params : dictionary Parameters used in the",
"them first. thumb_dir : str, optional If the interactive plot is laggy, use",
"row[\"selected\"] = bool(row[\"selected\"]) self.jpg_data = temp_data.copy() self.length = len(self.jpg_data) self.user_edits = {int(k): v",
"update_counts(self): \"\"\"Updates jpg_data with new counts (response metric). Variable new_count is attached to",
"curr[\"new_count\"] > self.plt_vals[\"resp_thresh\"]) prev = curr if self.dt_present: for move in (1, -1):",
"= resize_long_edge(im, long_edge) cv2.imwrite(to_path, resized) piexif.transplant(from_path, to_path) # SPECIFIC FUNCTIONS def find_imgs(dirpath, img_type=(\".jpg\",",
"[] for dir_, _, files in os.walk(dirpath): if \"_selected\" not in dir_: found",
"self.jpg_data[ind] if row[\"new_count\"] < 0: if func == operator.sub: master_set.add(ind) break else: master_set.add(ind)",
"tag. This can be changed if images don\"t have a datetime, but do",
"// scale) lo_H, hi_H = (0 - H // scale), (H + H",
"filepath }) return output def attach_exif(jpg_data, parse_tags=DEFAULT_PARSE): \"\"\"Loops through jpg_data, reading filepaths and",
"= shift self.mark_edits(i, \"user_edit\") def update_events(self): \"\"\"Updates jpg_data with new events (runs of",
"array, typically from cv2.imread(). Returns ------- tuple Format is (crop, clone_to, clone_directs). The",
"-0.1 RESP_NUM = 3.5 def PARSE_DT(raw): \"\"\"Default parser for EXIF \"Image DateTime\" tag.",
"{**self.user_edits, **new_edits} elif event.key == \",\": for i in lo_to_hi: self.user_edits.pop(i, None) self.press",
"anon in parse_tags: row[var] = anon(tags[key][tag]) output.append(row) return output def hist_median(image): \"\"\"Quickly finds",
"numpy.ndarray Image array, typically from cv2.imread(). crop : tuple Format is (y1, y2,",
"new_count = 0 self.mark_edits(i, \"trans_edit\") if self.dt_present: new_count *= 1 + ( self.plt_vals[\"night_mult\"]",
"fig.canvas.set_window_title(\"Crop and Clone Preview\") ax_crop = fig.add_subplot(gs[0, 0]) ax_clone = fig.add_subplot(gs[0, 1]) ax_mod",
"can be fed directly into process_jpgs(). Then, use \"generate_clone_tuples(clone_to, directs[0])\" to get the",
"(movement). Very noisy, but fast. Parameters ---------- curr : numpy.ndarray Image array, typically",
"256) Parameter to be passed to the cv2.threshold() function. ksize : int Parameter",
"variable can be fed directly into process_jpgs(). Then, use \"generate_clone_tuples(clone_to, directs[0])\" to get",
"while True: if any(n < 0 for n in array): array += 1",
"grayscale image. \"\"\" px_count = image.shape[0] * image.shape[1] hist = cv2.calcHist([image], [0], None,",
"row[\"med_diff\"] = abs(row[\"med_diff\"]) row[\"selected\"] = False row[\"user_edit\"] = False row[\"trans_edit\"] = False if",
"sequence. process_options : dictionary, optional Passes along paramters to the process_jpgs() function. By",
"function. Default is 11. Must be positive, odd number. min_area : int Minimum",
"preform image cropping, cloning, and histogram equalization on images read from jpg_data filepaths",
"COL_ORDER.index(var_name) else: return BIG_NUM def input_filename(): while True: filename = input(\"FILEPATH > \")",
"= fig.add_subplot(gs[0, 1]) ax_mod = fig.add_subplot(gs[1, :]) crop_RS = RectangleSelector( ax_crop, RS_event, **RS_PARAMS)",
"cropped image with an equalized histogram. Parameters ---------- image : numpy.ndarray Image array,",
"str(obj) return '\"' + string + '\"' if \",\" in string else string",
"return directory else: print(\"Directory does not exist, would you like to make it?\")",
"H, W, *_ = image.shape scale = 10 lo_W, hi_W = (0 -",
"+ H // scale) gs = gridspec.GridSpec(2, 2, height_ratios=[1, 1.25]) fig = plt.figure()",
"optional Matches the format ((clone_to), (clone_from)). For simplicity, use generate_clone_tuples() to generate this",
"blurred = cv2.medianBlur(difference, ksize) _, mask = cv2.threshold( blurred, threshold, 255, cv2.THRESH_BINARY) contours,",
"X = np.array(day_hr).reshape(-1, 1) kmeans = KMeans(n_clusters=3).fit(X) night_indices = [np.argmin(kmeans.cluster_centers_), np.argmax(kmeans.cluster_centers_)] for n,",
"= \"_\".join((dt_ISO, row[\"filename\"])) new_path = os.path.join(directory, new_name) write_row[\"filename\"] = new_name write_row[\"filepath\"] = new_path",
"(y1, y2, x1, x2), just like slicing images as np.arrays. fill_from : {\"A\",",
"for v in variables)) else: raise ValueError(\"No images selected for export.\") def attach_diffs(self,",
"\"\"\"Most basic frame differencing method. Takes two images, then finds their absolute difference.",
"process_jpgs(jpg_data, crop=crop, clone=clone) if type(processed_data) is not tuple: cam = Cam(processed_data) print(\"→ Please",
"list can be fed into the Cam() class for response filtering. Parameters ----------",
"like slicing images as np.arrays. fill_from : {\"A\", \"B\", \"R\", \"L\"} Calls directional",
"np.hstack([img[:min_y, :] for img in stack]) h, w, *_ = pano.shape cv2.namedWindow(\"Gallery\", cv2.WINDOW_NORMAL)",
"clone out any timestamps from images.\") crop, clone_to, directs = crop_clone_preview( cv2.imread(jpg_data[len(jpg_data) //",
"contours are drawn around the resulting white pixels. If the contours are above",
"to reduce noise. After thresholding, the resulting white pixels are counted toward response",
"area > min_area: count += area return count # JPG PROCESSING def process_jpgs(",
"filename = input(\"FILEPATH > \") if os.path.exists(filename): print(\"File already exists, would you like",
"i == 0: self.jpg_data[i][kind] = True else: self.jpg_data[i][kind] = True self.jpg_data[i-1][kind] = True",
"response value to Inf. z - Hold and release to DECREASE response value",
"True: directory = input(\"DIRPATH > \") if os.path.isdir(directory): return directory else: print(\"Directory does",
"import datetime as dt, timedelta as td from matplotlib import pyplot as plt",
"list of dictionaries Same as incoming jpg_data, but now with the median image",
"specify the export directory here. These smaller images will be displayed in the",
"None and event.key in \"zx,\": i = int(round(event.xdata)) low, high = sorted((self.press[1], i))",
"crop, clone_to, directs = crop_clone_preview( cv2.imread(jpg_data[len(jpg_data) // 2][\"filepath\"])) clone = (generate_clone_tuples(clone_to, directs[0]) if",
"DIRECTION_MULTS = { \"A\": (-1, -1, 0, 0), \"B\": (1, 1, 0, 0),",
"to shorten the process_jpgs() function. \"\"\" difference = cv2.absdiff(curr, prev) _, mask =",
"0 or min_x > W or max_x < 0) return tuple(map( lambda x:",
"[BIG_NUM, i] elif event.key == \",\": self.press = [0, i] if event.key in",
"for i, count in enumerate(hist): tally += count if tally > threshold: return",
"dictionary Parameters used in the plot() method. To reset these values, re- assign",
"export. QUICK GUIDE: c - Hold to VIEW IMAGES in gallery. x -",
"= -0.1 RESP_NUM = 3.5 def PARSE_DT(raw): \"\"\"Default parser for EXIF \"Image DateTime\"",
"= row[\"timedelta\"].total_seconds() if \"selected\" in row.keys(): row[\"selected\"] = int(row[\"selected\"]) with open(filename, \"w\") as",
"in array): array -= 1 else: break stack = [] for n in",
"/ 60 + time.second / 3600 def extract_var(data, var): \"\"\"Returns a list of",
"be passed to the cv2.medianBlur() function. Default is 11. Must be positive, odd",
"= directs mod = imgs[0] del choose else: mem.clone_tuple = False mem.clone_directs =",
"paramters to the process_jpgs() function. By default, no options are specified. Make sure",
"min_y = max(0, min(geometry[0, :])) max_y = min(H, max(geometry[0, :])) min_x = max(0,",
"_ = cv2.findContours( mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2:] count = 0 for cnt in contours:",
"\"user_edit\", \"trans_edit\" ] RS_PARAMS = { \"drawtype\": \"box\", \"useblit\": True, \"button\": [1, 3],",
"attached to jpg_data. Day to night transitions are filtered out based on slider.",
"self.plt_vals[\"smooth_time\"], \"%.1f\"), (\"NIGHT\", 0.02, -1, 50, self.plt_vals[\"night_mult\"], \"%.1f\") ] def update(): self.update_counts() self.update_events()",
"from DIRECTION_MULTS to fill pixels within the clone_to area. Neighboring pixels from \"[A]bove,\"",
"get the clone parameter, or any other direction in the directs list (all",
"in row.keys(): row[\"selected\"] = int(row[\"selected\"]) with open(filename, \"w\") as f: f.write(json.dumps(self.plt_vals) + \"\\n\")",
"if row[\"selected\"]: if self.dt_present: dt_ISO = dt.strftime( row[\"datetime\"], \"%Y%m%dT%H%M%S\" ) else: dt_ISO =",
"+ ( self.plt_vals[\"night_mult\"] * row[\"is_night\"]) row[\"new_count\"] = new_count for i, shift in self.user_edits.items():",
"for name in self.lines.keys(): self.lines[name].remove() np_counts = np.array(extract_var(self.jpg_data, \"new_count\")) self.lines[\"edited\"] = ax.fill_between( np.arange(0,",
"dictionary, optional Passes along paramters to the process_jpgs() function. By default, no options",
"= self.sliders[slider_key].val ** RESP_NUM self.plt_vals[key] = mod self.sliders[slider_key].valtext.set_text(\"%.2e\" % mod) else: self.plt_vals[key] =",
"1024 pixels on the long edge of the image. Smaller sizes speed up",
"= os.path.join(thumb_dir, row[\"filename\"]) else: row[\"thumbpath\"] = row[\"filepath\"] row[\"count\"] = row[self.resp_var] row[\"med_diff\"] = abs(row[\"med_diff\"])",
"0, 1, 1), \"L\": (0, 0, -1, -1) } COL_ORDER = [ \"old_name\",",
"this object. \"\"\" (a, b, c, d), (e, f, g, h) = clone",
"Then, events are lumped based on time since last image (SMOOTH slider value).",
"return tuple(map( lambda x: int(round(x)), (min_y, max_y, min_x, max_x))), ignore def RS_event(eclick, erelease):",
"on to frame differencing methods that generate a response metric. This is the",
"if clone_to else False print(\"→ Images are being processed.\") processed_data = process_jpgs(jpg_data, crop=crop,",
"temp_data = [ {k: v for k, v in row.items()} for row in",
"are identified as being selected or not. Then, events are lumped based on",
"tone and a count variable, which respresents how many pixels have changed between",
"\"\"\" def __init__(self, jpg_data=False, resp_var=\"count\", thumb_dir=None): \"\"\" Parameters ---------- jpg_data : list of",
"ksize), mask and sum. def BLURRED(curr, prev, threshold, ksize=11, min_area=None): \"\"\"Useful, mid-grade frame",
"= len(self.jpg_data) self.dt_present = \"datetime\" in self.jpg_data[0].keys() h, w = jpg_data[0][\"shape\"] self.plt_vals[\"ceiling\"] =",
"day_hr = extract_var(self.jpg_data, \"24hr\") # meds = extract_var(self.jpg_data, \"median\") X = np.array(day_hr).reshape(-1, 1)",
"are counted toward response (movement). Very noisy, but fast. Parameters ---------- curr :",
"generate_clone_tuples(clone_to, fill_from): \"\"\"Loops through jpg_data, reading filepaths and attaching EXIF data. Useful for",
"as an example parameter to pass to attach_exif(), if more data is desired",
"bool(row[\"selected\"]) self.jpg_data = temp_data.copy() self.length = len(self.jpg_data) self.user_edits = {int(k): v for k,",
"int(round(x)), (min_y, max_y, min_x, max_x))), ignore def RS_event(eclick, erelease): x1, y1 = eclick.xdata,",
"self.press = [NEG_NUM, i] elif event.key == \"x\": self.press = [BIG_NUM, i] elif",
"output def attach_exif(jpg_data, parse_tags=DEFAULT_PARSE): \"\"\"Loops through jpg_data, reading filepaths and attaching EXIF data.",
"clone_to + (h_or_w * mults) return (tuple(clone_to), tuple(clone_from)) # IMAGE PREPROCESSING def CROPPER(image,",
"images will be displayed in the Gallery tab. \"\"\" self.resp_var = resp_var self.plt_vals",
"dictionaries within the jpg_data list are sorted by their \"Image DateTime\" EXIF tag.",
"_, files in os.walk(dirpath): if \"_selected\" not in dir_: found = ( f",
"+ string + '\"' if \",\" in string else string def to_24_hour(datetime): \"\"\"Converts",
"\"\"\" if not os.path.exists(directory): os.makedirs(directory) write_data = [] for i, row in enumerate(self.jpg_data):",
"initialization could be: Cam(construct_jpg_data()). After filtering images with the plot, save() and export()",
"list of dictionaries Similar to what is inputted, but includes variables denoting selection,",
"\"\"\"Formats a timedelta object as a string. Parameters ---------- jpg_data : list of",
"as inst: if \"(-209:Sizes\" in str(inst): (a, b), (c, d) = curr.shape[:2], prev.shape[:2]",
"= [] timer = (len(jpg_data) // 10, time.time()) for i, deep_row in enumerate(jpg_data):",
"spaces, filled with zeros. \"\"\" d = {\"days\": tdelta.days} d[\"hours\"], rem = divmod(tdelta.seconds,",
"= clone image[a:b, c:d] = image[e:f, g:h] image = CROPPER(image, crop) return cv2.equalizeHist(image)",
"well, little noise; slower than others. Parameters ---------- curr : numpy.ndarray Image array,",
"self.press[0] for i in lo_to_hi} self.user_edits = {**self.user_edits, **new_edits} elif event.key == \",\":",
"ax.axhline( self.plt_vals[\"resp_thresh\"], color=\"#14B37D\") fig.canvas.draw_idle() def on_slide(val): for key in self.plt_vals.keys(): if key !=",
"Returns ------- str Right justified 2 spaces, filled with zeros. \"\"\" d =",
"} DIRECTION_MULTS = { \"A\": (-1, -1, 0, 0), \"B\": (1, 1, 0,",
"\"threshold\", \"selected\", \"edited\"): self.lines[name] = ax.axhline() for name, pos, minv, maxv, init, fmt",
"images with the plot, save() and export() should be called so as not",
"abs(row[\"med_diff\"]) row[\"selected\"] = False row[\"user_edit\"] = False row[\"trans_edit\"] = False if self.dt_present: self.attach_diffs(\"datetime\",",
"None: i = int(round(event.xdata)) if event.key == \"z\": self.press = [NEG_NUM, i] elif",
"Returns ------- list of dictionaries Each row contains everything that is needed to",
"mem.crop_tuple = False mem.clone_tuple = False mem.clone_directs = False def update(event): if crop_RS.active:",
"(clone_from)). For simplicity, use generate_clone_tuples() to generate this object. \"\"\" image = CROPPER(image,",
"if self.dt_present: self.attach_diffs(\"datetime\", \"timedelta\") for row in self.jpg_data: row[\"24hr\"] = to_24_hour(row[\"datetime\"]) row[\"td_minutes\"] =",
"\"\"\"Returns a cropped image, with specified cloning and equalization. Parameters ---------- image :",
"generate this object. threshold : int, in range(0, 256) Parameter to be passed",
"Passes along paramters to the process_jpgs() function. By default, no options are specified.",
"w) print(\"FUNCTION ABORTED!\\n\" \"Not all images are of same size, \" \"consider using",
"being processed.\") processed_data = process_jpgs(jpg_data, crop=crop, clone=clone) if type(processed_data) is not tuple: cam",
"print(\"→ Save once again, so changes are recorded.\") cam.save(input_filename()) print(\"→ Finally, choose a",
"= {} self.user_edits = {} self.press = [None, None] self.toggle = False self.buffer",
"func(i, j) try: row = self.jpg_data[ind] if row[\"new_count\"] < 0: if func ==",
"fmt in SLIDER_PARAMS: slider_ax = fig.add_axes([0.125, pos, 0.8, 0.02]) self.sliders[name] = Slider( slider_ax,",
"data # used in exporting, parameters for graphing, and plot function. class Cam():",
"> \") if os.path.isdir(directory): return directory else: print(\"Directory does not exist, would you",
"(1, 1, 0, 0), \"R\": (0, 0, 1, 1), \"L\": (0, 0, -1,",
"d[\"minutes\"], d[\"seconds\"] = divmod(rem, 60) for k, v in d.items(): if k !=",
"func in (operator.add, operator.sub): for j in range(nudge+1): ind = func(i, j) try:",
"tups = generate_clone_tuples(cl_corn, direct) a, b, c, d = tups[1] if not (a",
"and Clone Preview\") ax_crop = fig.add_subplot(gs[0, 0]) ax_clone = fig.add_subplot(gs[0, 1]) ax_mod =",
"Hold and release to DECREASE response value to 0. , - Hold and",
"area. Neighboring pixels from \"[A]bove,\" \"[B]elow,\" \"[R]ight,\" and \"[L]eft\" are used for filling",
"self.dt_present: for move in (1, -1): is_neg = move < 0 prev =",
"them. \"\"\" string = str(obj) return '\"' + string + '\"' if \",\"",
"off_key(event): try: if event.xdata is not None and event.key in \"zx,\": i =",
"curr else: nudge = int(self.plt_vals[\"smooth_time\"]) master_set = set() for i, row in enumerate(self.jpg_data):",
"c, d = clone_to h, w = b - a, d - c",
"plot(self): \"\"\"Interactive plot used to select images for export. QUICK GUIDE: c -",
"def CROP_EQUALIZE(image, crop, clone=None): \"\"\"Returns a cropped image with an equalized histogram. Parameters",
"as a response, but alternatives like \"median\" can be used to plot jpgs",
"return output def attach_exif(jpg_data, parse_tags=DEFAULT_PARSE): \"\"\"Loops through jpg_data, reading filepaths and attaching EXIF",
"= curr[\"td_minutes\"] else: lapse = prev[\"td_minutes\"] curr[\"selected\"] = ( lapse <= self.plt_vals[\"smooth_time\"]) prev",
"are specified. Make sure that this parameter is mappable. Returns ------- list of",
"process_jpgs(). Can be omitted if a empty Cam() object is desired for a",
"row[\"filepath\"] shutil.copy2(row[\"filepath\"], new_path) write_data.append(write_row) if write_data: with open(os.path.join(directory, \"_export.csv\"), \"w\") as f: variables",
"the mask. def SIMPLE(curr, prev, threshold, ksize=None, min_area=None): \"\"\"Most basic frame differencing method.",
"Must be positive, odd number. min_area : int Minimum contour area to count",
":])) max_x = min(W, max(geometry[1, :])) ignore = (min_y > H or max_y",
"= [] for dir_, _, files in os.walk(dirpath): if \"_selected\" not in dir_:",
"= plt.figure() fig.canvas.set_window_title(\"Crop and Clone Preview\") ax_crop = fig.add_subplot(gs[0, 0]) ax_clone = fig.add_subplot(gs[0,",
"in self.user_edits.items(): self.jpg_data[i][\"new_count\"] = shift self.mark_edits(i, \"user_edit\") def update_events(self): \"\"\"Updates jpg_data with new",
"self.update_events() draw() def draw(): for name in self.lines.keys(): self.lines[name].remove() np_counts = np.array(extract_var(self.jpg_data, \"new_count\"))",
"filenames and filepaths. \"\"\" output = [] for dir_, _, files in os.walk(dirpath):",
"{k: v for k, v in row.items()} for row in self.jpg_data] for row",
"np.array(range(i - 2, i + 2)) while True: if any(n < 0 for",
"to generate this object. \"\"\" (a, b, c, d), (e, f, g, h)",
"row[\"selected\"]: for func in (operator.add, operator.sub): for j in range(nudge+1): ind = func(i,",
"/ 60, 2) day_hr = extract_var(self.jpg_data, \"24hr\") # meds = extract_var(self.jpg_data, \"median\") X",
"Cam(): \"\"\" A class used to store, plot, filter, and export image data.",
"= {**self.user_edits, **new_edits} elif event.key == \",\": for i in lo_to_hi: self.user_edits.pop(i, None)",
"to have data to initialize. # This way, someone can load() older, processed",
"(tuple(clone_to), tuple(clone_from)) # IMAGE PREPROCESSING def CROPPER(image, crop): \"\"\"Returns a cropped image. Parameters",
"Similar to what is inputted, but includes variables denoting selection, edits, event, etc.",
"False row[\"trans_edit\"] = False new_count = row[\"count\"] if row[\"med_diff\"] > self.plt_vals[\"trans_thresh\"]: new_count =",
">= self.length for n in array): array -= 1 else: break stack =",
"( f for f in files if f.lower().endswith(img_type) ) for filename in found:",
"row[\"count\"] = row[self.resp_var] row[\"med_diff\"] = abs(row[\"med_diff\"]) row[\"selected\"] = False row[\"user_edit\"] = False row[\"trans_edit\"]",
"in temp_dict.items()} def export(self, directory): \"\"\"Exports selected images and a .csv file to",
"between the current and previous items. export(directory) Exports selected images and a .csv",
"= sorted(write_data[0].keys(), key=sort_cols) for i, row in enumerate(write_data): if i != 0: f.write(\"\\n\")",
"def export(self, directory): \"\"\"Exports selected images and a .csv file to specified directory.",
"__init__(self): pass def rint(n): return round(int(n)) def sort_cols(var_name): if var_name in COL_ORDER: return",
"example parameter to pass to attach_exif(), if more data is desired from EXIF",
"A simple threshold is called, the resulting white pixels are counted toward response",
": int, unused Used in the BLURRED() and CONTOURS() functions, but retained here",
"be positive, odd number. min_area : int, unused Only used in the CONTOURS()",
"in str(inst): (a, b), (c, d) = curr.shape[:2], prev.shape[:2] h, w = min(a,",
"NEG_NUM = -0.1 RESP_NUM = 3.5 def PARSE_DT(raw): \"\"\"Default parser for EXIF \"Image",
"range(nudge+1): ind = func(i, j) try: row = self.jpg_data[ind] if row[\"new_count\"] < 0:",
"keys, which is easily provided by find_imgs() prior to this function. parse_tags :",
"pass on_slide(1) plt.show() cv2.destroyAllWindows() if __name__ == \"__main__\": print(\"→ Please input a directory",
"the export directory here. These smaller images will be displayed in the Gallery",
"\"ceiling\": slider_key = key[:key.find(\"_\")].upper() if key == \"resp_thresh\": mod = self.sliders[slider_key].val ** RESP_NUM",
"mod self.sliders[slider_key].valtext.set_text(\"%.2e\" % mod) else: self.plt_vals[key] = self.sliders[slider_key].val update() # Displays last two",
"print(\"→ Images are being processed.\") processed_data = process_jpgs(jpg_data, crop=crop, clone=clone) if type(processed_data) is",
"typically from cv2.imread(). crop : tuple Format is (y1, y2, x1, x2), just",
"timer = (len(jpg_data) // 10, time.time()) for i, deep_row in enumerate(jpg_data): row =",
"w = jpg_data[0][\"shape\"] self.plt_vals[\"ceiling\"] = h * w * 0.02 self.plt_vals[\"resp_thresh\"] = self.plt_vals[\"ceiling\"]",
"plot_params : dictionary Parameters used in the plot() method. To reset these values,",
"if camera exports a different filetype. Returns ------- list of dictionaries Contains filenames",
"+ W // scale) lo_H, hi_H = (0 - H // scale), (H",
"x in string.digits) return dt.strptime(str_, \"%Y%m%d%H%M%S\") def SORT_BY_DT(row): \"\"\"Default sort for construct_jpg_data(). \"\"\"",
"min_x, max_x))), ignore def RS_event(eclick, erelease): x1, y1 = eclick.xdata, eclick.ydata x2, y2",
"as inst: raise inst mod = self.plt_vals[\"resp_thresh\"] ** (1 / RESP_NUM) SLIDER_PARAMS =",
"new_h)) def generate_thumbnails(jpg_data, export_dir, long_edge=1024): \"\"\"Formats a timedelta object as a string. Parameters",
"= 10 lo_W, hi_W = (0 - W // scale), (W + W",
"output = [] for dir_, _, files in os.walk(dirpath): if \"_selected\" not in",
"h, w, *_ = pano.shape cv2.namedWindow(\"Gallery\", cv2.WINDOW_NORMAL) cv2.imshow(\"Gallery\", cv2.resize(pano, (w // 2, h",
"use. Ordered from left to right based on increasing accuracy, decreasing speed. crop",
"performance, but decrease acuity. \"\"\" if not os.path.exists(export_dir): os.makedirs(export_dir) timer = (len(jpg_data) //",
"if any(n < 0 for n in array): array += 1 elif any(n",
"maxv, init, fmt in SLIDER_PARAMS: slider_ax = fig.add_axes([0.125, pos, 0.8, 0.02]) self.sliders[name] =",
"event.key == \".\": self.user_edits = {} def off_key(event): try: if event.xdata is not",
"self.jpg_data[i] boo = (not curr[\"selected\"] and prev[\"selected\"] and not (prev[\"user_edit\"] and curr[\"user_edit\"])) if",
"= elapsed / (progress / 100) remain = strfdelta(td(seconds=total - elapsed), \"{days}:{hours}:{minutes}:{seconds}\") print(f\"{progress}%",
"if var_name in COL_ORDER: return COL_ORDER.index(var_name) else: return BIG_NUM def input_filename(): while True:",
"is in dictionary keys, which is easily provided by find_imgs() prior to this",
"else: self.dt_present = False if \"timedelta\" in row.keys(): try: row[\"timedelta\"] = td(seconds=row[\"timedelta\"]) except",
"enumerate(self.jpg_data): if row[\"selected\"]: for func in (operator.add, operator.sub): for j in range(nudge+1): ind",
"in self.jpg_data: row[\"24hr\"] = to_24_hour(row[\"datetime\"]) row[\"td_minutes\"] = round( row[\"timedelta\"].total_seconds() / 60, 2) day_hr",
"- prev prev = curr def mark_edits(self, i, kind): \"\"\"Marks which photos to",
"((clone_to), (clone_from)). For simplicity, use generate_clone_tuples() to generate this object. threshold : int,",
"count if tally > threshold: return i def generate_clone_tuples(clone_to, fill_from): \"\"\"Loops through jpg_data,",
"contours over given limit. def CONTOURS(curr, prev, threshold, ksize=11, min_area=100): \"\"\"Slower, but powerful",
"self.length) + 0.5, -BIG_NUM, BIG_NUM, where=extract_var(self.jpg_data, \"selected\"), facecolor=\"#F00314\") self.lines[\"count\"] = ax.fill_between( range(self.length), 0,",
"just like slicing images as np.arrays. fill_from : {\"A\", \"B\", \"R\", \"L\"} Calls",
"k, v in d.items(): if k != \"days\": d[k] = str(v).rjust(2, \"0\") return",
"ksize : int Parameter to be passed to the cv2.medianBlur() function. Default is",
"in the plot() method. To reset these values, re- assign DEFAULT_PLOT_PARAMS to this",
"Parameters ---------- jpg_data : list of dictionaries Requires that \"filepath\" is in dictionary",
"Image array, typically from cv2.imread(). crop : tuple Format is (y1, y2, x1,",
"cl_ig: mem.clone_tuple = cl_corn trials = [] for direct in (\"A\", \"B\", \"R\",",
"INCREASE response value to Inf. z - Hold and release to DECREASE response",
"of dictionaries, optional Typically requires the output of process_jpgs(). Can be omitted if",
"for filling the area. Returns ------- pair of tuples Matches the format for",
"self.jpg_data[n][\"is_night\"] = index in night_indices def save(self, filename): \"\"\"Dumps a JSON object with",
"\"\"\" temp_data = [ {k: v for k, v in row.items()} for row",
"cam.save(input_filename()) print(\"→ Use the interactive plot to select images for export.\") help(Cam.plot) cam.plot()",
"tags = piexif.load(row[\"filepath\"]) for (key, tag), var, anon in parse_tags: row[var] = anon(tags[key][tag])",
"tup = (0, h, 0, w) print(\"FUNCTION ABORTED!\\n\" \"Not all images are of",
"to make it?\") answer = input(\"Y / N > \") if answer.lower() in",
"- H // scale), (H + H // scale) gs = gridspec.GridSpec(2, 2,",
"night_indices = [np.argmin(kmeans.cluster_centers_), np.argmax(kmeans.cluster_centers_)] for n, index in enumerate(kmeans.labels_): self.jpg_data[n][\"is_night\"] = index in",
"operator import os import shutil import string import sys import time import cv2",
"------- list of dictionaries Contains filenames and filepaths. \"\"\" output = [] for",
"EXIF tags. Returns ------- list of dictionaries Same as jpg_data, but now with",
"jpg_data, reading filepaths and attaching EXIF data. Parameters ---------- jpg_data : list of",
"someone can load() older, processed data. if jpg_data: self.jpg_data = list(jpg_data) self.length =",
"desired from EXIF tags. sort_key : function, optional By default, dictionaries within the",
"ax.grid(alpha=0.4) ax.set_axisbelow(True) ax.set_ylim([0, self.plt_vals[\"ceiling\"]]) ax.set_xlim([0, min(500, self.length)]) ax.set_xlabel(\"Frame\") ax.set_ylabel(\"Response\") plt.yticks(rotation=45) for name in",
"---------- clone_to : tuple Format is (y1, y2, x1, x2), just like slicing",
"clone parameter in process_jpgs(). \"\"\" clone_to = np.array(clone_to) mults = np.array(DIRECTION_MULTS[fill_from[0].upper()]) a, b,",
"cv2.COLOR_BGR2RGB) ax_mod.imshow(mod) fig.canvas.draw_idle() rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) H, W, *_ = image.shape scale",
"test = image.copy() (a, b, c, d), (e, f, g, h) = tups",
"RS_event, **RS_PARAMS) clone_RS = RectangleSelector( ax_clone, RS_event, **RS_PARAMS) ax_crop.set_title(\"Crop\") ax_clone.set_title(\"Clone\") ax_mod.set_title(\"Result\") for axe",
"taken at with nighttime are multiplied based on slider. Manual user edits are",
"rem = divmod(tdelta.seconds, 3600) d[\"minutes\"], d[\"seconds\"] = divmod(rem, 60) for k, v in",
"total = elapsed / (progress / 100) remain = strfdelta(td(seconds=total - elapsed), \"{days}:{hours}:{minutes}:{seconds}\")",
"now identical to the last. \"\"\" with open(filename, \"r\") as f: self.plt_vals =",
"step before the jpg_data list can be fed into the Cam() class for",
"method. A simply initialization could be: Cam(construct_jpg_data()). After filtering images with the plot,",
"= os.path.expanduser(\"~\") # Cam objects don\"t need to have data to initialize. #",
"easily provided by find_imgs() prior to this function. export_dir : str Directory path",
"lambda x: int(round(x)), (min_y, max_y, min_x, max_x))), ignore def RS_event(eclick, erelease): x1, y1",
"if more data is desired from EXIF tags. sort_key : function, optional By",
"fmt.format(**d) def resize_long_edge(im, size): h, w, *_ = im.shape if w > h:",
"pixels have changed between a photo and its previous, after preprocessing / thresholding.",
"curr[\"selected\"] and prev[\"selected\"] and not (prev[\"user_edit\"] and curr[\"user_edit\"])) if boo: if not is_neg:",
"= cv2.threshold( difference, threshold, 255, cv2.THRESH_BINARY) return cv2.countNonZero(mask) # Difference, blur (amount changes",
"image cropping, cloning, and histogram equalization on images read from jpg_data filepaths before",
"= self.jpg_data[i] boo = (not curr[\"selected\"] and prev[\"selected\"] and not (prev[\"user_edit\"] and curr[\"user_edit\"]))",
"to the cv2.medianBlur() function. Default is 11. Must be positive, odd number. min_area",
"mod = cv2.cvtColor(mod, cv2.COLOR_BGR2RGB) ax_mod.imshow(mod) fig.canvas.draw_idle() rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) H, W, *_",
"SLIDER_PARAMS = [ (\"RESP\", 0.08, 0, 100, mod, \"%.2e\"), (\"TRANS\", 0.06, 0, 120,",
"not None: if self.press[0] is None: i = int(round(event.xdata)) if event.key == \"z\":",
"are being processed.\") processed_data = process_jpgs(jpg_data, crop=crop, clone=clone) if type(processed_data) is not tuple:",
"operator.sub: master_set.add(ind) break else: master_set.add(ind) except IndexError: pass for i in master_set: self.jpg_data[i][\"selected\"]",
"\"\"\" self.resp_var = resp_var self.plt_vals = DEFAULT_PLOT_PARAMS self.lines = {} self.sliders = {}",
"os.walk(dirpath): if \"_selected\" not in dir_: found = ( f for f in",
"print(inst) prev = curr output.append(row) return output def construct_jpg_data( dirpath, parse_tags=DEFAULT_PARSE, sort_key=SORT_BY_DT, process_options={}",
"+= area return count # JPG PROCESSING def process_jpgs( jpg_data, method=CONTOURS, crop=False, clone=False,",
"= bool(row[\"selected\"]) self.jpg_data = temp_data.copy() self.length = len(self.jpg_data) self.user_edits = {int(k): v for",
"ax = fig.add_subplot(111) fig.canvas.set_window_title(\"Response Filtering\") fig.subplots_adjust(0.07, 0.18, 0.97, 0.97) ax.grid(alpha=0.4) ax.set_axisbelow(True) ax.set_ylim([0, self.plt_vals[\"ceiling\"]])",
"\"drawtype\": \"box\", \"useblit\": True, \"button\": [1, 3], \"minspanx\": 5, \"minspany\": 5, \"spancoords\": \"pixels\",",
"# GENERAL FUNCTIONS class Mem(): def __init__(self): pass def rint(n): return round(int(n)) def",
"= False else: mem.crop_tuple = cr_corn y1, y2, x1, x2 = cr_corn mod",
"AND POTATOES # Requires data from process_jpg(). Object essentially holds data # used",
"------- pair of tuples Matches the format for the clone parameter in process_jpgs().",
"CROPPER(image, crop): \"\"\"Returns a cropped image. Parameters ---------- image : numpy.ndarray Image array,",
"blurred to reduce noise. After thresholding, the resulting white pixels are counted toward",
"image data. Contains the heart of this module, the interactive plot() method. A",
"release to REMOVE EDITS. . - Press to RESET ALL EDITS. v -",
"erelease.ydata cr_corn, cr_ig = safe_corners(crop_RS.geometry) cl_corn, cl_ig = safe_corners(clone_RS.geometry) mod = image.copy() if",
"cv2.medianBlur() function. Default is 11. Must be positive, odd number. min_area : int",
"else: preprocess = CROP_CLONE_EQUALIZE output = [] timer = (len(jpg_data) // 10, time.time())",
"optional Typically requires the output of process_jpgs(). Can be omitted if a empty",
"img in stack]) h, w, *_ = pano.shape cv2.namedWindow(\"Gallery\", cv2.WINDOW_NORMAL) cv2.imshow(\"Gallery\", cv2.resize(pano, (w",
"return time.hour + time.minute / 60 + time.second / 3600 def extract_var(data, var):",
"with the plot, save() and export() should be called so as not to",
"Larger numbers decreases sensitivity. Returns ------- list of dictionaries Same as incoming jpg_data,",
"0 for cnt in contours: area = cv2.contourArea(cnt) if area > min_area: count",
"] DEFAULT_PLOT_PARAMS = { \"ceiling\": 40000, \"resp_thresh\": 20000, \"trans_thresh\": 30, \"smooth_time\": 1, \"night_mult\":",
"RESP_NUM)) temp_data = json.loads(next(f)) temp_dict = json.loads(next(f)) for row in temp_data: if \"datetime\"",
"not threshold: thresh_init = False if not clone: preprocess = CROP_EQUALIZE else: preprocess",
"directs mod = imgs[0] del choose else: mem.clone_tuple = False mem.clone_directs = False",
"process_options = {\"crop\": crop, \"clone\": clone} print(\"Started processing...\") output = process_jpgs(jpg_data, **process_options) print(\"Done!\")",
"Please input a directory path with camera-trapping images.\") jpg_paths = find_imgs(input_directory()) jpg_data =",
"path.\") def csv_safe(obj): \"\"\"Puts quotes around strings with commas in them. \"\"\" string",
"N > \") if answer.lower() in (\"y\", \"yes\"): os.makedirs(directory) return directory print(\"Please input",
"b, c, d), (e, f, g, h) = tups test[a:b, c:d] = test[e:f,",
"are sorted by their \"Image DateTime\" EXIF tag. This can be changed if",
"process_jpg(). Object essentially holds data # used in exporting, parameters for graphing, and",
"EQUALIZED image (for dark images). \"\"\" try: self.jpg_data except AttributeError as inst: raise",
"0 threshold = px_count / 2 for i, count in enumerate(hist): tally +=",
"trials: test = image.copy() (a, b, c, d), (e, f, g, h) =",
"\"\"\" Parameters ---------- jpg_data : list of dictionaries, optional Typically requires the output",
"(operator.add, operator.sub): for j in range(nudge+1): ind = func(i, j) try: row =",
"is now identical to the last. \"\"\" with open(filename, \"r\") as f: self.plt_vals",
"\"zx,\": i = int(round(event.xdata)) low, high = sorted((self.press[1], i)) lo_to_hi = range(max(0, low),",
"if tally > threshold: return i def generate_clone_tuples(clone_to, fill_from): \"\"\"Loops through jpg_data, reading",
"ax_clone.imshow(rgb) ax_mod.imshow(rgb) plt.connect(\"draw_event\", update) plt.show() return mem.crop_tuple, mem.clone_tuple, mem.clone_directs # FRAME DIFFERENCING METHODS",
"frame differencing methods that generate a response metric. This is the last step",
"to be passed to the cv2.threshold() function. ksize : int Parameter to be",
"Cam() class for response filtering. Parameters ---------- jpg_data : list of dictionaries Requires",
"the difference between the current and previous variable. Requires a list of dictionaries.",
"timedelta object as a string. Parameters ---------- jpg_data : list of dictionaries Requires",
"but only sums drawn contours over given limit. def CONTOURS(curr, prev, threshold, ksize=11,",
"jpg_data. Day to night transitions are filtered out based on slider. Counts taken",
"crop = (0, h, 0, w) prev = preprocess(jpg, crop, clone) elif i",
"images will be resized to 1024 pixels on the long edge of the",
"= input(\"Y / N > \") if answer.lower() in (\"y\", \"yes\"): return filename",
"DEFAULT_PARSE as an example parameter to pass to attach_exif(), if more data is",
"Takes two images, then finds their absolute difference. A simple threshold is called,",
"dictionaries Requires that \"filepath\" is in dictionary keys, which is easily provided by",
"as np.arrays. fill_from : {\"A\", \"B\", \"R\", \"L\"} Calls directional tuples from DIRECTION_MULTS",
"response (movement). Works decently, a little faster than COUNTOURS. Parameters ---------- curr :",
"differenced. threshold : int, in range(0, 256) Parameter to be passed to the",
"-1, 0, 0), \"B\": (1, 1, 0, 0), \"R\": (0, 0, 1, 1),",
"Preview\") ax_crop = fig.add_subplot(gs[0, 0]) ax_clone = fig.add_subplot(gs[0, 1]) ax_mod = fig.add_subplot(gs[1, :])",
"[] for n in array: if n in self.buffer[0]: ind = self.buffer[0].index(n) img",
"class Cam(): \"\"\" A class used to store, plot, filter, and export image",
"\"\"\"Useful, mid-grade frame differencing method. Takes two images, then finds their absolute difference.",
"self.toggle = not self.toggle image_pano(event.xdata) elif event.key == \".\": self.user_edits = {} def",
"If the interactive plot is laggy, use resize_with_exif() on your jpg_data list, and",
"------- list of dictionaries Same as jpg_data, but now with desired EXIF data",
"event.xdata is not None and event.key in \"zx,\": i = int(round(event.xdata)) low, high",
"= clone_to + (h_or_w * mults) return (tuple(clone_to), tuple(clone_from)) # IMAGE PREPROCESSING def",
"do have a variable for sequence. process_options : dictionary, optional Passes along paramters",
"curr[\"new_count\"] > self.plt_vals[\"resp_thresh\"]) if i == self.length-1: curr[\"selected\"] = ( curr[\"new_count\"] > self.plt_vals[\"resp_thresh\"])",
"filepaths and attaching EXIF data. Parameters ---------- jpg_data : list of dictionaries Requires",
"= tups test[a:b, c:d] = test[e:f, g:h] diff = cv2.absdiff(test, image) choose.append((sum(cv2.sumElems(diff)), direct,",
"data. Contains the heart of this module, the interactive plot() method. A simply",
"True: if any(n < 0 for n in array): array += 1 elif",
"= divmod(tdelta.seconds, 3600) d[\"minutes\"], d[\"seconds\"] = divmod(rem, 60) for k, v in d.items():",
"in enumerate(self.jpg_data): write_row = row.copy() if row[\"selected\"]: if self.dt_present: dt_ISO = dt.strftime( row[\"datetime\"],",
"self.plt_vals[\"trans_thresh\"]: new_count = 0 self.mark_edits(i, \"trans_edit\") if self.dt_present: new_count *= 1 + (",
"differencing method to use. Ordered from left to right based on increasing accuracy,",
"row[var] row[new_var] = curr - prev prev = curr def mark_edits(self, i, kind):",
"int(round(event.xdata)) low, high = sorted((self.press[1], i)) lo_to_hi = range(max(0, low), min(self.length, high+1)) if",
"changed between a photo and its previous, after preprocessing / thresholding. \"\"\" if",
"images and a .csv file to specified directory. \"\"\" if not os.path.exists(directory): os.makedirs(directory)",
"pair of tuples, optional Matches the format ((clone_to), (clone_from)). For simplicity, use generate_clone_tuples()",
"Parameters used in the plot() method. To reset these values, re- assign DEFAULT_PLOT_PARAMS",
"\"\"\"Loads a .sav file, the Cam() object is now identical to the last.",
"prev = self.jpg_data[0] for i, curr in enumerate(self.jpg_data): prev[\"selected\"] = ( prev[\"new_count\"] >",
"attaching EXIF data. Parameters ---------- jpg_data : list of dictionaries Requires that \"filepath\"",
"cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2:] count = 0 for cnt in contours: area = cv2.contourArea(cnt) if",
"plt.rcParams[\"keymap.back\"] = \"left, backspace\" fig = plt.figure() ax = fig.add_subplot(111) fig.canvas.set_window_title(\"Response Filtering\") fig.subplots_adjust(0.07,",
"move) - is_neg, move): curr = self.jpg_data[i] boo = (not curr[\"selected\"] and prev[\"selected\"]",
"return directory print(\"Please input a new directory path.\") def csv_safe(obj): \"\"\"Puts quotes around",
"list(jpg_data) self.length = len(self.jpg_data) self.dt_present = \"datetime\" in self.jpg_data[0].keys() h, w = jpg_data[0][\"shape\"]",
"i = int(round(event.xdata)) low, high = sorted((self.press[1], i)) lo_to_hi = range(max(0, low), min(self.length,",
"this function. export_dir : str Directory path that is used for exporting thumbnails.",
"on slider. Counts taken at with nighttime are multiplied based on slider. Manual",
"{} def off_key(event): try: if event.xdata is not None and event.key in \"zx,\":",
"= row[\"filename\"] write_row[\"old_path\"] = row[\"filepath\"] shutil.copy2(row[\"filepath\"], new_path) write_data.append(write_row) if write_data: with open(os.path.join(directory, \"_export.csv\"),",
"image : numpy.ndarray Image array, typically from cv2.imread(). Returns ------- tuple Format is",
"laggy, use resize_with_exif() on your jpg_data list, and specify the export directory here.",
"jpg_data, method=CONTOURS, crop=False, clone=False, threshold=False, ksize=11, min_area=100 ): \"\"\"Generates a response (movement) metric",
"\"\"\"Exports selected images and a .csv file to specified directory. \"\"\" if not",
"ax.set_xlim([0, min(500, self.length)]) ax.set_xlabel(\"Frame\") ax.set_ylabel(\"Response\") plt.yticks(rotation=45) for name in (\"count\", \"threshold\", \"selected\", \"edited\"):",
"cl_ig = safe_corners(clone_RS.geometry) mod = image.copy() if not cl_ig: mem.clone_tuple = cl_corn trials",
"v in row.items()} for row in self.jpg_data] for row in temp_data: if \"datetime\"",
"== {}: print(\"Crop and clone image as desired.\") crop, clone_to, directs = crop_clone_preview(",
": numpy.ndarray Like curr. The second image to be differenced. threshold : int,",
"row[\"timedelta\"].total_seconds() if \"selected\" in row.keys(): row[\"selected\"] = int(row[\"selected\"]) with open(filename, \"w\") as f:",
"row = deep_row.copy() tags = piexif.load(row[\"filepath\"]) for (key, tag), var, anon in parse_tags:",
"a load() method call. resp_var : str, optional A key found in jpg_data,",
"[0], None, [256], [0, 256]) tally = 0 threshold = px_count / 2",
"faster than COUNTOURS. Parameters ---------- curr : numpy.ndarray Image array, typically from cv2.imread().",
"True else: self.dt_present = False if \"timedelta\" in row.keys(): try: row[\"timedelta\"] = td(seconds=row[\"timedelta\"])",
"var=\"name\") [\"Shane\", \"Eve\"] \"\"\" return [x[var] for x in data] def stop_watch(i, timer):",
"detection). An event is a contiguous sequence of images. First, images are identified",
"= ax.axhline() for name, pos, minv, maxv, init, fmt in SLIDER_PARAMS: slider_ax =",
"in self.jpg_data: curr = row[var] row[new_var] = curr - prev prev = curr",
"for row in self.jpg_data] for row in temp_data: if \"datetime\" in row.keys(): row[\"datetime\"]",
"= pano.shape cv2.namedWindow(\"Gallery\", cv2.WINDOW_NORMAL) cv2.imshow(\"Gallery\", cv2.resize(pano, (w // 2, h // 2))) cv2.waitKey(1)",
"\"_\".join((dt_ISO, row[\"filename\"])) new_path = os.path.join(directory, new_name) write_row[\"filename\"] = new_name write_row[\"filepath\"] = new_path write_row[\"old_name\"]",
"image, with specified cloning and equalization. Parameters ---------- image : numpy.ndarray Image array,",
"photos have been edited. plot() Interactive plot used to select images for export.",
"extract_var(self.jpg_data, \"median\") X = np.array(day_hr).reshape(-1, 1) kmeans = KMeans(n_clusters=3).fit(X) night_indices = [np.argmin(kmeans.cluster_centers_), np.argmax(kmeans.cluster_centers_)]",
"in row.keys(): row[\"datetime\"] = dt.strftime( row[\"datetime\"], \"%Y-%m-%d %H:%M:%S\") if \"timedelta\" in row.keys(): row[\"timedelta\"]",
"data using DEFAULT_PARSE. Examine DEFAULT_PARSE as an example parameter to pass to attach_exif(),",
"update() except TypeError: pass plt.rc(\"font\", **{\"size\": 8}) plt.rcParams[\"keymap.back\"] = \"left, backspace\" fig =",
"os.path.exists(export_dir): os.makedirs(export_dir) timer = (len(jpg_data) // 10, time.time()) for i, jpg in enumerate(jpg_data):",
"in lo_to_hi} self.user_edits = {**self.user_edits, **new_edits} elif event.key == \",\": for i in",
"preprocess = CROP_EQUALIZE else: preprocess = CROP_CLONE_EQUALIZE output = [] timer = (len(jpg_data)",
"/ thresholding. \"\"\" if not threshold: thresh_init = False if not clone: preprocess",
"len(self.jpg_data) self.dt_present = \"datetime\" in self.jpg_data[0].keys() h, w = jpg_data[0][\"shape\"] self.plt_vals[\"ceiling\"] = h",
"i, row in enumerate(self.jpg_data): write_row = row.copy() if row[\"selected\"]: if self.dt_present: dt_ISO =",
"= str(obj) return '\"' + string + '\"' if \",\" in string else",
"new_var): \"\"\"Finds the difference between the current and previous variable. Requires a list",
"int(round(xdata)) if i != self.pano_i: self.pano_i = i array = np.array(range(i - 2,",
"== \"z\": self.press = [NEG_NUM, i] elif event.key == \"x\": self.press = [BIG_NUM,",
"= test[e:f, g:h] diff = cv2.absdiff(test, image) choose.append((sum(cv2.sumElems(diff)), direct, test)) choose.sort() if choose:",
"BIG_NUM = int(1e9) NEG_NUM = -0.1 RESP_NUM = 3.5 def PARSE_DT(raw): \"\"\"Default parser",
"= mod[y1:y2, x1:x2] mod = cv2.cvtColor(mod, cv2.COLOR_BGR2RGB) ax_mod.imshow(mod) fig.canvas.draw_idle() rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)",
"if clone_to else False) process_options = {\"crop\": crop, \"clone\": clone} print(\"Started processing...\") output",
"metric between images. Works hierarchically to preform image cropping, cloning, and histogram equalization",
"interactive plot to select images for export.\") help(Cam.plot) cam.plot() print(\"→ Save once again,",
"threshold : int, in range(0, 256) Parameter to be passed to the cv2.threshold()",
"mem.clone_tuple = False mem.clone_directs = False if cr_ig: cr_corn = (0, H, 0,",
"method. Takes two images, then finds their absolute difference. A simple threshold is",
"event.key == \"x\": self.press = [BIG_NUM, i] elif event.key == \",\": self.press =",
"datetime import datetime as dt, timedelta as td from matplotlib import pyplot as",
"lo_W, hi_W = (0 - W // scale), (W + W // scale)",
"else: img = cv2.imread(self.jpg_data[n][\"thumbpath\"]) self.buffer[0] = self.buffer[0][1:] + [n] self.buffer[1] = self.buffer[1][1:] +",
".sav file. update_counts() Updates jpg_data attribute with new counts. update_events() Updates jpg_data attribute",
"dt.strftime( row[\"datetime\"], \"%Y%m%dT%H%M%S\" ) else: dt_ISO = str(i) new_name = \"_\".join((dt_ISO, row[\"filename\"])) new_path",
"generate_clone_tuples(cl_corn, direct) a, b, c, d = tups[1] if not (a < 0",
"input a new directory path.\") def csv_safe(obj): \"\"\"Puts quotes around strings with commas",
"row[\"user_edit\"] = False row[\"trans_edit\"] = False new_count = row[\"count\"] if row[\"med_diff\"] > self.plt_vals[\"trans_thresh\"]:",
"= row[var] row[new_var] = curr - prev prev = curr def mark_edits(self, i,",
"> W or max_x < 0) return tuple(map( lambda x: int(round(x)), (min_y, max_y,",
"positive, odd number. min_area : int, unused Only used in the CONTOURS() function,",
"to be passed to the cv2.medianBlur() function. Default is 11. Must be positive,",
"count = 0 for cnt in contours: area = cv2.contourArea(cnt) if area >",
"if os.path.isdir(directory): return directory else: print(\"Directory does not exist, would you like to",
"string.digits) return dt.strptime(str_, \"%Y%m%d%H%M%S\") def SORT_BY_DT(row): \"\"\"Default sort for construct_jpg_data(). \"\"\" return row[\"datetime\"]",
"Returns ------- tuple Format is (crop, clone_to, clone_directs). The crop_tuple variable can be",
"SPECIFIC FUNCTIONS def find_imgs(dirpath, img_type=(\".jpg\", \".jpeg\")): \"\"\"Walks directory path, finding all files ending",
"object is desired for a load() method call. resp_var : str, optional A",
"1) kmeans = KMeans(n_clusters=3).fit(X) night_indices = [np.argmin(kmeans.cluster_centers_), np.argmax(kmeans.cluster_centers_)] for n, index in enumerate(kmeans.labels_):",
"(\"NIGHT\", 0.02, -1, 50, self.plt_vals[\"night_mult\"], \"%.1f\") ] def update(): self.update_counts() self.update_events() draw() def",
"array: if n in self.buffer[0]: ind = self.buffer[0].index(n) img = self.buffer[1][ind] self.buffer[0].append(self.buffer[0].pop(ind)) self.buffer[1].append(self.buffer[1].pop(ind))",
"return i def generate_clone_tuples(clone_to, fill_from): \"\"\"Loops through jpg_data, reading filepaths and attaching EXIF",
"cv2.absdiff(curr, prev) _, mask = cv2.threshold( difference, threshold, 255, cv2.THRESH_BINARY) return cv2.countNonZero(mask) #",
"\"B\": (1, 1, 0, 0), \"R\": (0, 0, 1, 1), \"L\": (0, 0,",
"} COL_ORDER = [ \"old_name\", \"old_path\", \"filename\", \"filepath\", \"shape\", \"datetime\", \"24hr\", \"is_night\", \"timedelta\",",
"data attached. \"\"\" output = [] for deep_row in jpg_data: row = deep_row.copy()",
"is (y1, y2, x1, x2), just like slicing images as np.arrays. fill_from :",
"= px_count / 2 for i, count in enumerate(hist): tally += count if",
"inputted, but includes variables denoting selection, edits, event, etc. plot_params : dictionary Parameters",
"i, jpg in enumerate(jpg_data): if not i % timer[0] and i: stop_watch(i, timer)",
"= False self.buffer = [[None] * 64, [None] * 64] self.recent_folder = os.path.expanduser(\"~\")",
"called, the resulting white pixels are counted toward response (movement). Very noisy, but",
"here to shorten the process_jpgs() function. min_area : int, unused Only used in",
"images don\"t have a datetime, but do have a variable for sequence. process_options",
"= cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img = cv2.cv2.equalizeHist(gray) stack.append(img) min_y = min(img.shape[0] for img in",
"for i, deep_row in enumerate(jpg_data): row = deep_row.copy() if i == 0: jpg",
"cv2.medianBlur(difference, ksize) _, mask = cv2.threshold( blurred, threshold, 255, cv2.THRESH_BINARY) return cv2.countNonZero(mask) #",
"find_imgs(dirpath, img_type=(\".jpg\", \".jpeg\")): \"\"\"Walks directory path, finding all files ending in img_type. Parameters",
"in \"zx,\": i = int(round(event.xdata)) low, high = sorted((self.press[1], i)) lo_to_hi = range(max(0,",
"\"filename\", \"filepath\", \"shape\", \"datetime\", \"24hr\", \"is_night\", \"timedelta\", \"td_minutes\", \"median\", \"med_diff\", \"count\", \"new_count\", \"selected\",",
"used in the CONTOURS() function, but retained here to shorten the process_jpgs() function.",
"changes with ksize), mask and sum. def BLURRED(curr, prev, threshold, ksize=11, min_area=None): \"\"\"Useful,",
"omitted if a empty Cam() object is desired for a load() method call.",
"KeyError: pass on_slide(1) plt.show() cv2.destroyAllWindows() if __name__ == \"__main__\": print(\"→ Please input a",
"in d.items(): if k != \"days\": d[k] = str(v).rjust(2, \"0\") return fmt.format(**d) def",
"c h_or_w = np.array([h, h, w, w]) clone_from = clone_to + (h_or_w *",
"image.copy() (a, b, c, d), (e, f, g, h) = tups test[a:b, c:d]",
"= curr else: nudge = int(self.plt_vals[\"smooth_time\"]) master_set = set() for i, row in",
"img = cv2.cv2.equalizeHist(gray) stack.append(img) min_y = min(img.shape[0] for img in stack) pano =",
"( curr[\"new_count\"] > self.plt_vals[\"resp_thresh\"]) prev = curr if self.dt_present: for move in (1,",
"reduce noise. After thresholding, contours are drawn around the resulting white pixels. If",
"can be changed if images don\"t have a datetime, but do have a",
"is called, the resulting white pixels are counted toward response (movement). Very noisy,",
"\"24hr\") # meds = extract_var(self.jpg_data, \"median\") X = np.array(day_hr).reshape(-1, 1) kmeans = KMeans(n_clusters=3).fit(X)",
"for i in lo_to_hi: self.user_edits.pop(i, None) self.press = [None, None] update() except TypeError:",
"/ h new_w = rint(w * scale) new_h = rint(h * scale) return",
"prev = self.jpg_data[0][var] for row in self.jpg_data: curr = row[var] row[new_var] = curr",
"row in enumerate(self.jpg_data): row[\"user_edit\"] = False row[\"trans_edit\"] = False new_count = row[\"count\"] if",
"eclick.ydata x2, y2 = erelease.xdata, erelease.ydata cr_corn, cr_ig = safe_corners(crop_RS.geometry) cl_corn, cl_ig =",
"f.lower().endswith(img_type) ) for filename in found: filepath = os.path.join(dir_, filename) output.append({ \"filename\": filename,",
"image to be differenced. threshold : int, in range(0, 256) Parameter to be",
"cv2.medianBlur(difference, ksize) _, mask = cv2.threshold( blurred, threshold, 255, cv2.THRESH_BINARY) contours, _ =",
"move < 0 prev = self.jpg_data[-is_neg] for i in range(-is_neg, (self.length * move)",
"from_path = jpg[\"filepath\"] to_path = os.path.join(export_dir, jpg[\"filename\"]) im = cv2.imread(from_path) resized = resize_long_edge(im,",
"** RESP_NUM self.plt_vals[key] = mod self.sliders[slider_key].valtext.set_text(\"%.2e\" % mod) else: self.plt_vals[key] = self.sliders[slider_key].val update()",
"desired EXIF data attached. \"\"\" output = [] for deep_row in jpg_data: row",
"plot() method. A simply initialization could be: Cam(construct_jpg_data()). After filtering images with the",
"def __init__(self): pass def rint(n): return round(int(n)) def sort_cols(var_name): if var_name in COL_ORDER:",
"new counts. update_events() Updates jpg_data attribute with new events. \"\"\" def __init__(self, jpg_data=False,",
"list of dictionaries Each row contains everything that is needed to feed a",
"k, v in row.items()} for row in self.jpg_data] for row in temp_data: if",
"mem.clone_directs # FRAME DIFFERENCING METHODS # Bare-bones. Take difference, threshold, and sum the",
"self.plt_vals[key] = mod self.sliders[slider_key].valtext.set_text(\"%.2e\" % mod) else: self.plt_vals[key] = self.sliders[slider_key].val update() # Displays",
"function. method : function, {SIMPLE, BLURRED, COUNTOURS} Determines the frame differencing method to",
"+ '\"' if \",\" in string else string def to_24_hour(datetime): \"\"\"Converts datetime.datetime type",
"difference = cv2.absdiff(curr, prev) _, mask = cv2.threshold( difference, threshold, 255, cv2.THRESH_BINARY) return",
"to initialize. # This way, someone can load() older, processed data. if jpg_data:",
"First, images are identified as being selected or not. Then, events are lumped",
"selected or not. Then, events are lumped based on time since last image",
"= max(0, min(geometry[0, :])) max_y = min(H, max(geometry[0, :])) min_x = max(0, min(geometry[1,",
"for row in temp_data: if \"datetime\" in row.keys(): row[\"datetime\"] = dt.strftime( row[\"datetime\"], \"%Y-%m-%d",
"as gridspec # CONSTANTS BIG_NUM = int(1e9) NEG_NUM = -0.1 RESP_NUM = 3.5",
"def plot(self): \"\"\"Interactive plot used to select images for export. QUICK GUIDE: c",
"image. Smaller sizes speed up performance, but decrease acuity. \"\"\" if not os.path.exists(export_dir):",
"for i, curr in enumerate(self.jpg_data): prev[\"selected\"] = ( prev[\"new_count\"] > self.plt_vals[\"resp_thresh\"] or curr[\"new_count\"]",
"plot is laggy, use resize_with_exif() on your jpg_data list, and specify the export",
"self.length) + 0.5, -BIG_NUM, BIG_NUM, where=[r[\"trans_edit\"] or r[\"user_edit\"] for r in self.jpg_data], facecolor=\"#D8BFAA\",",
"answer.lower() in (\"y\", \"yes\"): os.makedirs(directory) return directory print(\"Please input a new directory path.\")",
"max(0, min(geometry[1, :])) max_x = min(W, max(geometry[1, :])) ignore = (min_y > H",
"white pixels. If the contours are above the min_area parameter, they are counted",
"curr = self.jpg_data[i] boo = (not curr[\"selected\"] and prev[\"selected\"] and not (prev[\"user_edit\"] and",
"ALL EDITS. v - Press for EQUALIZED image (for dark images). \"\"\" try:",
"others. Parameters ---------- curr : numpy.ndarray Image array, typically from cv2.imread(). One of",
"= True self.jpg_data[i-1][kind] = True def update_counts(self): \"\"\"Updates jpg_data with new counts (response",
"to the cv2.threshold() function. ksize : int, unused Used in the BLURRED() and",
": dictionary, optional Passes along paramters to the process_jpgs() function. By default, no",
"decreases sensitivity. Returns ------- list of dictionaries Same as incoming jpg_data, but now",
"5, \"minspany\": 5, \"spancoords\": \"pixels\", \"interactive\": True } # GENERAL FUNCTIONS class Mem():",
"the differenced image is blurred to reduce noise. After thresholding, the resulting white",
"be fed into the Cam() class for response filtering. Parameters ---------- jpg_data :",
"(new_w, new_h)) def generate_thumbnails(jpg_data, export_dir, long_edge=1024): \"\"\"Formats a timedelta object as a string.",
"try: row[\"count\"] = method(curr, prev, threshold, ksize, min_area) except cv2.error as inst: if",
"tuples Matches the format ((clone_to), (clone_from)). For simplicity, use generate_clone_tuples() to generate this",
"based on [i]ndex. \"\"\" if i == 0: self.jpg_data[i][kind] = True else: self.jpg_data[i][kind]",
"nudge = int(self.plt_vals[\"smooth_time\"]) master_set = set() for i, row in enumerate(self.jpg_data): if row[\"selected\"]:",
"response (movement). Works very well, little noise; slower than others. Parameters ---------- curr",
"update() # Displays last two and next two images from response spike. def",
"def attach_exif(jpg_data, parse_tags=DEFAULT_PARSE): \"\"\"Loops through jpg_data, reading filepaths and attaching EXIF data. Parameters",
"i] if event.key in \"zxc,\": image_pano(event.xdata) elif event.key == \"v\": self.toggle = not",
"slider value). \"\"\" self.pano_i = 0 prev = self.jpg_data[0] for i, curr in",
"attach_exif(), if more data is desired from EXIF tags. Returns ------- list of",
"def safe_corners(geometry): min_y = max(0, min(geometry[0, :])) max_y = min(H, max(geometry[0, :])) min_x",
"area return count # JPG PROCESSING def process_jpgs( jpg_data, method=CONTOURS, crop=False, clone=False, threshold=False,",
"are applied. \"\"\" for i, row in enumerate(self.jpg_data): row[\"user_edit\"] = False row[\"trans_edit\"] =",
"but now with the median image tone and a count variable, which respresents",
"ABORTED!\\n\" \"Not all images are of same size, \" \"consider using the crop",
"in row.items()} for row in self.jpg_data] for row in temp_data: if \"datetime\" in",
"stack) pano = np.hstack([img[:min_y, :] for img in stack]) h, w, *_ =",
": str, optional If the interactive plot is laggy, use resize_with_exif() on your",
"fig.canvas.mpl_connect(\"button_press_event\", on_click) ax.fill_between( np.arange(0, self.length) + 0.5, -BIG_NUM, 0, facecolor=\"white\", alpha=0.75, zorder=2) try:",
"self.plt_vals[\"night_mult\"] * row[\"is_night\"]) row[\"new_count\"] = new_count for i, shift in self.user_edits.items(): self.jpg_data[i][\"new_count\"] =",
"input(\"Y / N > \") if answer.lower() in (\"y\", \"yes\"): return filename elif",
"\"median\" can be used to plot jpgs without processing them first. thumb_dir :",
"2, height_ratios=[1, 1.25]) fig = plt.figure() fig.canvas.set_window_title(\"Crop and Clone Preview\") ax_crop = fig.add_subplot(gs[0,",
"> self.plt_vals[\"resp_thresh\"] or curr[\"new_count\"] > self.plt_vals[\"resp_thresh\"]) if i == self.length-1: curr[\"selected\"] = (",
"strfdelta(td(seconds=total - elapsed), \"{days}:{hours}:{minutes}:{seconds}\") print(f\"{progress}% done. {remain} left.\") def strfdelta(tdelta, fmt): \"\"\"Formats a",
"filepaths before being passed on to frame differencing methods that generate a response",
"f.write(json.dumps(self.user_edits)) def load(self, filename): \"\"\"Loads a .sav file, the Cam() object is now",
"answer = input(\"Y / N > \") if answer.lower() in (\"y\", \"yes\"): os.makedirs(directory)",
"from EXIF data using DEFAULT_PARSE. Examine DEFAULT_PARSE as an example parameter to pass",
"np.arrays. clone : pair of tuples, optional Matches the format ((clone_to), (clone_from)). For",
"if not thresh_init: threshold = row[\"median\"]*1.05 try: row[\"count\"] = method(curr, prev, threshold, ksize,",
"time.second / 3600 def extract_var(data, var): \"\"\"Returns a list of values corresponding to",
"data. \"\"\" jpg_paths = find_imgs(dirpath) print(f\"{len(jpg_paths)} images found.\") jpg_data = attach_exif(jpg_paths, parse_tags) jpg_data.sort(key=sort_key)",
"or not. Then, events are lumped based on time since last image (SMOOTH",
"curr output.append(row) return output def construct_jpg_data( dirpath, parse_tags=DEFAULT_PARSE, sort_key=SORT_BY_DT, process_options={} ): \"\"\"Performs all",
"\"%.1f\"), (\"SMOOTH\", 0.04, 0, 10, self.plt_vals[\"smooth_time\"], \"%.1f\"), (\"NIGHT\", 0.02, -1, 50, self.plt_vals[\"night_mult\"], \"%.1f\")",
"with specified cloning and equalization. Parameters ---------- image : numpy.ndarray Image array, typically",
"optional By default, finds JPG image types, but can be changed if camera",
"This is the last step before the jpg_data list can be fed into",
"sort_key=SORT_BY_DT, process_options={} ): \"\"\"Performs all necessary steps to make jpg_data feedable to Cam().",
"the clone_to area. Neighboring pixels from \"[A]bove,\" \"[B]elow,\" \"[R]ight,\" and \"[L]eft\" are used",
"for export.\") help(Cam.plot) cam.plot() print(\"→ Save once again, so changes are recorded.\") cam.save(input_filename())",
"str(i) new_name = \"_\".join((dt_ISO, row[\"filename\"])) new_path = os.path.join(directory, new_name) write_row[\"filename\"] = new_name write_row[\"filepath\"]",
"0 } DIRECTION_MULTS = { \"A\": (-1, -1, 0, 0), \"B\": (1, 1,",
"\"button\": [1, 3], \"minspanx\": 5, \"minspany\": 5, \"spancoords\": \"pixels\", \"interactive\": True } #",
"image. \"\"\" px_count = image.shape[0] * image.shape[1] hist = cv2.calcHist([image], [0], None, [256],",
"(e, f, g, h) = tups test[a:b, c:d] = test[e:f, g:h] diff =",
"user edits are applied. \"\"\" for i, row in enumerate(self.jpg_data): row[\"user_edit\"] = False",
"plot to select images for export.\") help(Cam.plot) cam.plot() print(\"→ Save once again, so",
"\"days\": d[k] = str(v).rjust(2, \"0\") return fmt.format(**d) def resize_long_edge(im, size): h, w, *_",
") self.dt_present = True else: self.dt_present = False if \"timedelta\" in row.keys(): try:",
"only sums drawn contours over given limit. def CONTOURS(curr, prev, threshold, ksize=11, min_area=100):",
"the crop parameter.\\n\" f\"Try crop={tup}.\") return tup else: print(inst) prev = curr output.append(row)",
"new_name = \"_\".join((dt_ISO, row[\"filename\"])) new_path = os.path.join(directory, new_name) write_row[\"filename\"] = new_name write_row[\"filepath\"] =",
"clone_to, clone_directs). The crop_tuple variable can be fed directly into process_jpgs(). Then, use",
"noise; slower than others. Parameters ---------- curr : numpy.ndarray Image array, typically from",
":])) ignore = (min_y > H or max_y < 0 or min_x >",
"mask and sum. def BLURRED(curr, prev, threshold, ksize=11, min_area=None): \"\"\"Useful, mid-grade frame differencing",
"all necessary steps to make jpg_data feedable to Cam(). Parameters ---------- dirpath :",
"2][\"filepath\"])) clone = (generate_clone_tuples(clone_to, directs[0]) if clone_to else False) process_options = {\"crop\": crop,",
"(\"y\", \"yes\"): return filename elif filename: return filename def input_directory(): while True: directory",
"False mem.clone_tuple = False mem.clone_directs = False def update(event): if crop_RS.active: crop_RS.update() if",
"= size / w else: scale = size / h new_w = rint(w",
"use generate_clone_tuples() to generate this object. \"\"\" (a, b, c, d), (e, f,",
"can be used to plot jpgs without processing them first. thumb_dir : str,",
"self.mark_edits(i, \"trans_edit\") if self.dt_present: new_count *= 1 + ( self.plt_vals[\"night_mult\"] * row[\"is_night\"]) row[\"new_count\"]",
"\"(-209:Sizes\" in str(inst): (a, b), (c, d) = curr.shape[:2], prev.shape[:2] h, w =",
"temp_dict = json.loads(next(f)) for row in temp_data: if \"datetime\" in row.keys(): row[\"datetime\"] =",
"facecolor=\"#F00314\") self.lines[\"count\"] = ax.fill_between( range(self.length), 0, np_counts, facecolor=\"black\") self.lines[\"threshold\"] = ax.axhline( self.plt_vals[\"resp_thresh\"], color=\"#14B37D\")",
": str Path to an image-containing directory. img_type : tuple, optional By default,",
"and curr[\"user_edit\"])) if boo: if not is_neg: lapse = curr[\"td_minutes\"] else: lapse =",
"\"left, backspace\" fig = plt.figure() ax = fig.add_subplot(111) fig.canvas.set_window_title(\"Response Filtering\") fig.subplots_adjust(0.07, 0.18, 0.97,",
"= False if not clone: preprocess = CROP_EQUALIZE else: preprocess = CROP_CLONE_EQUALIZE output",
"os.path.join(export_dir, jpg[\"filename\"]) im = cv2.imread(from_path) resized = resize_long_edge(im, long_edge) cv2.imwrite(to_path, resized) piexif.transplant(from_path, to_path)",
"\"\"\"Marks which photos to label as edited based on [i]ndex. \"\"\" if i",
"update(): self.update_counts() self.update_events() draw() def draw(): for name in self.lines.keys(): self.lines[name].remove() np_counts =",
"np.array([h, h, w, w]) clone_from = clone_to + (h_or_w * mults) return (tuple(clone_to),",
"mem = Mem() mem.crop_tuple = False mem.clone_tuple = False mem.clone_directs = False def",
"\"age\": 22}, {\"name\": \"Eve\", \"age\": 7}] >>> extract_var(data=foo, var=\"name\") [\"Shane\", \"Eve\"] \"\"\" return",
"if event.key in \"zx\": new_edits = {i: self.press[0] for i in lo_to_hi} self.user_edits",
"datetime as dt, timedelta as td from matplotlib import pyplot as plt from",
"curr = row[var] row[new_var] = curr - prev prev = curr def mark_edits(self,",
"def extract_var(data, var): \"\"\"Returns a list of values corresponding to a variable name.",
"hi_W) axe.set_ylim(hi_H, lo_H) ax_crop.imshow(rgb) ax_clone.imshow(rgb) ax_mod.imshow(rgb) plt.connect(\"draw_event\", update) plt.show() return mem.crop_tuple, mem.clone_tuple, mem.clone_directs",
"\"med_diff\", \"count\", \"new_count\", \"selected\", \"user_edit\", \"trans_edit\" ] RS_PARAMS = { \"drawtype\": \"box\", \"useblit\":",
"ksize=11, min_area=None): \"\"\"Useful, mid-grade frame differencing method. Takes two images, then finds their",
"in self.jpg_data: if thumb_dir is not None: row[\"thumbpath\"] = os.path.join(thumb_dir, row[\"filename\"]) else: row[\"thumbpath\"]",
"256) Parameter to be passed to the cv2.threshold() function. ksize : int, unused",
"row[\"24hr\"] = to_24_hour(row[\"datetime\"]) row[\"td_minutes\"] = round( row[\"timedelta\"].total_seconds() / 60, 2) day_hr = extract_var(self.jpg_data,",
"for i, row in enumerate(self.jpg_data): if row[\"selected\"]: for func in (operator.add, operator.sub): for",
"self.jpg_data], facecolor=\"#D8BFAA\", alpha=0.5) self.lines[\"selected\"] = ax.fill_between( np.arange(0, self.length) + 0.5, -BIG_NUM, BIG_NUM, where=extract_var(self.jpg_data,",
"[] for direct in (\"A\", \"B\", \"R\", \"L\"): tups = generate_clone_tuples(cl_corn, direct) a,",
"the two images for the absolute difference to be taken. prev : numpy.ndarray",
": numpy.ndarray Image array, typically from cv2.imread(). crop : tuple Format is (y1,",
"= [ \"old_name\", \"old_path\", \"filename\", \"filepath\", \"shape\", \"datetime\", \"24hr\", \"is_night\", \"timedelta\", \"td_minutes\", \"median\",",
"(1 / RESP_NUM)) temp_data = json.loads(next(f)) temp_dict = json.loads(next(f)) for row in temp_data:",
"self.dt_present: new_count *= 1 + ( self.plt_vals[\"night_mult\"] * row[\"is_night\"]) row[\"new_count\"] = new_count for",
"return COL_ORDER.index(var_name) else: return BIG_NUM def input_filename(): while True: filename = input(\"FILEPATH >",
"jpg_data list, and specify the export directory here. These smaller images will be",
"(amount changes with ksize), mask and sum. def BLURRED(curr, prev, threshold, ksize=11, min_area=None):",
"var): \"\"\"Returns a list of values corresponding to a variable name. >>> foo",
"timer[0] and i: stop_watch(i, timer) from_path = jpg[\"filepath\"] to_path = os.path.join(export_dir, jpg[\"filename\"]) im",
"IMAGE PREPROCESSING def CROPPER(image, crop): \"\"\"Returns a cropped image. Parameters ---------- image :",
"be differenced. threshold : int, in range(0, 256) Parameter to be passed to",
"select images for export. save(filename) Dumps a JSON object as a .sav file.",
"new_name) write_row[\"filename\"] = new_name write_row[\"filepath\"] = new_path write_row[\"old_name\"] = row[\"filename\"] write_row[\"old_path\"] = row[\"filepath\"]",
"// 2, h // 2))) cv2.waitKey(1) def on_click(event): if event.dblclick and event.xdata is",
"= cv2.contourArea(cnt) if area > min_area: count += area return count # JPG",
"matplotlib import pyplot as plt from matplotlib.widgets import Slider, RectangleSelector import matplotlib.gridspec as",
"tally += count if tally > threshold: return i def generate_clone_tuples(clone_to, fill_from): \"\"\"Loops",
"* w * 0.02 self.plt_vals[\"resp_thresh\"] = self.plt_vals[\"ceiling\"] / 2 self.attach_diffs(\"median\", \"med_diff\") for row",
"choose else: mem.clone_tuple = False mem.clone_directs = False if cr_ig: cr_corn = (0,",
"min_y = min(img.shape[0] for img in stack) pano = np.hstack([img[:min_y, :] for img",
"release to DECREASE response value to 0. , - Hold and release to",
"list of dictionaries Requires that \"filepath\" and \"filename\" is in dictionary keys, which",
"for dir_, _, files in os.walk(dirpath): if \"_selected\" not in dir_: found =",
"that is needed to feed a Cam() object with its initial data. \"\"\"",
"// 10, time.time()) for i, deep_row in enumerate(jpg_data): row = deep_row.copy() if i",
"prev) _, mask = cv2.threshold( difference, threshold, 255, cv2.THRESH_BINARY) return cv2.countNonZero(mask) # Difference,",
"False row[\"user_edit\"] = False row[\"trans_edit\"] = False if self.dt_present: self.attach_diffs(\"datetime\", \"timedelta\") for row",
"Day to night transitions are filtered out based on slider. Counts taken at",
"row[\"is_night\"]) row[\"new_count\"] = new_count for i, shift in self.user_edits.items(): self.jpg_data[i][\"new_count\"] = shift self.mark_edits(i,",
"the median image tone and a count variable, which respresents how many pixels",
"is_neg = move < 0 prev = self.jpg_data[-is_neg] for i in range(-is_neg, (self.length",
"not to lose any prior work. Attributes ---------- jpg_data : list of dictionaries",
"class Mem(): def __init__(self): pass def rint(n): return round(int(n)) def sort_cols(var_name): if var_name",
"process_jpgs() function. By default, no options are specified. Make sure that this parameter",
"= [0, i] if event.key in \"zxc,\": image_pano(event.xdata) elif event.key == \"v\": self.toggle",
"f.write(\",\".join(variables) + \"\\n\") f.write(\",\".join(csv_safe(row[v]) for v in variables)) else: raise ValueError(\"No images selected",
"enumerate(kmeans.labels_): self.jpg_data[n][\"is_night\"] = index in night_indices def save(self, filename): \"\"\"Dumps a JSON object",
"(min_y, max_y, min_x, max_x))), ignore def RS_event(eclick, erelease): x1, y1 = eclick.xdata, eclick.ydata",
"else: mem.crop_tuple = cr_corn y1, y2, x1, x2 = cr_corn mod = mod[y1:y2,",
"used as a response, but alternatives like \"median\" can be used to plot",
"as f: f.write(json.dumps(self.plt_vals) + \"\\n\") f.write(json.dumps(temp_data) + \"\\n\") f.write(json.dumps(self.user_edits)) def load(self, filename): \"\"\"Loads",
"a grayscale image. \"\"\" px_count = image.shape[0] * image.shape[1] hist = cv2.calcHist([image], [0],",
"cv2.THRESH_BINARY) return cv2.countNonZero(mask) # Difference, blur (amount changes with ksize), mask and sum.",
"plot function. class Cam(): \"\"\" A class used to store, plot, filter, and",
"Smaller sizes speed up performance, but decrease acuity. \"\"\" if not os.path.exists(export_dir): os.makedirs(export_dir)",
"mem.clone_directs = False def update(event): if crop_RS.active: crop_RS.update() if clone_RS.active: clone_RS.update() def safe_corners(geometry):",
"= image.copy() (a, b, c, d), (e, f, g, h) = tups test[a:b,",
"x2 = cr_corn mod = mod[y1:y2, x1:x2] mod = cv2.cvtColor(mod, cv2.COLOR_BGR2RGB) ax_mod.imshow(mod) fig.canvas.draw_idle()",
"in night_indices def save(self, filename): \"\"\"Dumps a JSON object with jpg_data, plot_params, and",
"aids in histogram equalization. Parameters ---------- clone_to : tuple Format is (y1, y2,",
"specified. Make sure that this parameter is mappable. Returns ------- list of dictionaries",
"\"v\": self.toggle = not self.toggle image_pano(event.xdata) elif event.key == \".\": self.user_edits = {}",
"if crop_RS.active: crop_RS.update() if clone_RS.active: clone_RS.update() def safe_corners(geometry): min_y = max(0, min(geometry[0, :]))",
"0, 0), \"B\": (1, 1, 0, 0), \"R\": (0, 0, 1, 1), \"L\":",
"= safe_corners(crop_RS.geometry) cl_corn, cl_ig = safe_corners(clone_RS.geometry) mod = image.copy() if not cl_ig: mem.clone_tuple",
"if images don\"t have a datetime, but do have a variable for sequence.",
"None] update() except TypeError: pass plt.rc(\"font\", **{\"size\": 8}) plt.rcParams[\"keymap.back\"] = \"left, backspace\" fig",
"parameters. Parameters ---------- image : numpy.ndarray Image array, typically from cv2.imread(). Returns -------",
"low, high = sorted((self.press[1], i)) lo_to_hi = range(max(0, low), min(self.length, high+1)) if event.key",
"string import sys import time import cv2 import piexif import numpy as np",
"ax.set_ylabel(\"Response\") plt.yticks(rotation=45) for name in (\"count\", \"threshold\", \"selected\", \"edited\"): self.lines[name] = ax.axhline() for",
"\"spancoords\": \"pixels\", \"interactive\": True } # GENERAL FUNCTIONS class Mem(): def __init__(self): pass",
"long_edge) cv2.imwrite(to_path, resized) piexif.transplant(from_path, to_path) # SPECIFIC FUNCTIONS def find_imgs(dirpath, img_type=(\".jpg\", \".jpeg\")): \"\"\"Walks",
"Image array, typically from cv2.imread(). One of the two images for the absolute",
"Updates jpg_data attribute with new counts. update_events() Updates jpg_data attribute with new events.",
"Please input a file path for an initial save.\") cam.save(input_filename()) print(\"→ Use the",
"plot jpgs without processing them first. thumb_dir : str, optional If the interactive",
"# FRAME DIFFERENCING METHODS # Bare-bones. Take difference, threshold, and sum the mask.",
"contours are above the min_area parameter, they are counted as a response (movement).",
"resp_var : str, optional A key found in jpg_data, typically the \"count\" variable",
"dictionaries Each row contains everything that is needed to feed a Cam() object",
"Matches the format for the clone parameter in process_jpgs(). \"\"\" clone_to = np.array(clone_to)",
"and equalization. Parameters ---------- image : numpy.ndarray Image array, typically from cv2.imread(). crop",
"= CROPPER(image, crop) return cv2.equalizeHist(image) def crop_clone_preview(image): \"\"\"Interactive viewer to quickly get crop",
"del choose else: mem.clone_tuple = False mem.clone_directs = False if cr_ig: cr_corn =",
"between a photo and its previous, after preprocessing / thresholding. \"\"\" if not",
"GUIDE: c - Hold to VIEW IMAGES in gallery. x - Hold and",
"to Cam(). Parameters ---------- dirpath : str Path to an image-containing directory. parse_tags",
"be called so as not to lose any prior work. Attributes ---------- jpg_data",
"jpg_data, but now with the median image tone and a count variable, which",
"or r[\"user_edit\"] for r in self.jpg_data], facecolor=\"#D8BFAA\", alpha=0.5) self.lines[\"selected\"] = ax.fill_between( np.arange(0, self.length)",
"crop) return cv2.equalizeHist(image) def crop_clone_preview(image): \"\"\"Interactive viewer to quickly get crop and clone",
"y2, x1, x2), just like slicing images as np.arrays. clone : pair of",
"items. export(directory) Exports selected images and a .csv file. load(filename) Loads a .sav",
"within the clone_to area. Neighboring pixels from \"[A]bove,\" \"[B]elow,\" \"[R]ight,\" and \"[L]eft\" are",
"64] self.recent_folder = os.path.expanduser(\"~\") # Cam objects don\"t need to have data to",
"dir_, _, files in os.walk(dirpath): if \"_selected\" not in dir_: found = (",
"_, mask = cv2.threshold( difference, threshold, 255, cv2.THRESH_BINARY) return cv2.countNonZero(mask) # Difference, blur",
"Cam() object is now identical to the last. \"\"\" with open(filename, \"r\") as",
"dt.strptime( row[\"datetime\"], \"%Y-%m-%d %H:%M:%S\" ) self.dt_present = True else: self.dt_present = False if",
"easily provided by find_imgs() prior to this function. method : function, {SIMPLE, BLURRED,",
"[] for deep_row in jpg_data: row = deep_row.copy() tags = piexif.load(row[\"filepath\"]) for (key,",
"process_options={} ): \"\"\"Performs all necessary steps to make jpg_data feedable to Cam(). Parameters",
"self.press[0] is None: i = int(round(event.xdata)) if event.key == \"z\": self.press = [NEG_NUM,",
"Contains filenames and filepaths. \"\"\" output = [] for dir_, _, files in",
"h) = tups test[a:b, c:d] = test[e:f, g:h] diff = cv2.absdiff(test, image) choose.append((sum(cv2.sumElems(diff)),",
"\"selected\" in row.keys(): row[\"selected\"] = bool(row[\"selected\"]) self.jpg_data = temp_data.copy() self.length = len(self.jpg_data) self.user_edits",
"long_edge=1024): \"\"\"Formats a timedelta object as a string. Parameters ---------- jpg_data : list",
"list of dictionaries Same as jpg_data, but now with desired EXIF data attached.",
"write_data = [] for i, row in enumerate(self.jpg_data): write_row = row.copy() if row[\"selected\"]:",
"\"\"\"Returns a list of values corresponding to a variable name. >>> foo =",
"def image_pano(xdata): i = int(round(xdata)) if i != self.pano_i: self.pano_i = i array",
"Save once again, so changes are recorded.\") cam.save(input_filename()) print(\"→ Finally, choose a location",
"images are identified as being selected or not. Then, events are lumped based",
"been checked for bounds, unlike generate_clone_tuples). \"\"\" mem = Mem() mem.crop_tuple = False",
"high+1)) if event.key in \"zx\": new_edits = {i: self.press[0] for i in lo_to_hi}",
"event.key == \"v\": self.toggle = not self.toggle image_pano(event.xdata) elif event.key == \".\": self.user_edits",
"= not self.toggle image_pano(event.xdata) elif event.key == \".\": self.user_edits = {} def off_key(event):",
"would you like to overwrite it?\") answer = input(\"Y / N > \")",
"differencing method. Takes two images, then finds their absolute difference. Prior to thresholding,",
"self.length = len(self.jpg_data) self.user_edits = {int(k): v for k, v in temp_dict.items()} def",
"v for k, v in temp_dict.items()} def export(self, directory): \"\"\"Exports selected images and",
"cr_ig: cr_corn = (0, H, 0, W) mem.crop_tuple = False else: mem.crop_tuple =",
"find_imgs() prior to this function. export_dir : str Directory path that is used",
"class used to store, plot, filter, and export image data. Contains the heart",
"extract_var(data=foo, var=\"name\") [\"Shane\", \"Eve\"] \"\"\" return [x[var] for x in data] def stop_watch(i,",
"x1, x2 = cr_corn mod = mod[y1:y2, x1:x2] mod = cv2.cvtColor(mod, cv2.COLOR_BGR2RGB) ax_mod.imshow(mod)",
"more data is desired from EXIF tags. sort_key : function, optional By default,",
"self.plt_vals[\"trans_thresh\"], \"%.1f\"), (\"SMOOTH\", 0.04, 0, 10, self.plt_vals[\"smooth_time\"], \"%.1f\"), (\"NIGHT\", 0.02, -1, 50, self.plt_vals[\"night_mult\"],",
"cam.plot() print(\"→ Save once again, so changes are recorded.\") cam.save(input_filename()) print(\"→ Finally, choose",
"w, w]) clone_from = clone_to + (h_or_w * mults) return (tuple(clone_to), tuple(clone_from)) #",
"Format is (crop, clone_to, clone_directs). The crop_tuple variable can be fed directly into",
"(0 - W // scale), (W + W // scale) lo_H, hi_H =",
"the plot, save() and export() should be called so as not to lose",
"nighttime are multiplied based on slider. Manual user edits are applied. \"\"\" for",
"to reduce noise. After thresholding, contours are drawn around the resulting white pixels.",
"if not os.path.exists(export_dir): os.makedirs(export_dir) timer = (len(jpg_data) // 10, time.time()) for i, jpg",
"if row[\"selected\"]: for func in (operator.add, operator.sub): for j in range(nudge+1): ind =",
"facecolor=\"black\") self.lines[\"threshold\"] = ax.axhline( self.plt_vals[\"resp_thresh\"], color=\"#14B37D\") fig.canvas.draw_idle() def on_slide(val): for key in self.plt_vals.keys():",
"to frame differencing methods that generate a response metric. This is the last",
"= cv2.calcHist([image], [0], None, [256], [0, 256]) tally = 0 threshold = px_count",
"\"filepath\" is in dictionary keys, which is easily provided by find_imgs() prior to",
"for cloning out timestamps, aids in histogram equalization. Parameters ---------- clone_to : tuple",
"i] elif event.key == \",\": self.press = [0, i] if event.key in \"zxc,\":",
"IMAGES in gallery. x - Hold and release to INCREASE response value to",
"assign DEFAULT_PLOT_PARAMS to this attribute. Methods ------- attach_diffs(var, new_var) Finds the difference between",
"\"filename\" is in dictionary keys, which is easily provided by find_imgs() prior to",
"= cv2.absdiff(curr, prev) _, mask = cv2.threshold( difference, threshold, 255, cv2.THRESH_BINARY) return cv2.countNonZero(mask)",
"= False row[\"user_edit\"] = False row[\"trans_edit\"] = False if self.dt_present: self.attach_diffs(\"datetime\", \"timedelta\") for",
"d[\"hours\"], rem = divmod(tdelta.seconds, 3600) d[\"minutes\"], d[\"seconds\"] = divmod(rem, 60) for k, v",
"row in self.jpg_data: row[\"24hr\"] = to_24_hour(row[\"datetime\"]) row[\"td_minutes\"] = round( row[\"timedelta\"].total_seconds() / 60, 2)",
"curr def mark_edits(self, i, kind): \"\"\"Marks which photos to label as edited based",
"tuple Format is (crop, clone_to, clone_directs). The crop_tuple variable can be fed directly",
"KMeans(n_clusters=3).fit(X) night_indices = [np.argmin(kmeans.cluster_centers_), np.argmax(kmeans.cluster_centers_)] for n, index in enumerate(kmeans.labels_): self.jpg_data[n][\"is_night\"] = index",
"as not to lose any prior work. Attributes ---------- jpg_data : list of",
"def update(): self.update_counts() self.update_events() draw() def draw(): for name in self.lines.keys(): self.lines[name].remove() np_counts",
"def csv_safe(obj): \"\"\"Puts quotes around strings with commas in them. \"\"\" string =",
"try: self.jpg_data except AttributeError as inst: raise inst mod = self.plt_vals[\"resp_thresh\"] ** (1",
"tuple: cam = Cam(processed_data) print(\"→ Please input a file path for an initial",
"image as desired.\") crop, clone_to, directs = crop_clone_preview( cv2.imread(jpg_data[len(jpg_data) // 2][\"filepath\"])) clone =",
"curr.shape[:2], prev.shape[:2] h, w = min(a, c), min(b, d) tup = (0, h,",
"% timer[0] == 0: stop_watch(i, timer) jpg = cv2.imread(row[\"filepath\"], 0) curr = preprocess(jpg,",
"decreases sensitivity. \"\"\" difference = cv2.absdiff(curr, prev) blurred = cv2.medianBlur(difference, ksize) _, mask",
"CROP_CLONE_EQUALIZE(image, crop, clone): \"\"\"Returns a cropped image, with specified cloning and equalization. Parameters",
"to what is inputted, but includes variables denoting selection, edits, event, etc. plot_params",
"new_edits = {i: self.press[0] for i in lo_to_hi} self.user_edits = {**self.user_edits, **new_edits} elif",
"found: filepath = os.path.join(dir_, filename) output.append({ \"filename\": filename, \"filepath\": filepath }) return output",
"if self.dt_present: new_count *= 1 + ( self.plt_vals[\"night_mult\"] * row[\"is_night\"]) row[\"new_count\"] = new_count",
"row.keys(): row[\"datetime\"] = dt.strftime( row[\"datetime\"], \"%Y-%m-%d %H:%M:%S\") if \"timedelta\" in row.keys(): row[\"timedelta\"] =",
"erelease.xdata, erelease.ydata cr_corn, cr_ig = safe_corners(crop_RS.geometry) cl_corn, cl_ig = safe_corners(clone_RS.geometry) mod = image.copy()",
"_, mask = cv2.threshold( blurred, threshold, 255, cv2.THRESH_BINARY) return cv2.countNonZero(mask) # Like BLURRED,",
"used to select images for export. save(filename) Dumps a JSON object as a",
"c, d = tups[1] if not (a < 0 or b > H",
"spike. def image_pano(xdata): i = int(round(xdata)) if i != self.pano_i: self.pano_i = i",
"\"%.1f\") ] def update(): self.update_counts() self.update_events() draw() def draw(): for name in self.lines.keys():",
"inst mod = self.plt_vals[\"resp_thresh\"] ** (1 / RESP_NUM) SLIDER_PARAMS = [ (\"RESP\", 0.08,",
"tdelta.days} d[\"hours\"], rem = divmod(tdelta.seconds, 3600) d[\"minutes\"], d[\"seconds\"] = divmod(rem, 60) for k,",
":])) max_y = min(H, max(geometry[0, :])) min_x = max(0, min(geometry[1, :])) max_x =",
"and prev[\"selected\"] and not (prev[\"user_edit\"] and curr[\"user_edit\"])) if boo: if not is_neg: lapse",
"images as np.arrays. clone : pair of tuples, optional Matches the format ((clone_to),",
"- 2, i + 2)) while True: if any(n < 0 for n",
"img_type. Parameters ---------- dirpath : str Path to an image-containing directory. img_type :",
"COL_ORDER = [ \"old_name\", \"old_path\", \"filename\", \"filepath\", \"shape\", \"datetime\", \"24hr\", \"is_night\", \"timedelta\", \"td_minutes\",",
"None: row[\"thumbpath\"] = os.path.join(thumb_dir, row[\"filename\"]) else: row[\"thumbpath\"] = row[\"filepath\"] row[\"count\"] = row[self.resp_var] row[\"med_diff\"]",
"image = CROPPER(image, crop) return cv2.equalizeHist(image) def CROP_CLONE_EQUALIZE(image, crop, clone): \"\"\"Returns a cropped",
"in self.plt_vals.keys(): if key != \"ceiling\": slider_key = key[:key.find(\"_\")].upper() if key == \"resp_thresh\":",
"[None] * 64] self.recent_folder = os.path.expanduser(\"~\") # Cam objects don\"t need to have",
"= ax.fill_between( range(self.length), 0, np_counts, facecolor=\"black\") self.lines[\"threshold\"] = ax.axhline( self.plt_vals[\"resp_thresh\"], color=\"#14B37D\") fig.canvas.draw_idle() def",
"format ((clone_to), (clone_from)). For simplicity, use generate_clone_tuples() to generate this object. threshold :",
"cv2.namedWindow(\"Gallery\", cv2.WINDOW_NORMAL) cv2.imshow(\"Gallery\", cv2.resize(pano, (w // 2, h // 2))) cv2.waitKey(1) def on_click(event):",
"as incoming jpg_data, but now with the median image tone and a count",
"clone_RS = RectangleSelector( ax_clone, RS_event, **RS_PARAMS) ax_crop.set_title(\"Crop\") ax_clone.set_title(\"Clone\") ax_mod.set_title(\"Result\") for axe in (ax_crop,",
"for i in range(-is_neg, (self.length * move) - is_neg, move): curr = self.jpg_data[i]",
"contiguous sequence of images. First, images are identified as being selected or not.",
": tuple, optional By default, finds JPG image types, but can be changed",
"any other direction in the directs list (all have been checked for bounds,",
"edited. plot() Interactive plot used to select images for export. save(filename) Dumps a",
"as a response (movement). Default is an area of 100 pixels. Larger numbers",
"scale = size / h new_w = rint(w * scale) new_h = rint(h",
"CONTOURS() function, but retained here to shorten the process_jpgs() function. \"\"\" difference =",
"= np.array([h, h, w, w]) clone_from = clone_to + (h_or_w * mults) return",
"load() method call. resp_var : str, optional A key found in jpg_data, typically",
"self.pano_i = 0 prev = self.jpg_data[0] for i, curr in enumerate(self.jpg_data): prev[\"selected\"] =",
"count += area return count # JPG PROCESSING def process_jpgs( jpg_data, method=CONTOURS, crop=False,",
"min_area) except cv2.error as inst: if \"(-209:Sizes\" in str(inst): (a, b), (c, d)",
"lapse = prev[\"td_minutes\"] curr[\"selected\"] = ( lapse <= self.plt_vals[\"smooth_time\"]) prev = curr else:",
"images for export. QUICK GUIDE: c - Hold to VIEW IMAGES in gallery.",
"be passed to the cv2.threshold() function. ksize : int, unused Used in the",
"= time.time() - timer[1] total = elapsed / (progress / 100) remain =",
"0 prev = self.jpg_data[-is_neg] for i in range(-is_neg, (self.length * move) - is_neg,",
"output def construct_jpg_data( dirpath, parse_tags=DEFAULT_PARSE, sort_key=SORT_BY_DT, process_options={} ): \"\"\"Performs all necessary steps to",
"= {} def off_key(event): try: if event.xdata is not None and event.key in",
"jpg_data: row = deep_row.copy() tags = piexif.load(row[\"filepath\"]) for (key, tag), var, anon in",
"clone: preprocess = CROP_EQUALIZE else: preprocess = CROP_CLONE_EQUALIZE output = [] timer =",
"days, hours, minutes, and seconds. Returns ------- str Right justified 2 spaces, filled",
"Returns ------- list of dictionaries Contains filenames and filepaths. \"\"\" output = []",
"# THE MEAT AND POTATOES # Requires data from process_jpg(). Object essentially holds",
"for x in str(raw) if x in string.digits) return dt.strptime(str_, \"%Y%m%d%H%M%S\") def SORT_BY_DT(row):",
"+ 2)) while True: if any(n < 0 for n in array): array",
"cv2.imread(self.jpg_data[n][\"thumbpath\"]) self.buffer[0] = self.buffer[0][1:] + [n] self.buffer[1] = self.buffer[1][1:] + [img] if self.toggle:",
"f, g, h) = clone image[a:b, c:d] = image[e:f, g:h] image = CROPPER(image,",
"td from matplotlib import pyplot as plt from matplotlib.widgets import Slider, RectangleSelector import",
"of tuples, optional By default, only Image DateTime is retrieved from EXIF data",
"return BIG_NUM def input_filename(): while True: filename = input(\"FILEPATH > \") if os.path.exists(filename):",
"and previous items. export(directory) Exports selected images and a .csv file. load(filename) Loads",
"x: int(round(x)), (min_y, max_y, min_x, max_x))), ignore def RS_event(eclick, erelease): x1, y1 =",
"crop: crop = (0, h, 0, w) prev = preprocess(jpg, crop, clone) elif",
"reset these values, re- assign DEFAULT_PLOT_PARAMS to this attribute. Methods ------- attach_diffs(var, new_var)",
"self.buffer[1].append(self.buffer[1].pop(ind)) else: img = cv2.imread(self.jpg_data[n][\"thumbpath\"]) self.buffer[0] = self.buffer[0][1:] + [n] self.buffer[1] = self.buffer[1][1:]",
"\"_export.csv\"), \"w\") as f: variables = sorted(write_data[0].keys(), key=sort_cols) for i, row in enumerate(write_data):",
"curr in enumerate(self.jpg_data): prev[\"selected\"] = ( prev[\"new_count\"] > self.plt_vals[\"resp_thresh\"] or curr[\"new_count\"] > self.plt_vals[\"resp_thresh\"])",
"timestamps from images.\") crop, clone_to, directs = crop_clone_preview( cv2.imread(jpg_data[len(jpg_data) // 2][\"filepath\"])) clone =",
"(len(jpg_data) // 10, time.time()) for i, jpg in enumerate(jpg_data): if not i %",
"cv2.threshold( blurred, threshold, 255, cv2.THRESH_BINARY) return cv2.countNonZero(mask) # Like BLURRED, but only sums",
"except TypeError: pass plt.rc(\"font\", **{\"size\": 8}) plt.rcParams[\"keymap.back\"] = \"left, backspace\" fig = plt.figure()",
"for export. save(filename) Dumps a JSON object as a .sav file. update_counts() Updates",
"= input(\"FILEPATH > \") if os.path.exists(filename): print(\"File already exists, would you like to",
"based on slider. Manual user edits are applied. \"\"\" for i, row in",
"i in range(-is_neg, (self.length * move) - is_neg, move): curr = self.jpg_data[i] boo",
"within the jpg_data list are sorted by their \"Image DateTime\" EXIF tag. This",
"where=extract_var(self.jpg_data, \"selected\"), facecolor=\"#F00314\") self.lines[\"count\"] = ax.fill_between( range(self.length), 0, np_counts, facecolor=\"black\") self.lines[\"threshold\"] = ax.axhline(",
"i in lo_to_hi} self.user_edits = {**self.user_edits, **new_edits} elif event.key == \",\": for i",
"identical to the last. \"\"\" with open(filename, \"r\") as f: self.plt_vals = json.loads(next(f))",
": int Minimum contour area to count as a response (movement). Default is",
"Variable new_count is attached to jpg_data. Day to night transitions are filtered out",
"image_pano(event.xdata) def on_key(event): if event.xdata is not None: if self.press[0] is None: i",
"= [ {k: v for k, v in row.items()} for row in self.jpg_data]",
"= image.shape scale = 10 lo_W, hi_W = (0 - W // scale),",
"0.18, 0.97, 0.97) ax.grid(alpha=0.4) ax.set_axisbelow(True) ax.set_ylim([0, self.plt_vals[\"ceiling\"]]) ax.set_xlim([0, min(500, self.length)]) ax.set_xlabel(\"Frame\") ax.set_ylabel(\"Response\") plt.yticks(rotation=45)",
"= {int(k): v for k, v in temp_dict.items()} def export(self, directory): \"\"\"Exports selected",
"necessary steps to make jpg_data feedable to Cam(). Parameters ---------- dirpath : str",
"[ \"old_name\", \"old_path\", \"filename\", \"filepath\", \"shape\", \"datetime\", \"24hr\", \"is_night\", \"timedelta\", \"td_minutes\", \"median\", \"med_diff\",",
"retrieved from EXIF data using DEFAULT_PARSE. Examine DEFAULT_PARSE as an example parameter to",
"mem.clone_tuple = False mem.clone_directs = False def update(event): if crop_RS.active: crop_RS.update() if clone_RS.active:",
"for n in array): array += 1 elif any(n >= self.length for n",
"Works hierarchically to preform image cropping, cloning, and histogram equalization on images read",
"SLIDER_PARAMS: slider_ax = fig.add_axes([0.125, pos, 0.8, 0.02]) self.sliders[name] = Slider( slider_ax, name, minv,",
"gridspec.GridSpec(2, 2, height_ratios=[1, 1.25]) fig = plt.figure() fig.canvas.set_window_title(\"Crop and Clone Preview\") ax_crop =",
"method : function, {SIMPLE, BLURRED, COUNTOURS} Determines the frame differencing method to use.",
"prev, threshold, ksize, min_area) except cv2.error as inst: if \"(-209:Sizes\" in str(inst): (a,",
"off_key) fig.canvas.mpl_connect(\"button_press_event\", on_click) ax.fill_between( np.arange(0, self.length) + 0.5, -BIG_NUM, 0, facecolor=\"white\", alpha=0.75, zorder=2)",
"jpg_data attribute with new counts. update_events() Updates jpg_data attribute with new events. \"\"\"",
"clone_to else False print(\"→ Images are being processed.\") processed_data = process_jpgs(jpg_data, crop=crop, clone=clone)",
"* 10) // timer[0] elapsed = time.time() - timer[1] total = elapsed /",
"{remain} left.\") def strfdelta(tdelta, fmt): \"\"\"Formats a timedelta object as a string. Parameters",
"as a string. Parameters ---------- tdelta : datetime.timedelta Timedelta object to format. fmt",
"taken. prev : numpy.ndarray Like curr. The second image to be differenced. threshold",
"clone_to = np.array(clone_to) mults = np.array(DIRECTION_MULTS[fill_from[0].upper()]) a, b, c, d = clone_to h,",
"of tuples, optional Matches the format ((clone_to), (clone_from)). For simplicity, use generate_clone_tuples() to",
"previous variable. Requires a list of dictionaries. \"\"\" prev = self.jpg_data[0][var] for row",
"\"w\") as f: f.write(json.dumps(self.plt_vals) + \"\\n\") f.write(json.dumps(temp_data) + \"\\n\") f.write(json.dumps(self.user_edits)) def load(self, filename):",
"cv2.equalizeHist(image) def crop_clone_preview(image): \"\"\"Interactive viewer to quickly get crop and clone parameters. Parameters",
"in string.digits) return dt.strptime(str_, \"%Y%m%d%H%M%S\") def SORT_BY_DT(row): \"\"\"Default sort for construct_jpg_data(). \"\"\" return",
"csv_safe(obj): \"\"\"Puts quotes around strings with commas in them. \"\"\" string = str(obj)",
"(min_y > H or max_y < 0 or min_x > W or max_x",
"0, facecolor=\"white\", alpha=0.75, zorder=2) try: ax.fill_between( np.arange(0, self.length) + 0.5, -BIG_NUM, BIG_NUM, where=extract_var(self.jpg_data,",
"drawn contours over given limit. def CONTOURS(curr, prev, threshold, ksize=11, min_area=100): \"\"\"Slower, but",
"directs[0]) if clone_to else False) process_options = {\"crop\": crop, \"clone\": clone} print(\"Started processing...\")",
"120, self.plt_vals[\"trans_thresh\"], \"%.1f\"), (\"SMOOTH\", 0.04, 0, 10, self.plt_vals[\"smooth_time\"], \"%.1f\"), (\"NIGHT\", 0.02, -1, 50,",
"40000, \"resp_thresh\": 20000, \"trans_thresh\": 30, \"smooth_time\": 1, \"night_mult\": 0 } DIRECTION_MULTS = {",
"plot, save() and export() should be called so as not to lose any",
"else: dt_ISO = str(i) new_name = \"_\".join((dt_ISO, row[\"filename\"])) new_path = os.path.join(directory, new_name) write_row[\"filename\"]",
"this module, the interactive plot() method. A simply initialization could be: Cam(construct_jpg_data()). After",
"= Slider( slider_ax, name, minv, maxv, valinit=init, valfmt=fmt, color=\"#003459\", alpha=0.5) self.sliders[name].on_changed(on_slide) fig.canvas.mpl_connect(\"key_press_event\", on_key)",
"else: raise ValueError(\"No images selected for export.\") def attach_diffs(self, var, new_var): \"\"\"Finds the",
"backspace\" fig = plt.figure() ax = fig.add_subplot(111) fig.canvas.set_window_title(\"Response Filtering\") fig.subplots_adjust(0.07, 0.18, 0.97, 0.97)",
"exists, would you like to overwrite it?\") answer = input(\"Y / N >",
"int Parameter to be passed to the cv2.medianBlur() function. Default is 11. Must",
"image.copy() if not cl_ig: mem.clone_tuple = cl_corn trials = [] for direct in",
"now with desired EXIF data attached. \"\"\" output = [] for deep_row in",
"accuracy, decreasing speed. crop : tuple Format is (y1, y2, x1, x2), just",
"in found: filepath = os.path.join(dir_, filename) output.append({ \"filename\": filename, \"filepath\": filepath }) return",
"threshold, ksize=11, min_area=None): \"\"\"Useful, mid-grade frame differencing method. Takes two images, then finds",
"sort for construct_jpg_data(). \"\"\" return row[\"datetime\"] DEFAULT_PARSE = [ ((\"0th\", 306), \"datetime\", PARSE_DT)",
"resize_with_exif() on your jpg_data list, and specify the export directory here. These smaller",
"variables = sorted(write_data[0].keys(), key=sort_cols) for i, row in enumerate(write_data): if i != 0:",
"options are specified. Make sure that this parameter is mappable. Returns ------- list",
"event.xdata is not None: if self.press[0] is None: i = int(round(event.xdata)) if event.key",
"clone) elif i % timer[0] == 0: stop_watch(i, timer) jpg = cv2.imread(row[\"filepath\"], 0)",
"to thresholding, the differenced image is blurred to reduce noise. After thresholding, the",
"is_neg, move): curr = self.jpg_data[i] boo = (not curr[\"selected\"] and prev[\"selected\"] and not",
"self.jpg_data except AttributeError as inst: raise inst mod = self.plt_vals[\"resp_thresh\"] ** (1 /",
"to attach_exif(), if more data is desired from EXIF tags. Returns ------- list",
"is used for exporting thumbnails. long_edge : int, optional By default, images will",
"sequence of images. First, images are identified as being selected or not. Then,",
"Attributes ---------- jpg_data : list of dictionaries Similar to what is inputted, but",
"round(int(n)) def sort_cols(var_name): if var_name in COL_ORDER: return COL_ORDER.index(var_name) else: return BIG_NUM def",
"as f: variables = sorted(write_data[0].keys(), key=sort_cols) for i, row in enumerate(write_data): if i",
"= self.jpg_data[ind] if row[\"new_count\"] < 0: if func == operator.sub: master_set.add(ind) break else:",
"key != \"ceiling\": slider_key = key[:key.find(\"_\")].upper() if key == \"resp_thresh\": mod = self.sliders[slider_key].val",
"to be passed to the cv2.threshold() function. ksize : int, unused Used in",
"from matplotlib import pyplot as plt from matplotlib.widgets import Slider, RectangleSelector import matplotlib.gridspec",
"CROPPER(image, crop) return cv2.equalizeHist(image) def crop_clone_preview(image): \"\"\"Interactive viewer to quickly get crop and",
"a list of values corresponding to a variable name. >>> foo = [{\"name\":",
"minutes, and seconds. Returns ------- str Right justified 2 spaces, filled with zeros.",
"how many pixels have changed between a photo and its previous, after preprocessing",
"filename, \"filepath\": filepath }) return output def attach_exif(jpg_data, parse_tags=DEFAULT_PARSE): \"\"\"Loops through jpg_data, reading",
"By default, images will be resized to 1024 pixels on the long edge",
"row[\"count\"] = method(curr, prev, threshold, ksize, min_area) except cv2.error as inst: if \"(-209:Sizes\"",
"50, self.plt_vals[\"night_mult\"], \"%.1f\") ] def update(): self.update_counts() self.update_events() draw() def draw(): for name",
"= cv2.cv2.equalizeHist(gray) stack.append(img) min_y = min(img.shape[0] for img in stack) pano = np.hstack([img[:min_y,",
"i def generate_clone_tuples(clone_to, fill_from): \"\"\"Loops through jpg_data, reading filepaths and attaching EXIF data.",
"for EQUALIZED image (for dark images). \"\"\" try: self.jpg_data except AttributeError as inst:",
"= abs(row[\"med_diff\"]) row[\"selected\"] = False row[\"user_edit\"] = False row[\"trans_edit\"] = False if self.dt_present:",
"-BIG_NUM, BIG_NUM, where=extract_var(self.jpg_data, \"is_night\"), facecolor=\"#003459\", alpha=0.5) except KeyError: pass on_slide(1) plt.show() cv2.destroyAllWindows() if",
"(movement). Works very well, little noise; slower than others. Parameters ---------- curr :",
"Images are being processed.\") processed_data = process_jpgs(jpg_data, crop=crop, clone=clone) if type(processed_data) is not",
"different filetype. Returns ------- list of dictionaries Contains filenames and filepaths. \"\"\" output",
"-= 1 else: break stack = [] for n in array: if n",
"fed into the Cam() class for response filtering. Parameters ---------- jpg_data : list",
"but powerful frame differencing method. Takes two images, then finds their absolute difference.",
"speed. crop : tuple Format is (y1, y2, x1, x2), just like slicing",
"0: jpg = cv2.imread(row[\"filepath\"], 0) h, w = jpg.shape if not crop: crop",
"fig.subplots_adjust(0.07, 0.18, 0.97, 0.97) ax.grid(alpha=0.4) ax.set_axisbelow(True) ax.set_ylim([0, self.plt_vals[\"ceiling\"]]) ax.set_xlim([0, min(500, self.length)]) ax.set_xlabel(\"Frame\") ax.set_ylabel(\"Response\")",
"images as np.arrays. fill_from : {\"A\", \"B\", \"R\", \"L\"} Calls directional tuples from",
"is blurred to reduce noise. After thresholding, the resulting white pixels are counted",
"tup else: print(inst) prev = curr output.append(row) return output def construct_jpg_data( dirpath, parse_tags=DEFAULT_PARSE,",
"h_or_w = np.array([h, h, w, w]) clone_from = clone_to + (h_or_w * mults)",
"justified 2 spaces, filled with zeros. \"\"\" d = {\"days\": tdelta.days} d[\"hours\"], rem",
"pixels. Larger numbers decreases sensitivity. \"\"\" difference = cv2.absdiff(curr, prev) blurred = cv2.medianBlur(difference,",
"except AttributeError as inst: raise inst mod = self.plt_vals[\"resp_thresh\"] ** (1 / RESP_NUM)",
"= {\"days\": tdelta.days} d[\"hours\"], rem = divmod(tdelta.seconds, 3600) d[\"minutes\"], d[\"seconds\"] = divmod(rem, 60)",
"Works decently, a little faster than COUNTOURS. Parameters ---------- curr : numpy.ndarray Image",
"variable is used as a response, but alternatives like \"median\" can be used",
"\"B\", \"R\", \"L\"): tups = generate_clone_tuples(cl_corn, direct) a, b, c, d = tups[1]",
"- W // scale), (W + W // scale) lo_H, hi_H = (0",
"threshold, ksize=None, min_area=None): \"\"\"Most basic frame differencing method. Takes two images, then finds",
"jpg = cv2.imread(row[\"filepath\"], 0) h, w = jpg.shape if not crop: crop =",
"provided by find_imgs() prior to this function. export_dir : str Directory path that",
"process_jpgs(). Then, use \"generate_clone_tuples(clone_to, directs[0])\" to get the clone parameter, or any other",
"== 0: stop_watch(i, timer) jpg = cv2.imread(row[\"filepath\"], 0) curr = preprocess(jpg, crop, clone)",
"type(processed_data) is not tuple: cam = Cam(processed_data) print(\"→ Please input a file path",
"{ \"A\": (-1, -1, 0, 0), \"B\": (1, 1, 0, 0), \"R\": (0,",
"minv, maxv, valinit=init, valfmt=fmt, color=\"#003459\", alpha=0.5) self.sliders[name].on_changed(on_slide) fig.canvas.mpl_connect(\"key_press_event\", on_key) fig.canvas.mpl_connect(\"key_release_event\", off_key) fig.canvas.mpl_connect(\"button_press_event\", on_click)",
"i, curr in enumerate(self.jpg_data): prev[\"selected\"] = ( prev[\"new_count\"] > self.plt_vals[\"resp_thresh\"] or curr[\"new_count\"] >",
"in self.jpg_data], facecolor=\"#D8BFAA\", alpha=0.5) self.lines[\"selected\"] = ax.fill_between( np.arange(0, self.length) + 0.5, -BIG_NUM, BIG_NUM,",
"slider. Counts taken at with nighttime are multiplied based on slider. Manual user",
"be changed if camera exports a different filetype. Returns ------- list of dictionaries",
"are counted as a response (movement). Works very well, little noise; slower than",
"not os.path.exists(directory): os.makedirs(directory) write_data = [] for i, row in enumerate(self.jpg_data): write_row =",
"ax_crop.imshow(rgb) ax_clone.imshow(rgb) ax_mod.imshow(rgb) plt.connect(\"draw_event\", update) plt.show() return mem.crop_tuple, mem.clone_tuple, mem.clone_directs # FRAME DIFFERENCING",
"Updates jpg_data attribute with new events. \"\"\" def __init__(self, jpg_data=False, resp_var=\"count\", thumb_dir=None): \"\"\"",
"in SLIDER_PARAMS: slider_ax = fig.add_axes([0.125, pos, 0.8, 0.02]) self.sliders[name] = Slider( slider_ax, name,",
"on time since last image (SMOOTH slider value). \"\"\" self.pano_i = 0 prev",
"# Bare-bones. Take difference, threshold, and sum the mask. def SIMPLE(curr, prev, threshold,",
"if key != \"ceiling\": slider_key = key[:key.find(\"_\")].upper() if key == \"resp_thresh\": mod =",
"method call. resp_var : str, optional A key found in jpg_data, typically the",
"cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img = cv2.cv2.equalizeHist(gray) stack.append(img) min_y = min(img.shape[0] for img in stack)",
"------- tuple Format is (crop, clone_to, clone_directs). The crop_tuple variable can be fed",
"v for k, v in row.items()} for row in self.jpg_data] for row in",
"Path to an image-containing directory. parse_tags : list of tuples, optional By default,",
"for i, row in enumerate(write_data): if i != 0: f.write(\"\\n\") else: f.write(\",\".join(variables) +",
"curr if self.dt_present: for move in (1, -1): is_neg = move < 0",
"construct_jpg_data( dirpath, parse_tags=DEFAULT_PARSE, sort_key=SORT_BY_DT, process_options={} ): \"\"\"Performs all necessary steps to make jpg_data",
"input a directory path with camera-trapping images.\") jpg_paths = find_imgs(input_directory()) jpg_data = attach_exif(jpg_paths)",
"thumb_dir=None): \"\"\" Parameters ---------- jpg_data : list of dictionaries, optional Typically requires the",
"1), \"L\": (0, 0, -1, -1) } COL_ORDER = [ \"old_name\", \"old_path\", \"filename\",",
"be displayed in the Gallery tab. \"\"\" self.resp_var = resp_var self.plt_vals = DEFAULT_PLOT_PARAMS",
"row[\"thumbpath\"] = row[\"filepath\"] row[\"count\"] = row[self.resp_var] row[\"med_diff\"] = abs(row[\"med_diff\"]) row[\"selected\"] = False row[\"user_edit\"]",
"(a, b, c, d), (e, f, g, h) = tups test[a:b, c:d] =",
"file. mark_edits(i) Marks which photos have been edited. plot() Interactive plot used to",
"= image[e:f, g:h] image = CROPPER(image, crop) return cv2.equalizeHist(image) def crop_clone_preview(image): \"\"\"Interactive viewer",
"\"new_count\")) self.lines[\"edited\"] = ax.fill_between( np.arange(0, self.length) + 0.5, -BIG_NUM, BIG_NUM, where=[r[\"trans_edit\"] or r[\"user_edit\"]",
"numpy.ndarray Image array, typically from cv2.imread(). Returns ------- tuple Format is (crop, clone_to,",
"row[\"datetime\"] = dt.strptime( row[\"datetime\"], \"%Y-%m-%d %H:%M:%S\" ) self.dt_present = True else: self.dt_present =",
"d = clone_to h, w = b - a, d - c h_or_w",
"between images. Works hierarchically to preform image cropping, cloning, and histogram equalization on",
"w * 0.02 self.plt_vals[\"resp_thresh\"] = self.plt_vals[\"ceiling\"] / 2 self.attach_diffs(\"median\", \"med_diff\") for row in",
"slider_ax, name, minv, maxv, valinit=init, valfmt=fmt, color=\"#003459\", alpha=0.5) self.sliders[name].on_changed(on_slide) fig.canvas.mpl_connect(\"key_press_event\", on_key) fig.canvas.mpl_connect(\"key_release_event\", off_key)",
"viewer to quickly get crop and clone parameters. Parameters ---------- image : numpy.ndarray",
". - Press to RESET ALL EDITS. v - Press for EQUALIZED image",
"before being passed on to frame differencing methods that generate a response metric.",
"if x in string.digits) return dt.strptime(str_, \"%Y%m%d%H%M%S\") def SORT_BY_DT(row): \"\"\"Default sort for construct_jpg_data().",
"used to plot jpgs without processing them first. thumb_dir : str, optional If",
"str Path to an image-containing directory. parse_tags : list of tuples, optional By",
"have a variable for sequence. process_options : dictionary, optional Passes along paramters to",
"jpg_data: self.jpg_data = list(jpg_data) self.length = len(self.jpg_data) self.dt_present = \"datetime\" in self.jpg_data[0].keys() h,",
"row[\"selected\"] = False row[\"user_edit\"] = False row[\"trans_edit\"] = False if self.dt_present: self.attach_diffs(\"datetime\", \"timedelta\")",
"with new counts (response metric). Variable new_count is attached to jpg_data. Day to",
"write_row[\"old_path\"] = row[\"filepath\"] shutil.copy2(row[\"filepath\"], new_path) write_data.append(write_row) if write_data: with open(os.path.join(directory, \"_export.csv\"), \"w\") as",
"difference = cv2.absdiff(curr, prev) blurred = cv2.medianBlur(difference, ksize) _, mask = cv2.threshold( blurred,",
"camera-trapping images.\") jpg_paths = find_imgs(input_directory()) jpg_data = attach_exif(jpg_paths) jpg_data.sort(key=lambda x: x[\"datetime\"]) print(\"→ Crop",
"self.plt_vals[\"night_mult\"], \"%.1f\") ] def update(): self.update_counts() self.update_events() draw() def draw(): for name in",
"find_imgs() prior to this function. parse_tags : list of tuples, optional By default,",
"= self.jpg_data[0][var] for row in self.jpg_data: curr = row[var] row[new_var] = curr -",
"function. ksize : int Parameter to be passed to the cv2.medianBlur() function. Default",
"in dictionary keys, which is easily provided by find_imgs() prior to this function.",
"clone_RS.active: clone_RS.update() def safe_corners(geometry): min_y = max(0, min(geometry[0, :])) max_y = min(H, max(geometry[0,",
"to 1024 pixels on the long edge of the image. Smaller sizes speed",
"self.buffer[1][1:] + [img] if self.toggle: gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img = cv2.cv2.equalizeHist(gray) stack.append(img)",
"self.plt_vals[\"resp_thresh\"] = ( self.plt_vals[\"resp_thresh\"] ** (1 / RESP_NUM)) temp_data = json.loads(next(f)) temp_dict =",
"a cropped image with an equalized histogram. Parameters ---------- image : numpy.ndarray Image",
"counted toward response (movement). Very noisy, but fast. Parameters ---------- curr : numpy.ndarray",
"cv2.COLOR_BGR2RGB) H, W, *_ = image.shape scale = 10 lo_W, hi_W = (0",
"that generate a response metric. This is the last step before the jpg_data",
"here to shorten the process_jpgs() function. \"\"\" difference = cv2.absdiff(curr, prev) _, mask",
"\"\"\" A class used to store, plot, filter, and export image data. Contains",
"\"night_mult\": 0 } DIRECTION_MULTS = { \"A\": (-1, -1, 0, 0), \"B\": (1,",
"max_y < 0 or min_x > W or max_x < 0) return tuple(map(",
"x1:x2] mod = cv2.cvtColor(mod, cv2.COLOR_BGR2RGB) ax_mod.imshow(mod) fig.canvas.draw_idle() rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) H, W,",
"crop : tuple Format is (y1, y2, x1, x2), just like slicing images",
"import json import operator import os import shutil import string import sys import",
"speed up performance, but decrease acuity. \"\"\" if not os.path.exists(export_dir): os.makedirs(export_dir) timer =",
"jpg.shape if not crop: crop = (0, h, 0, w) prev = preprocess(jpg,",
"default, dictionaries within the jpg_data list are sorted by their \"Image DateTime\" EXIF",
"long_edge : int, optional By default, images will be resized to 1024 pixels",
"= crop_clone_preview( cv2.imread(jpg_data[len(jpg_data) // 2][\"filepath\"])) clone = generate_clone_tuples(clone_to, directs[0]) if clone_to else False",
"export(self, directory): \"\"\"Exports selected images and a .csv file to specified directory. \"\"\"",
"resized = resize_long_edge(im, long_edge) cv2.imwrite(to_path, resized) piexif.transplant(from_path, to_path) # SPECIFIC FUNCTIONS def find_imgs(dirpath,",
"= key[:key.find(\"_\")].upper() if key == \"resp_thresh\": mod = self.sliders[slider_key].val ** RESP_NUM self.plt_vals[key] =",
"reading filepaths and attaching EXIF data. Parameters ---------- jpg_data : list of dictionaries",
"if i == 0: jpg = cv2.imread(row[\"filepath\"], 0) h, w = jpg.shape if",
"process_options : dictionary, optional Passes along paramters to the process_jpgs() function. By default,",
"to the last. \"\"\" with open(filename, \"r\") as f: self.plt_vals = json.loads(next(f)) self.plt_vals[\"resp_thresh\"]",
"all images are of same size, \" \"consider using the crop parameter.\\n\" f\"Try",
"w, *_ = im.shape if w > h: scale = size / w",
"if \"timedelta\" in row.keys(): try: row[\"timedelta\"] = td(seconds=row[\"timedelta\"]) except AttributeError: pass if \"selected\"",
"\") if answer.lower() in (\"y\", \"yes\"): return filename elif filename: return filename def",
"don\"t have a datetime, but do have a variable for sequence. process_options :",
"in jpg_data: row = deep_row.copy() tags = piexif.load(row[\"filepath\"]) for (key, tag), var, anon",
"output.append({ \"filename\": filename, \"filepath\": filepath }) return output def attach_exif(jpg_data, parse_tags=DEFAULT_PARSE): \"\"\"Loops through",
"self.plt_vals[\"resp_thresh\"] = self.plt_vals[\"ceiling\"] / 2 self.attach_diffs(\"median\", \"med_diff\") for row in self.jpg_data: if thumb_dir",
"cv2.threshold( difference, threshold, 255, cv2.THRESH_BINARY) return cv2.countNonZero(mask) # Difference, blur (amount changes with",
"everything that is needed to feed a Cam() object with its initial data.",
"= func(i, j) try: row = self.jpg_data[ind] if row[\"new_count\"] < 0: if func",
"event.xdata is not None: image_pano(event.xdata) def on_key(event): if event.xdata is not None: if",
"a timedelta object as a string. Parameters ---------- jpg_data : list of dictionaries",
": int Parameter to be passed to the cv2.medianBlur() function. Default is 11.",
"(crop, clone_to, clone_directs). The crop_tuple variable can be fed directly into process_jpgs(). Then,",
"into the Cam() class for response filtering. Parameters ---------- jpg_data : list of",
"= process_jpgs(jpg_data, crop=crop, clone=clone) if type(processed_data) is not tuple: cam = Cam(processed_data) print(\"→",
"for key in self.plt_vals.keys(): if key != \"ceiling\": slider_key = key[:key.find(\"_\")].upper() if key",
"{\"days\": tdelta.days} d[\"hours\"], rem = divmod(tdelta.seconds, 3600) d[\"minutes\"], d[\"seconds\"] = divmod(rem, 60) for",
"divmod(tdelta.seconds, 3600) d[\"minutes\"], d[\"seconds\"] = divmod(rem, 60) for k, v in d.items(): if",
"optional If the interactive plot is laggy, use resize_with_exif() on your jpg_data list,",
"pass if \"selected\" in row.keys(): row[\"selected\"] = bool(row[\"selected\"]) self.jpg_data = temp_data.copy() self.length =",
"else: row[\"thumbpath\"] = row[\"filepath\"] row[\"count\"] = row[self.resp_var] row[\"med_diff\"] = abs(row[\"med_diff\"]) row[\"selected\"] = False",
"the area. Returns ------- pair of tuples Matches the format for the clone",
"h // 2))) cv2.waitKey(1) def on_click(event): if event.dblclick and event.xdata is not None:",
"os import shutil import string import sys import time import cv2 import piexif",
"to an image-containing directory. img_type : tuple, optional By default, finds JPG image",
"= image.copy() if not cl_ig: mem.clone_tuple = cl_corn trials = [] for direct",
"g:h] diff = cv2.absdiff(test, image) choose.append((sum(cv2.sumElems(diff)), direct, test)) choose.sort() if choose: _, directs,",
"crop_RS = RectangleSelector( ax_crop, RS_event, **RS_PARAMS) clone_RS = RectangleSelector( ax_clone, RS_event, **RS_PARAMS) ax_crop.set_title(\"Crop\")",
"thresh_init = False if not clone: preprocess = CROP_EQUALIZE else: preprocess = CROP_CLONE_EQUALIZE",
"= [] for i, row in enumerate(self.jpg_data): write_row = row.copy() if row[\"selected\"]: if",
"EXIF data. Parameters ---------- jpg_data : list of dictionaries Requires that \"filepath\" is",
"= False if cr_ig: cr_corn = (0, H, 0, W) mem.crop_tuple = False",
"directs = crop_clone_preview( cv2.imread(jpg_data[len(jpg_data) // 2][\"filepath\"])) clone = generate_clone_tuples(clone_to, directs[0]) if clone_to else",
"string def to_24_hour(datetime): \"\"\"Converts datetime.datetime type to 24 hour float type. \"\"\" time",
"3], \"minspanx\": 5, \"minspany\": 5, \"spancoords\": \"pixels\", \"interactive\": True } # GENERAL FUNCTIONS",
"path, finding all files ending in img_type. Parameters ---------- dirpath : str Path",
"n in array): array += 1 elif any(n >= self.length for n in",
"\"\"\"Default sort for construct_jpg_data(). \"\"\" return row[\"datetime\"] DEFAULT_PARSE = [ ((\"0th\", 306), \"datetime\",",
"for img in stack) pano = np.hstack([img[:min_y, :] for img in stack]) h,",
"output = [] timer = (len(jpg_data) // 10, time.time()) for i, deep_row in",
"(0, h, 0, w) prev = preprocess(jpg, crop, clone) elif i % timer[0]",
"time.time() - timer[1] total = elapsed / (progress / 100) remain = strfdelta(td(seconds=total",
"\"\"\"Slower, but powerful frame differencing method. Takes two images, then finds their absolute",
"load(filename) Loads a .sav file. mark_edits(i) Marks which photos have been edited. plot()",
"\"\"\"Updates jpg_data with new counts (response metric). Variable new_count is attached to jpg_data.",
"# meds = extract_var(self.jpg_data, \"median\") X = np.array(day_hr).reshape(-1, 1) kmeans = KMeans(n_clusters=3).fit(X) night_indices",
"a, b, c, d = clone_to h, w = b - a, d",
"shift in self.user_edits.items(): self.jpg_data[i][\"new_count\"] = shift self.mark_edits(i, \"user_edit\") def update_events(self): \"\"\"Updates jpg_data with",
"the resulting white pixels are counted toward response (movement). Works decently, a little",
"min_area=100): \"\"\"Slower, but powerful frame differencing method. Takes two images, then finds their",
"\"\"\"Generates a response (movement) metric between images. Works hierarchically to preform image cropping,",
"to 24 hour float type. \"\"\" time = datetime.time() return time.hour + time.minute",
"the differenced image is blurred to reduce noise. After thresholding, contours are drawn",
"0.06, 0, 120, self.plt_vals[\"trans_thresh\"], \"%.1f\"), (\"SMOOTH\", 0.04, 0, 10, self.plt_vals[\"smooth_time\"], \"%.1f\"), (\"NIGHT\", 0.02,",
"break else: master_set.add(ind) except IndexError: pass for i in master_set: self.jpg_data[i][\"selected\"] = True",
"= [] for (tups, direct) in trials: test = image.copy() (a, b, c,",
"blurred, threshold, 255, cv2.THRESH_BINARY) contours, _ = cv2.findContours( mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2:] count =",
"n, index in enumerate(kmeans.labels_): self.jpg_data[n][\"is_night\"] = index in night_indices def save(self, filename): \"\"\"Dumps",
"None, [256], [0, 256]) tally = 0 threshold = px_count / 2 for",
"if write_data: with open(os.path.join(directory, \"_export.csv\"), \"w\") as f: variables = sorted(write_data[0].keys(), key=sort_cols) for",
"def find_imgs(dirpath, img_type=(\".jpg\", \".jpeg\")): \"\"\"Walks directory path, finding all files ending in img_type.",
"cv2.imread(). One of the two images for the absolute difference to be taken.",
"lo_to_hi = range(max(0, low), min(self.length, high+1)) if event.key in \"zx\": new_edits = {i:",
"around strings with commas in them. \"\"\" string = str(obj) return '\"' +",
"= [BIG_NUM, i] elif event.key == \",\": self.press = [0, i] if event.key",
"= tups[1] if not (a < 0 or b > H or c",
"self.attach_diffs(\"datetime\", \"timedelta\") for row in self.jpg_data: row[\"24hr\"] = to_24_hour(row[\"datetime\"]) row[\"td_minutes\"] = round( row[\"timedelta\"].total_seconds()",
"found = ( f for f in files if f.lower().endswith(img_type) ) for filename",
"as np.arrays. clone : pair of tuples Matches the format ((clone_to), (clone_from)). For",
"0) h, w = jpg.shape if not crop: crop = (0, h, 0,",
"a different filetype. Returns ------- list of dictionaries Contains filenames and filepaths. \"\"\"",
"hist_median(image): \"\"\"Quickly finds the median tone of a grayscale image. \"\"\" px_count =",
"-1) } COL_ORDER = [ \"old_name\", \"old_path\", \"filename\", \"filepath\", \"shape\", \"datetime\", \"24hr\", \"is_night\",",
"dictionaries, optional Typically requires the output of process_jpgs(). Can be omitted if a",
"(clone_from)). For simplicity, use generate_clone_tuples() to generate this object. threshold : int, in",
"Must be positive, odd number. min_area : int, unused Only used in the",
"r in self.jpg_data], facecolor=\"#D8BFAA\", alpha=0.5) self.lines[\"selected\"] = ax.fill_between( np.arange(0, self.length) + 0.5, -BIG_NUM,",
"at with nighttime are multiplied based on slider. Manual user edits are applied.",
"= clone_to h, w = b - a, d - c h_or_w =",
"**{\"size\": 8}) plt.rcParams[\"keymap.back\"] = \"left, backspace\" fig = plt.figure() ax = fig.add_subplot(111) fig.canvas.set_window_title(\"Response",
"by find_imgs() prior to this function. parse_tags : list of tuples, optional By",
"# CONSTANTS BIG_NUM = int(1e9) NEG_NUM = -0.1 RESP_NUM = 3.5 def PARSE_DT(raw):",
"to shorten the process_jpgs() function. min_area : int, unused Only used in the",
"DateTime\" EXIF tag. This can be changed if images don\"t have a datetime,",
"provided by find_imgs() prior to this function. method : function, {SIMPLE, BLURRED, COUNTOURS}",
"True self.jpg_data[i-1][kind] = True def update_counts(self): \"\"\"Updates jpg_data with new counts (response metric).",
"cv2.cv2.equalizeHist(gray) stack.append(img) min_y = min(img.shape[0] for img in stack) pano = np.hstack([img[:min_y, :]",
"mask = cv2.threshold( blurred, threshold, 255, cv2.THRESH_BINARY) contours, _ = cv2.findContours( mask, cv2.RETR_LIST,",
"BIG_NUM, where=extract_var(self.jpg_data, \"is_night\"), facecolor=\"#003459\", alpha=0.5) except KeyError: pass on_slide(1) plt.show() cv2.destroyAllWindows() if __name__",
"= self.buffer[0].index(n) img = self.buffer[1][ind] self.buffer[0].append(self.buffer[0].pop(ind)) self.buffer[1].append(self.buffer[1].pop(ind)) else: img = cv2.imread(self.jpg_data[n][\"thumbpath\"]) self.buffer[0] =",
"noise. After thresholding, the resulting white pixels are counted toward response (movement). Works",
"2, h // 2))) cv2.waitKey(1) def on_click(event): if event.dblclick and event.xdata is not",
"self.jpg_data[i][\"new_count\"] = shift self.mark_edits(i, \"user_edit\") def update_events(self): \"\"\"Updates jpg_data with new events (runs",
"\"yes\"): return filename elif filename: return filename def input_directory(): while True: directory =",
"\"generate_clone_tuples(clone_to, directs[0])\" to get the clone parameter, or any other direction in the",
"is laggy, use resize_with_exif() on your jpg_data list, and specify the export directory",
"in os.walk(dirpath): if \"_selected\" not in dir_: found = ( f for f",
"not cl_ig: mem.clone_tuple = cl_corn trials = [] for direct in (\"A\", \"B\",",
"a count variable, which respresents how many pixels have changed between a photo",
"\"med_diff\") for row in self.jpg_data: if thumb_dir is not None: row[\"thumbpath\"] = os.path.join(thumb_dir,",
"= td(seconds=row[\"timedelta\"]) except AttributeError: pass if \"selected\" in row.keys(): row[\"selected\"] = bool(row[\"selected\"]) self.jpg_data",
"self.buffer[1][ind] self.buffer[0].append(self.buffer[0].pop(ind)) self.buffer[1].append(self.buffer[1].pop(ind)) else: img = cv2.imread(self.jpg_data[n][\"thumbpath\"]) self.buffer[0] = self.buffer[0][1:] + [n] self.buffer[1]",
"crop_tuple variable can be fed directly into process_jpgs(). Then, use \"generate_clone_tuples(clone_to, directs[0])\" to",
"_, mask = cv2.threshold( blurred, threshold, 255, cv2.THRESH_BINARY) contours, _ = cv2.findContours( mask,",
"be positive, odd number. min_area : int Minimum contour area to count as",
"checked for bounds, unlike generate_clone_tuples). \"\"\" mem = Mem() mem.crop_tuple = False mem.clone_tuple",
"for a load() method call. resp_var : str, optional A key found in",
"else False print(\"→ Images are being processed.\") processed_data = process_jpgs(jpg_data, crop=crop, clone=clone) if",
"jpg_data = attach_exif(jpg_paths, parse_tags) jpg_data.sort(key=sort_key) if process_options == {}: print(\"Crop and clone image",
"os.path.isdir(directory): return directory else: print(\"Directory does not exist, would you like to make",
"row[\"filename\"])) new_path = os.path.join(directory, new_name) write_row[\"filename\"] = new_name write_row[\"filepath\"] = new_path write_row[\"old_name\"] =",
"used in the plot() method. To reset these values, re- assign DEFAULT_PLOT_PARAMS to",
"* 0.02 self.plt_vals[\"resp_thresh\"] = self.plt_vals[\"ceiling\"] / 2 self.attach_diffs(\"median\", \"med_diff\") for row in self.jpg_data:",
"b, c, d = tups[1] if not (a < 0 or b >",
"variables)) else: raise ValueError(\"No images selected for export.\") def attach_diffs(self, var, new_var): \"\"\"Finds",
"directional tuples from DIRECTION_MULTS to fill pixels within the clone_to area. Neighboring pixels",
"feed a Cam() object with its initial data. \"\"\" jpg_paths = find_imgs(dirpath) print(f\"{len(jpg_paths)}",
"2][\"filepath\"])) clone = generate_clone_tuples(clone_to, directs[0]) if clone_to else False print(\"→ Images are being",
"attach_exif(), if more data is desired from EXIF tags. sort_key : function, optional",
"raise ValueError(\"No images selected for export.\") def attach_diffs(self, var, new_var): \"\"\"Finds the difference",
"changed if images don\"t have a datetime, but do have a variable for",
"noise. After thresholding, contours are drawn around the resulting white pixels. If the",
"= extract_var(self.jpg_data, \"median\") X = np.array(day_hr).reshape(-1, 1) kmeans = KMeans(n_clusters=3).fit(X) night_indices = [np.argmin(kmeans.cluster_centers_),",
"for direct in (\"A\", \"B\", \"R\", \"L\"): tups = generate_clone_tuples(cl_corn, direct) a, b,",
"piexif.load(row[\"filepath\"]) for (key, tag), var, anon in parse_tags: row[var] = anon(tags[key][tag]) output.append(row) return",
"max_y = min(H, max(geometry[0, :])) min_x = max(0, min(geometry[1, :])) max_x = min(W,",
"Takes two images, then finds their absolute difference. Prior to thresholding, the differenced",
"list of values corresponding to a variable name. >>> foo = [{\"name\": \"Shane\",",
"tally > threshold: return i def generate_clone_tuples(clone_to, fill_from): \"\"\"Loops through jpg_data, reading filepaths",
"= int(row[\"selected\"]) with open(filename, \"w\") as f: f.write(json.dumps(self.plt_vals) + \"\\n\") f.write(json.dumps(temp_data) + \"\\n\")",
"for cnt in contours: area = cv2.contourArea(cnt) if area > min_area: count +=",
"---------- dirpath : str Path to an image-containing directory. img_type : tuple, optional",
"cl_corn trials = [] for direct in (\"A\", \"B\", \"R\", \"L\"): tups =",
"def SIMPLE(curr, prev, threshold, ksize=None, min_area=None): \"\"\"Most basic frame differencing method. Takes two",
"row[\"filename\"]) else: row[\"thumbpath\"] = row[\"filepath\"] row[\"count\"] = row[self.resp_var] row[\"med_diff\"] = abs(row[\"med_diff\"]) row[\"selected\"] =",
"jpg_data : list of dictionaries Similar to what is inputted, but includes variables",
"\"R\": (0, 0, 1, 1), \"L\": (0, 0, -1, -1) } COL_ORDER =",
"Requires that \"filepath\" and \"filename\" is in dictionary keys, which is easily provided",
"image-containing directory. parse_tags : list of tuples, optional By default, only Image DateTime",
"0]) ax_clone = fig.add_subplot(gs[0, 1]) ax_mod = fig.add_subplot(gs[1, :]) crop_RS = RectangleSelector( ax_crop,",
"current and previous variable. Requires a list of dictionaries. \"\"\" prev = self.jpg_data[0][var]",
"if process_options == {}: print(\"Crop and clone image as desired.\") crop, clone_to, directs",
"to 0. , - Hold and release to REMOVE EDITS. . - Press",
"** (1 / RESP_NUM)) temp_data = json.loads(next(f)) temp_dict = json.loads(next(f)) for row in",
"prev = self.jpg_data[-is_neg] for i in range(-is_neg, (self.length * move) - is_neg, move):",
"here to shorten the process_jpgs() function. \"\"\" difference = cv2.absdiff(curr, prev) blurred =",
"mem.clone_directs = False if cr_ig: cr_corn = (0, H, 0, W) mem.crop_tuple =",
"self.press = [None, None] update() except TypeError: pass plt.rc(\"font\", **{\"size\": 8}) plt.rcParams[\"keymap.back\"] =",
"\"\\n\") f.write(\",\".join(csv_safe(row[v]) for v in variables)) else: raise ValueError(\"No images selected for export.\")",
"a timedelta object as a string. Parameters ---------- tdelta : datetime.timedelta Timedelta object",
"\"\"\"Loops through jpg_data, reading filepaths and attaching EXIF data. Parameters ---------- jpg_data :",
"Mem(): def __init__(self): pass def rint(n): return round(int(n)) def sort_cols(var_name): if var_name in",
"BLURRED(curr, prev, threshold, ksize=11, min_area=None): \"\"\"Useful, mid-grade frame differencing method. Takes two images,",
"like slicing images as np.arrays. clone : pair of tuples, optional Matches the",
"row = deep_row.copy() if i == 0: jpg = cv2.imread(row[\"filepath\"], 0) h, w",
"\"td_minutes\", \"median\", \"med_diff\", \"count\", \"new_count\", \"selected\", \"user_edit\", \"trans_edit\" ] RS_PARAMS = { \"drawtype\":",
"as desired.\") crop, clone_to, directs = crop_clone_preview( cv2.imread(jpg_data[len(jpg_data) // 2][\"filepath\"])) clone = (generate_clone_tuples(clone_to,",
"= (len(jpg_data) // 10, time.time()) for i, jpg in enumerate(jpg_data): if not i",
"self.user_edits = {} def off_key(event): try: if event.xdata is not None and event.key",
"time since last image (SMOOTH slider value). \"\"\" self.pano_i = 0 prev =",
"if \"_selected\" not in dir_: found = ( f for f in files",
"for i, row in enumerate(self.jpg_data): row[\"user_edit\"] = False row[\"trans_edit\"] = False new_count =",
"steps to make jpg_data feedable to Cam(). Parameters ---------- dirpath : str Path",
"function. \"\"\" difference = cv2.absdiff(curr, prev) _, mask = cv2.threshold( difference, threshold, 255,",
"j in range(nudge+1): ind = func(i, j) try: row = self.jpg_data[ind] if row[\"new_count\"]",
"= 0 threshold = px_count / 2 for i, count in enumerate(hist): tally",
"ax.fill_between( range(self.length), 0, np_counts, facecolor=\"black\") self.lines[\"threshold\"] = ax.axhline( self.plt_vals[\"resp_thresh\"], color=\"#14B37D\") fig.canvas.draw_idle() def on_slide(val):",
"Contains the heart of this module, the interactive plot() method. A simply initialization",
"\"datetime\", PARSE_DT) ] DEFAULT_PLOT_PARAMS = { \"ceiling\": 40000, \"resp_thresh\": 20000, \"trans_thresh\": 30, \"smooth_time\":",
"not exist, would you like to make it?\") answer = input(\"Y / N",
"def update_counts(self): \"\"\"Updates jpg_data with new counts (response metric). Variable new_count is attached",
"value to Inf. z - Hold and release to DECREASE response value to",
"ax.set_axisbelow(True) ax.set_ylim([0, self.plt_vals[\"ceiling\"]]) ax.set_xlim([0, min(500, self.length)]) ax.set_xlabel(\"Frame\") ax.set_ylabel(\"Response\") plt.yticks(rotation=45) for name in (\"count\",",
"deep_row.copy() if i == 0: jpg = cv2.imread(row[\"filepath\"], 0) h, w = jpg.shape",
"typically from cv2.imread(). One of the two images for the absolute difference to",
"types, but can be changed if camera exports a different filetype. Returns -------",
"mults = np.array(DIRECTION_MULTS[fill_from[0].upper()]) a, b, c, d = clone_to h, w = b",
"60) for k, v in d.items(): if k != \"days\": d[k] = str(v).rjust(2,",
"False else: mem.crop_tuple = cr_corn y1, y2, x1, x2 = cr_corn mod =",
"process_jpgs( jpg_data, method=CONTOURS, crop=False, clone=False, threshold=False, ksize=11, min_area=100 ): \"\"\"Generates a response (movement)",
"these values, re- assign DEFAULT_PLOT_PARAMS to this attribute. Methods ------- attach_diffs(var, new_var) Finds",
"2))) cv2.waitKey(1) def on_click(event): if event.dblclick and event.xdata is not None: image_pano(event.xdata) def",
"\"consider using the crop parameter.\\n\" f\"Try crop={tup}.\") return tup else: print(inst) prev =",
"self.plt_vals.keys(): if key != \"ceiling\": slider_key = key[:key.find(\"_\")].upper() if key == \"resp_thresh\": mod",
"slider. Manual user edits are applied. \"\"\" for i, row in enumerate(self.jpg_data): row[\"user_edit\"]",
"0: f.write(\"\\n\") else: f.write(\",\".join(variables) + \"\\n\") f.write(\",\".join(csv_safe(row[v]) for v in variables)) else: raise",
"x1, x2), just like slicing images as np.arrays. \"\"\" y1, y2, x1, x2",
"\"\"\" self.pano_i = 0 prev = self.jpg_data[0] for i, curr in enumerate(self.jpg_data): prev[\"selected\"]",
"its initial data. \"\"\" jpg_paths = find_imgs(dirpath) print(f\"{len(jpg_paths)} images found.\") jpg_data = attach_exif(jpg_paths,",
"h, w = min(a, c), min(b, d) tup = (0, h, 0, w)",
"datetime.datetime type to 24 hour float type. \"\"\" time = datetime.time() return time.hour",
"= (0, h, 0, w) prev = preprocess(jpg, crop, clone) elif i %",
") else: dt_ISO = str(i) new_name = \"_\".join((dt_ISO, row[\"filename\"])) new_path = os.path.join(directory, new_name)",
"\"\"\"Updates jpg_data with new events (runs of detection). An event is a contiguous",
"cv2.WINDOW_NORMAL) cv2.imshow(\"Gallery\", cv2.resize(pano, (w // 2, h // 2))) cv2.waitKey(1) def on_click(event): if",
"in enumerate(self.jpg_data): row[\"user_edit\"] = False row[\"trans_edit\"] = False new_count = row[\"count\"] if row[\"med_diff\"]",
"self.plt_vals[\"smooth_time\"]) prev = curr else: nudge = int(self.plt_vals[\"smooth_time\"]) master_set = set() for i,",
"else: mem.clone_tuple = False mem.clone_directs = False if cr_ig: cr_corn = (0, H,",
"ax_crop = fig.add_subplot(gs[0, 0]) ax_clone = fig.add_subplot(gs[0, 1]) ax_mod = fig.add_subplot(gs[1, :]) crop_RS",
"[] timer = (len(jpg_data) // 10, time.time()) for i, deep_row in enumerate(jpg_data): row",
"tab. \"\"\" self.resp_var = resp_var self.plt_vals = DEFAULT_PLOT_PARAMS self.lines = {} self.sliders =",
"// 2))) cv2.waitKey(1) def on_click(event): if event.dblclick and event.xdata is not None: image_pano(event.xdata)",
"filter, and export image data. Contains the heart of this module, the interactive",
"os.makedirs(directory) return directory print(\"Please input a new directory path.\") def csv_safe(obj): \"\"\"Puts quotes",
"= i array = np.array(range(i - 2, i + 2)) while True: if",
"row[\"selected\"]: if self.dt_present: dt_ISO = dt.strftime( row[\"datetime\"], \"%Y%m%dT%H%M%S\" ) else: dt_ISO = str(i)",
"0), \"B\": (1, 1, 0, 0), \"R\": (0, 0, 1, 1), \"L\": (0,",
"(h_or_w * mults) return (tuple(clone_to), tuple(clone_from)) # IMAGE PREPROCESSING def CROPPER(image, crop): \"\"\"Returns",
"( self.plt_vals[\"resp_thresh\"] ** (1 / RESP_NUM)) temp_data = json.loads(next(f)) temp_dict = json.loads(next(f)) for",
"in range(0, 256) Parameter to be passed to the cv2.threshold() function. ksize :",
"list of tuples, optional By default, only Image DateTime is retrieved from EXIF",
"thresholding, the differenced image is blurred to reduce noise. After thresholding, contours are",
"clone image[a:b, c:d] = image[e:f, g:h] image = CROPPER(image, crop) return cv2.equalizeHist(image) def",
"int(row[\"selected\"]) with open(filename, \"w\") as f: f.write(json.dumps(self.plt_vals) + \"\\n\") f.write(json.dumps(temp_data) + \"\\n\") f.write(json.dumps(self.user_edits))",
"on_key(event): if event.xdata is not None: if self.press[0] is None: i = int(round(event.xdata))",
"if \"selected\" in row.keys(): row[\"selected\"] = bool(row[\"selected\"]) self.jpg_data = temp_data.copy() self.length = len(self.jpg_data)",
"and plot function. class Cam(): \"\"\" A class used to store, plot, filter,",
"[256], [0, 256]) tally = 0 threshold = px_count / 2 for i,",
"def update(event): if crop_RS.active: crop_RS.update() if clone_RS.active: clone_RS.update() def safe_corners(geometry): min_y = max(0,",
"simply initialization could be: Cam(construct_jpg_data()). After filtering images with the plot, save() and",
"0.97, 0.97) ax.grid(alpha=0.4) ax.set_axisbelow(True) ax.set_ylim([0, self.plt_vals[\"ceiling\"]]) ax.set_xlim([0, min(500, self.length)]) ax.set_xlabel(\"Frame\") ax.set_ylabel(\"Response\") plt.yticks(rotation=45) for",
"are drawn around the resulting white pixels. If the contours are above the",
"elif event.key == \"x\": self.press = [BIG_NUM, i] elif event.key == \",\": self.press",
"prev = curr output.append(row) return output def construct_jpg_data( dirpath, parse_tags=DEFAULT_PARSE, sort_key=SORT_BY_DT, process_options={} ):",
"11. Must be positive, odd number. min_area : int, unused Only used in",
"if \"timedelta\" in row.keys(): row[\"timedelta\"] = row[\"timedelta\"].total_seconds() if \"selected\" in row.keys(): row[\"selected\"] =",
"output of process_jpgs(). Can be omitted if a empty Cam() object is desired",
"above the min_area parameter, they are counted as a response (movement). Works very",
"in row.keys(): row[\"datetime\"] = dt.strptime( row[\"datetime\"], \"%Y-%m-%d %H:%M:%S\" ) self.dt_present = True else:",
"self.user_edits = {int(k): v for k, v in temp_dict.items()} def export(self, directory): \"\"\"Exports",
"v in temp_dict.items()} def export(self, directory): \"\"\"Exports selected images and a .csv file",
"with nighttime are multiplied based on slider. Manual user edits are applied. \"\"\"",
".csv file to specified directory. \"\"\" if not os.path.exists(directory): os.makedirs(directory) write_data = []",
"name in self.lines.keys(): self.lines[name].remove() np_counts = np.array(extract_var(self.jpg_data, \"new_count\")) self.lines[\"edited\"] = ax.fill_between( np.arange(0, self.length)",
"ax.fill_between( np.arange(0, self.length) + 0.5, -BIG_NUM, BIG_NUM, where=extract_var(self.jpg_data, \"is_night\"), facecolor=\"#003459\", alpha=0.5) except KeyError:",
"plot used to select images for export. QUICK GUIDE: c - Hold to",
"print(f\"{len(jpg_paths)} images found.\") jpg_data = attach_exif(jpg_paths, parse_tags) jpg_data.sort(key=sort_key) if process_options == {}: print(\"Crop",
"mid-grade frame differencing method. Takes two images, then finds their absolute difference. Prior",
"> self.plt_vals[\"resp_thresh\"]) if i == self.length-1: curr[\"selected\"] = ( curr[\"new_count\"] > self.plt_vals[\"resp_thresh\"]) prev",
"to_path = os.path.join(export_dir, jpg[\"filename\"]) im = cv2.imread(from_path) resized = resize_long_edge(im, long_edge) cv2.imwrite(to_path, resized)",
"self.length-1: curr[\"selected\"] = ( curr[\"new_count\"] > self.plt_vals[\"resp_thresh\"]) prev = curr if self.dt_present: for",
"like to overwrite it?\") answer = input(\"Y / N > \") if answer.lower()",
"min_area parameter, they are counted as a response (movement). Works very well, little",
"= cv2.imread(row[\"filepath\"], 0) curr = preprocess(jpg, crop, clone) row[\"shape\"] = jpg.shape row[\"median\"] =",
"* move) - is_neg, move): curr = self.jpg_data[i] boo = (not curr[\"selected\"] and",
"0), \"R\": (0, 0, 1, 1), \"L\": (0, 0, -1, -1) } COL_ORDER",
"{ \"ceiling\": 40000, \"resp_thresh\": 20000, \"trans_thresh\": 30, \"smooth_time\": 1, \"night_mult\": 0 } DIRECTION_MULTS",
"w) prev = preprocess(jpg, crop, clone) elif i % timer[0] == 0: stop_watch(i,",
"\"24hr\", \"is_night\", \"timedelta\", \"td_minutes\", \"median\", \"med_diff\", \"count\", \"new_count\", \"selected\", \"user_edit\", \"trans_edit\" ] RS_PARAMS",
"\"\"\" output = [] for dir_, _, files in os.walk(dirpath): if \"_selected\" not",
"format for the clone parameter in process_jpgs(). \"\"\" clone_to = np.array(clone_to) mults =",
"\"filepath\": filepath }) return output def attach_exif(jpg_data, parse_tags=DEFAULT_PARSE): \"\"\"Loops through jpg_data, reading filepaths",
"prev = curr def mark_edits(self, i, kind): \"\"\"Marks which photos to label as",
"cv2.THRESH_BINARY) return cv2.countNonZero(mask) # Like BLURRED, but only sums drawn contours over given",
"\"minspanx\": 5, \"minspany\": 5, \"spancoords\": \"pixels\", \"interactive\": True } # GENERAL FUNCTIONS class",
"in enumerate(jpg_data): row = deep_row.copy() if i == 0: jpg = cv2.imread(row[\"filepath\"], 0)",
"[None, None] self.toggle = False self.buffer = [[None] * 64, [None] * 64]",
"not tuple: cam = Cam(processed_data) print(\"→ Please input a file path for an",
"= self.plt_vals[\"resp_thresh\"] ** (1 / RESP_NUM) SLIDER_PARAMS = [ (\"RESP\", 0.08, 0, 100,",
"a string. Parameters ---------- jpg_data : list of dictionaries Requires that \"filepath\" and",
"in \"zx\": new_edits = {i: self.press[0] for i in lo_to_hi} self.user_edits = {**self.user_edits,",
"[\"Shane\", \"Eve\"] \"\"\" return [x[var] for x in data] def stop_watch(i, timer): progress",
"(key, tag), var, anon in parse_tags: row[var] = anon(tags[key][tag]) output.append(row) return output def",
"many pixels have changed between a photo and its previous, after preprocessing /",
"out any timestamps from images.\") crop, clone_to, directs = crop_clone_preview( cv2.imread(jpg_data[len(jpg_data) // 2][\"filepath\"]))",
"<reponame>SpooksMcGoose/gamecam<gh_stars>0 import json import operator import os import shutil import string import sys",
"return output # THE MEAT AND POTATOES # Requires data from process_jpg(). Object",
"W // scale) lo_H, hi_H = (0 - H // scale), (H +",
"image (SMOOTH slider value). \"\"\" self.pano_i = 0 prev = self.jpg_data[0] for i,",
"\"A\": (-1, -1, 0, 0), \"B\": (1, 1, 0, 0), \"R\": (0, 0,",
"row[\"timedelta\"] = td(seconds=row[\"timedelta\"]) except AttributeError: pass if \"selected\" in row.keys(): row[\"selected\"] = bool(row[\"selected\"])",
"export.\") help(Cam.plot) cam.plot() print(\"→ Save once again, so changes are recorded.\") cam.save(input_filename()) print(\"→",
"mod[y1:y2, x1:x2] mod = cv2.cvtColor(mod, cv2.COLOR_BGR2RGB) ax_mod.imshow(mod) fig.canvas.draw_idle() rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) H,",
"fig.add_subplot(gs[0, 1]) ax_mod = fig.add_subplot(gs[1, :]) crop_RS = RectangleSelector( ax_crop, RS_event, **RS_PARAMS) clone_RS",
"os.path.exists(filename): print(\"File already exists, would you like to overwrite it?\") answer = input(\"Y",
"for k, v in d.items(): if k != \"days\": d[k] = str(v).rjust(2, \"0\")",
"generate_clone_tuples() to generate this object. threshold : int, in range(0, 256) Parameter to",
"= row[\"count\"] if row[\"med_diff\"] > self.plt_vals[\"trans_thresh\"]: new_count = 0 self.mark_edits(i, \"trans_edit\") if self.dt_present:",
"self.toggle = False self.buffer = [[None] * 64, [None] * 64] self.recent_folder =",
"1 elif any(n >= self.length for n in array): array -= 1 else:",
"def draw(): for name in self.lines.keys(): self.lines[name].remove() np_counts = np.array(extract_var(self.jpg_data, \"new_count\")) self.lines[\"edited\"] =",
"in stack) pano = np.hstack([img[:min_y, :] for img in stack]) h, w, *_",
"\"Shane\", \"age\": 22}, {\"name\": \"Eve\", \"age\": 7}] >>> extract_var(data=foo, var=\"name\") [\"Shane\", \"Eve\"] \"\"\"",
"b > H or c < 0 or d > W): trials.append((tups, direct))",
"= os.path.join(directory, new_name) write_row[\"filename\"] = new_name write_row[\"filepath\"] = new_path write_row[\"old_name\"] = row[\"filename\"] write_row[\"old_path\"]",
"toward response (movement). Very noisy, but fast. Parameters ---------- curr : numpy.ndarray Image",
"int, in range(0, 256) Parameter to be passed to the cv2.threshold() function. ksize",
"heart of this module, the interactive plot() method. A simply initialization could be:",
"shutil import string import sys import time import cv2 import piexif import numpy",
"f.write(json.dumps(self.plt_vals) + \"\\n\") f.write(json.dumps(temp_data) + \"\\n\") f.write(json.dumps(self.user_edits)) def load(self, filename): \"\"\"Loads a .sav",
"scale) return cv2.resize(im, (new_w, new_h)) def generate_thumbnails(jpg_data, export_dir, long_edge=1024): \"\"\"Formats a timedelta object",
"to_24_hour(datetime): \"\"\"Converts datetime.datetime type to 24 hour float type. \"\"\" time = datetime.time()",
", - Hold and release to REMOVE EDITS. . - Press to RESET",
"\"trans_thresh\": 30, \"smooth_time\": 1, \"night_mult\": 0 } DIRECTION_MULTS = { \"A\": (-1, -1,",
"the long edge of the image. Smaller sizes speed up performance, but decrease",
"FUNCTIONS def find_imgs(dirpath, img_type=(\".jpg\", \".jpeg\")): \"\"\"Walks directory path, finding all files ending in",
"{\"crop\": crop, \"clone\": clone} print(\"Started processing...\") output = process_jpgs(jpg_data, **process_options) print(\"Done!\") return output",
"None: image_pano(event.xdata) def on_key(event): if event.xdata is not None: if self.press[0] is None:",
"cv2.imread(). Returns ------- tuple Format is (crop, clone_to, clone_directs). The crop_tuple variable can",
"string = str(obj) return '\"' + string + '\"' if \",\" in string",
"corresponding to a variable name. >>> foo = [{\"name\": \"Shane\", \"age\": 22}, {\"name\":",
"k != \"days\": d[k] = str(v).rjust(2, \"0\") return fmt.format(**d) def resize_long_edge(im, size): h,",
"but retained here to shorten the process_jpgs() function. \"\"\" difference = cv2.absdiff(curr, prev)",
"threshold = row[\"median\"]*1.05 try: row[\"count\"] = method(curr, prev, threshold, ksize, min_area) except cv2.error",
"transitions are filtered out based on slider. Counts taken at with nighttime are",
"self.buffer[0]: ind = self.buffer[0].index(n) img = self.buffer[1][ind] self.buffer[0].append(self.buffer[0].pop(ind)) self.buffer[1].append(self.buffer[1].pop(ind)) else: img = cv2.imread(self.jpg_data[n][\"thumbpath\"])",
"h, w = jpg.shape if not crop: crop = (0, h, 0, w)",
"find_imgs() prior to this function. method : function, {SIMPLE, BLURRED, COUNTOURS} Determines the",
"pano = np.hstack([img[:min_y, :] for img in stack]) h, w, *_ = pano.shape",
"list of dictionaries Requires that \"filepath\" is in dictionary keys, which is easily",
"0 or b > H or c < 0 or d > W):",
"if not crop: crop = (0, h, 0, w) prev = preprocess(jpg, crop,",
"boo: if not is_neg: lapse = curr[\"td_minutes\"] else: lapse = prev[\"td_minutes\"] curr[\"selected\"] =",
"to days, hours, minutes, and seconds. Returns ------- str Right justified 2 spaces,",
"in histogram equalization. Parameters ---------- clone_to : tuple Format is (y1, y2, x1,",
"dir_: found = ( f for f in files if f.lower().endswith(img_type) ) for",
"data is desired from EXIF tags. Returns ------- list of dictionaries Same as",
"images, then finds their absolute difference. Prior to thresholding, the differenced image is",
"tups test[a:b, c:d] = test[e:f, g:h] diff = cv2.absdiff(test, image) choose.append((sum(cv2.sumElems(diff)), direct, test))",
"maxv, valinit=init, valfmt=fmt, color=\"#003459\", alpha=0.5) self.sliders[name].on_changed(on_slide) fig.canvas.mpl_connect(\"key_press_event\", on_key) fig.canvas.mpl_connect(\"key_release_event\", off_key) fig.canvas.mpl_connect(\"button_press_event\", on_click) ax.fill_between(",
"= safe_corners(clone_RS.geometry) mod = image.copy() if not cl_ig: mem.clone_tuple = cl_corn trials =",
"\"\"\" return row[\"datetime\"] DEFAULT_PARSE = [ ((\"0th\", 306), \"datetime\", PARSE_DT) ] DEFAULT_PLOT_PARAMS =",
"x2), just like slicing images as np.arrays. fill_from : {\"A\", \"B\", \"R\", \"L\"}",
"return (tuple(clone_to), tuple(clone_from)) # IMAGE PREPROCESSING def CROPPER(image, crop): \"\"\"Returns a cropped image.",
"little noise; slower than others. Parameters ---------- curr : numpy.ndarray Image array, typically",
"as td from matplotlib import pyplot as plt from matplotlib.widgets import Slider, RectangleSelector",
"np_counts, facecolor=\"black\") self.lines[\"threshold\"] = ax.axhline( self.plt_vals[\"resp_thresh\"], color=\"#14B37D\") fig.canvas.draw_idle() def on_slide(val): for key in",
"filepath = os.path.join(dir_, filename) output.append({ \"filename\": filename, \"filepath\": filepath }) return output def",
"print(f\"{progress}% done. {remain} left.\") def strfdelta(tdelta, fmt): \"\"\"Formats a timedelta object as a",
"two images, then finds their absolute difference. Prior to thresholding, the differenced image",
"[np.argmin(kmeans.cluster_centers_), np.argmax(kmeans.cluster_centers_)] for n, index in enumerate(kmeans.labels_): self.jpg_data[n][\"is_night\"] = index in night_indices def",
"image[y1:y2, x1:x2] def CROP_EQUALIZE(image, crop, clone=None): \"\"\"Returns a cropped image with an equalized",
"= im.shape if w > h: scale = size / w else: scale",
"done. {remain} left.\") def strfdelta(tdelta, fmt): \"\"\"Formats a timedelta object as a string.",
"= anon(tags[key][tag]) output.append(row) return output def hist_median(image): \"\"\"Quickly finds the median tone of",
"shorten the process_jpgs() function. \"\"\" difference = cv2.absdiff(curr, prev) _, mask = cv2.threshold(",
"cv2.imread(from_path) resized = resize_long_edge(im, long_edge) cv2.imwrite(to_path, resized) piexif.transplant(from_path, to_path) # SPECIFIC FUNCTIONS def",
"# Displays last two and next two images from response spike. def image_pano(xdata):",
"prev) blurred = cv2.medianBlur(difference, ksize) _, mask = cv2.threshold( blurred, threshold, 255, cv2.THRESH_BINARY)",
"x - Hold and release to INCREASE response value to Inf. z -",
"{} self.user_edits = {} self.press = [None, None] self.toggle = False self.buffer =",
"self.jpg_data[i][kind] = True else: self.jpg_data[i][kind] = True self.jpg_data[i-1][kind] = True def update_counts(self): \"\"\"Updates",
"jpg_data list are sorted by their \"Image DateTime\" EXIF tag. This can be",
"output = [] for deep_row in jpg_data: row = deep_row.copy() tags = piexif.load(row[\"filepath\"])",
"ax_mod = fig.add_subplot(gs[1, :]) crop_RS = RectangleSelector( ax_crop, RS_event, **RS_PARAMS) clone_RS = RectangleSelector(",
"\"[L]eft\" are used for filling the area. Returns ------- pair of tuples Matches",
"\"\"\"Loops through jpg_data, reading filepaths and attaching EXIF data. Useful for cloning out",
"def BLURRED(curr, prev, threshold, ksize=11, min_area=None): \"\"\"Useful, mid-grade frame differencing method. Takes two",
"found in jpg_data, typically the \"count\" variable is used as a response, but",
"row[\"td_minutes\"] = round( row[\"timedelta\"].total_seconds() / 60, 2) day_hr = extract_var(self.jpg_data, \"24hr\") # meds",
": dictionary Parameters used in the plot() method. To reset these values, re-",
"self.jpg_data[0][var] for row in self.jpg_data: curr = row[var] row[new_var] = curr - prev",
"i, row in enumerate(self.jpg_data): row[\"user_edit\"] = False row[\"trans_edit\"] = False new_count = row[\"count\"]",
"prev[\"td_minutes\"] curr[\"selected\"] = ( lapse <= self.plt_vals[\"smooth_time\"]) prev = curr else: nudge =",
"alpha=0.5) except KeyError: pass on_slide(1) plt.show() cv2.destroyAllWindows() if __name__ == \"__main__\": print(\"→ Please",
"but do have a variable for sequence. process_options : dictionary, optional Passes along",
"cv2.imwrite(to_path, resized) piexif.transplant(from_path, to_path) # SPECIFIC FUNCTIONS def find_imgs(dirpath, img_type=(\".jpg\", \".jpeg\")): \"\"\"Walks directory",
"for n, index in enumerate(kmeans.labels_): self.jpg_data[n][\"is_night\"] = index in night_indices def save(self, filename):",
"(clone_from)). For simplicity, use generate_clone_tuples() to generate this object. \"\"\" (a, b, c,",
"int(1e9) NEG_NUM = -0.1 RESP_NUM = 3.5 def PARSE_DT(raw): \"\"\"Default parser for EXIF",
"tdelta : datetime.timedelta Timedelta object to format. fmt : str Contains format calls",
"int, unused Only used in the CONTOURS() function, but retained here to shorten",
"odd number. min_area : int, unused Only used in the CONTOURS() function, but",
"row in temp_data: if \"datetime\" in row.keys(): row[\"datetime\"] = dt.strftime( row[\"datetime\"], \"%Y-%m-%d %H:%M:%S\")",
"i array = np.array(range(i - 2, i + 2)) while True: if any(n",
"in trials: test = image.copy() (a, b, c, d), (e, f, g, h)",
"n in self.buffer[0]: ind = self.buffer[0].index(n) img = self.buffer[1][ind] self.buffer[0].append(self.buffer[0].pop(ind)) self.buffer[1].append(self.buffer[1].pop(ind)) else: img",
"H // scale), (H + H // scale) gs = gridspec.GridSpec(2, 2, height_ratios=[1,",
"self.plt_vals[\"ceiling\"] / 2 self.attach_diffs(\"median\", \"med_diff\") for row in self.jpg_data: if thumb_dir is not",
"- a, d - c h_or_w = np.array([h, h, w, w]) clone_from =",
"self.attach_diffs(\"median\", \"med_diff\") for row in self.jpg_data: if thumb_dir is not None: row[\"thumbpath\"] =",
"have been checked for bounds, unlike generate_clone_tuples). \"\"\" mem = Mem() mem.crop_tuple =",
"i, shift in self.user_edits.items(): self.jpg_data[i][\"new_count\"] = shift self.mark_edits(i, \"user_edit\") def update_events(self): \"\"\"Updates jpg_data",
"in enumerate(self.jpg_data): if row[\"selected\"]: for func in (operator.add, operator.sub): for j in range(nudge+1):",
"Determines the frame differencing method to use. Ordered from left to right based",
"your jpg_data list, and specify the export directory here. These smaller images will",
"previous items. export(directory) Exports selected images and a .csv file. load(filename) Loads a",
"already exists, would you like to overwrite it?\") answer = input(\"Y / N",
"/ 2 for i, count in enumerate(hist): tally += count if tally >",
"passed to the cv2.medianBlur() function. Default is 11. Must be positive, odd number.",
"= {} self.sliders = {} self.user_edits = {} self.press = [None, None] self.toggle",
"events are lumped based on time since last image (SMOOTH slider value). \"\"\"",
"the format for the clone parameter in process_jpgs(). \"\"\" clone_to = np.array(clone_to) mults",
"+ time.second / 3600 def extract_var(data, var): \"\"\"Returns a list of values corresponding",
"Ordered from left to right based on increasing accuracy, decreasing speed. crop :",
"here. These smaller images will be displayed in the Gallery tab. \"\"\" self.resp_var",
"previous, after preprocessing / thresholding. \"\"\" if not threshold: thresh_init = False if",
"Press to RESET ALL EDITS. v - Press for EQUALIZED image (for dark",
"10, self.plt_vals[\"smooth_time\"], \"%.1f\"), (\"NIGHT\", 0.02, -1, 50, self.plt_vals[\"night_mult\"], \"%.1f\") ] def update(): self.update_counts()",
"self.lines[\"selected\"] = ax.fill_between( np.arange(0, self.length) + 0.5, -BIG_NUM, BIG_NUM, where=extract_var(self.jpg_data, \"selected\"), facecolor=\"#F00314\") self.lines[\"count\"]",
"for j in range(nudge+1): ind = func(i, j) try: row = self.jpg_data[ind] if",
"ax_mod.imshow(mod) fig.canvas.draw_idle() rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) H, W, *_ = image.shape scale =",
"False if not clone: preprocess = CROP_EQUALIZE else: preprocess = CROP_CLONE_EQUALIZE output =",
"answer = input(\"Y / N > \") if answer.lower() in (\"y\", \"yes\"): return",
"j) try: row = self.jpg_data[ind] if row[\"new_count\"] < 0: if func == operator.sub:",
"elapsed = time.time() - timer[1] total = elapsed / (progress / 100) remain",
"] def update(): self.update_counts() self.update_events() draw() def draw(): for name in self.lines.keys(): self.lines[name].remove()",
"where=[r[\"trans_edit\"] or r[\"user_edit\"] for r in self.jpg_data], facecolor=\"#D8BFAA\", alpha=0.5) self.lines[\"selected\"] = ax.fill_between( np.arange(0,",
"up performance, but decrease acuity. \"\"\" if not os.path.exists(export_dir): os.makedirs(export_dir) timer = (len(jpg_data)",
"in stack]) h, w, *_ = pano.shape cv2.namedWindow(\"Gallery\", cv2.WINDOW_NORMAL) cv2.imshow(\"Gallery\", cv2.resize(pano, (w //",
"new_path) write_data.append(write_row) if write_data: with open(os.path.join(directory, \"_export.csv\"), \"w\") as f: variables = sorted(write_data[0].keys(),",
"without processing them first. thumb_dir : str, optional If the interactive plot is",
"> H or c < 0 or d > W): trials.append((tups, direct)) choose",
"v in d.items(): if k != \"days\": d[k] = str(v).rjust(2, \"0\") return fmt.format(**d)",
"ignore def RS_event(eclick, erelease): x1, y1 = eclick.xdata, eclick.ydata x2, y2 = erelease.xdata,",
"COUNTOURS. Parameters ---------- curr : numpy.ndarray Image array, typically from cv2.imread(). One of",
"Matches the format ((clone_to), (clone_from)). For simplicity, use generate_clone_tuples() to generate this object.",
"export directory here. These smaller images will be displayed in the Gallery tab.",
"(a < 0 or b > H or c < 0 or d",
"= deep_row.copy() if i == 0: jpg = cv2.imread(row[\"filepath\"], 0) h, w =",
"be: Cam(construct_jpg_data()). After filtering images with the plot, save() and export() should be",
"+ 0.5, -BIG_NUM, BIG_NUM, where=extract_var(self.jpg_data, \"is_night\"), facecolor=\"#003459\", alpha=0.5) except KeyError: pass on_slide(1) plt.show()",
"histogram. Parameters ---------- image : numpy.ndarray Image array, typically from cv2.imread(). crop :",
"but now with desired EXIF data attached. \"\"\" output = [] for deep_row",
"y2, x1, x2 = cr_corn mod = mod[y1:y2, x1:x2] mod = cv2.cvtColor(mod, cv2.COLOR_BGR2RGB)",
"y2, x1, x2 = crop return image[y1:y2, x1:x2] def CROP_EQUALIZE(image, crop, clone=None): \"\"\"Returns",
"= False def update(event): if crop_RS.active: crop_RS.update() if clone_RS.active: clone_RS.update() def safe_corners(geometry): min_y",
"self.buffer[0].index(n) img = self.buffer[1][ind] self.buffer[0].append(self.buffer[0].pop(ind)) self.buffer[1].append(self.buffer[1].pop(ind)) else: img = cv2.imread(self.jpg_data[n][\"thumbpath\"]) self.buffer[0] = self.buffer[0][1:]",
"Crop and clone out any timestamps from images.\") crop, clone_to, directs = crop_clone_preview(",
"PREPROCESSING def CROPPER(image, crop): \"\"\"Returns a cropped image. Parameters ---------- image : numpy.ndarray",
"from cv2.imread(). One of the two images for the absolute difference to be",
"(-1, -1, 0, 0), \"B\": (1, 1, 0, 0), \"R\": (0, 0, 1,",
"is 11. Must be positive, odd number. min_area : int Minimum contour area",
"return round(int(n)) def sort_cols(var_name): if var_name in COL_ORDER: return COL_ORDER.index(var_name) else: return BIG_NUM",
": numpy.ndarray Image array, typically from cv2.imread(). Returns ------- tuple Format is (crop,",
"After thresholding, the resulting white pixels are counted toward response (movement). Works decently,",
"row[\"timedelta\"].total_seconds() / 60, 2) day_hr = extract_var(self.jpg_data, \"24hr\") # meds = extract_var(self.jpg_data, \"median\")",
"[NEG_NUM, i] elif event.key == \"x\": self.press = [BIG_NUM, i] elif event.key ==",
"w = min(a, c), min(b, d) tup = (0, h, 0, w) print(\"FUNCTION",
"parse_tags : list of tuples, optional By default, only Image DateTime is retrieved",
"Loads a .sav file. mark_edits(i) Marks which photos have been edited. plot() Interactive",
"== self.length-1: curr[\"selected\"] = ( curr[\"new_count\"] > self.plt_vals[\"resp_thresh\"]) prev = curr if self.dt_present:",
"self.lines[name].remove() np_counts = np.array(extract_var(self.jpg_data, \"new_count\")) self.lines[\"edited\"] = ax.fill_between( np.arange(0, self.length) + 0.5, -BIG_NUM,",
"= generate_clone_tuples(cl_corn, direct) a, b, c, d = tups[1] if not (a <",
"little faster than COUNTOURS. Parameters ---------- curr : numpy.ndarray Image array, typically from",
"as being selected or not. Then, events are lumped based on time since",
"Format is (y1, y2, x1, x2), just like slicing images as np.arrays. clone",
"THE MEAT AND POTATOES # Requires data from process_jpg(). Object essentially holds data",
"1 else: break stack = [] for n in array: if n in",
"update_events() Updates jpg_data attribute with new events. \"\"\" def __init__(self, jpg_data=False, resp_var=\"count\", thumb_dir=None):",
"0, np_counts, facecolor=\"black\") self.lines[\"threshold\"] = ax.axhline( self.plt_vals[\"resp_thresh\"], color=\"#14B37D\") fig.canvas.draw_idle() def on_slide(val): for key",
"if answer.lower() in (\"y\", \"yes\"): os.makedirs(directory) return directory print(\"Please input a new directory",
"name, minv, maxv, valinit=init, valfmt=fmt, color=\"#003459\", alpha=0.5) self.sliders[name].on_changed(on_slide) fig.canvas.mpl_connect(\"key_press_event\", on_key) fig.canvas.mpl_connect(\"key_release_event\", off_key) fig.canvas.mpl_connect(\"button_press_event\",",
"filepaths. \"\"\" output = [] for dir_, _, files in os.walk(dirpath): if \"_selected\"",
"direct, test)) choose.sort() if choose: _, directs, imgs = list(zip(*choose)) mem.clone_directs = directs",
"cv2.imshow(\"Gallery\", cv2.resize(pano, (w // 2, h // 2))) cv2.waitKey(1) def on_click(event): if event.dblclick",
"attribute. Methods ------- attach_diffs(var, new_var) Finds the difference between the current and previous",
"lapse = curr[\"td_minutes\"] else: lapse = prev[\"td_minutes\"] curr[\"selected\"] = ( lapse <= self.plt_vals[\"smooth_time\"])",
"if self.dt_present: dt_ISO = dt.strftime( row[\"datetime\"], \"%Y%m%dT%H%M%S\" ) else: dt_ISO = str(i) new_name",
"clone) row[\"shape\"] = jpg.shape row[\"median\"] = hist_median(jpg) if not thresh_init: threshold = row[\"median\"]*1.05",
"on_slide(val): for key in self.plt_vals.keys(): if key != \"ceiling\": slider_key = key[:key.find(\"_\")].upper() if",
"new counts (response metric). Variable new_count is attached to jpg_data. Day to night",
"prev.shape[:2] h, w = min(a, c), min(b, d) tup = (0, h, 0,",
"- Press for EQUALIZED image (for dark images). \"\"\" try: self.jpg_data except AttributeError",
"100, mod, \"%.2e\"), (\"TRANS\", 0.06, 0, 120, self.plt_vals[\"trans_thresh\"], \"%.1f\"), (\"SMOOTH\", 0.04, 0, 10,",
"if n in self.buffer[0]: ind = self.buffer[0].index(n) img = self.buffer[1][ind] self.buffer[0].append(self.buffer[0].pop(ind)) self.buffer[1].append(self.buffer[1].pop(ind)) else:",
"are of same size, \" \"consider using the crop parameter.\\n\" f\"Try crop={tup}.\") return",
"x2 = crop return image[y1:y2, x1:x2] def CROP_EQUALIZE(image, crop, clone=None): \"\"\"Returns a cropped",
"tuple, optional By default, finds JPG image types, but can be changed if",
"a .sav file. update_counts() Updates jpg_data attribute with new counts. update_events() Updates jpg_data",
"directory path with camera-trapping images.\") jpg_paths = find_imgs(input_directory()) jpg_data = attach_exif(jpg_paths) jpg_data.sort(key=lambda x:",
"] RS_PARAMS = { \"drawtype\": \"box\", \"useblit\": True, \"button\": [1, 3], \"minspanx\": 5,",
"to right based on increasing accuracy, decreasing speed. crop : tuple Format is",
"powerful frame differencing method. Takes two images, then finds their absolute difference. Prior",
"init, fmt in SLIDER_PARAMS: slider_ax = fig.add_axes([0.125, pos, 0.8, 0.02]) self.sliders[name] = Slider(",
"((clone_to), (clone_from)). For simplicity, use generate_clone_tuples() to generate this object. \"\"\" (a, b,",
"return filename elif filename: return filename def input_directory(): while True: directory = input(\"DIRPATH",
"Inf. z - Hold and release to DECREASE response value to 0. ,",
"attaching EXIF data. Useful for cloning out timestamps, aids in histogram equalization. Parameters",
"+= 1 elif any(n >= self.length for n in array): array -= 1",
"= json.loads(next(f)) for row in temp_data: if \"datetime\" in row.keys(): row[\"datetime\"] = dt.strptime(",
"for EXIF \"Image DateTime\" tag. \"\"\" str_ = ''.join(x for x in str(raw)",
"threshold, ksize, min_area) except cv2.error as inst: if \"(-209:Sizes\" in str(inst): (a, b),",
"long edge of the image. Smaller sizes speed up performance, but decrease acuity.",
"= False row[\"trans_edit\"] = False new_count = row[\"count\"] if row[\"med_diff\"] > self.plt_vals[\"trans_thresh\"]: new_count",
"RESET ALL EDITS. v - Press for EQUALIZED image (for dark images). \"\"\"",
"EXIF tag. This can be changed if images don\"t have a datetime, but",
"- Hold and release to INCREASE response value to Inf. z - Hold",
"strings with commas in them. \"\"\" string = str(obj) return '\"' + string",
"int, unused Used in the BLURRED() and CONTOURS() functions, but retained here to",
"edits, event, etc. plot_params : dictionary Parameters used in the plot() method. To",
"else: lapse = prev[\"td_minutes\"] curr[\"selected\"] = ( lapse <= self.plt_vals[\"smooth_time\"]) prev = curr",
"retained here to shorten the process_jpgs() function. min_area : int, unused Only used",
"attribute with new counts. update_events() Updates jpg_data attribute with new events. \"\"\" def",
"fmt : str Contains format calls to days, hours, minutes, and seconds. Returns",
"sys import time import cv2 import piexif import numpy as np from sklearn.cluster",
"else: print(inst) prev = curr output.append(row) return output def construct_jpg_data( dirpath, parse_tags=DEFAULT_PARSE, sort_key=SORT_BY_DT,",
"their absolute difference. A simple threshold is called, the resulting white pixels are",
"jpg_data with new counts (response metric). Variable new_count is attached to jpg_data. Day",
"**RS_PARAMS) clone_RS = RectangleSelector( ax_clone, RS_event, **RS_PARAMS) ax_crop.set_title(\"Crop\") ax_clone.set_title(\"Clone\") ax_mod.set_title(\"Result\") for axe in",
"* 64] self.recent_folder = os.path.expanduser(\"~\") # Cam objects don\"t need to have data",
"\"median\") X = np.array(day_hr).reshape(-1, 1) kmeans = KMeans(n_clusters=3).fit(X) night_indices = [np.argmin(kmeans.cluster_centers_), np.argmax(kmeans.cluster_centers_)] for",
"value). \"\"\" self.pano_i = 0 prev = self.jpg_data[0] for i, curr in enumerate(self.jpg_data):",
"\"datetime\" in self.jpg_data[0].keys() h, w = jpg_data[0][\"shape\"] self.plt_vals[\"ceiling\"] = h * w *",
"the directs list (all have been checked for bounds, unlike generate_clone_tuples). \"\"\" mem",
"which is easily provided by find_imgs() prior to this function. method : function,",
"SIMPLE(curr, prev, threshold, ksize=None, min_area=None): \"\"\"Most basic frame differencing method. Takes two images,",
"x1, x2 = crop return image[y1:y2, x1:x2] def CROP_EQUALIZE(image, crop, clone=None): \"\"\"Returns a",
"img = self.buffer[1][ind] self.buffer[0].append(self.buffer[0].pop(ind)) self.buffer[1].append(self.buffer[1].pop(ind)) else: img = cv2.imread(self.jpg_data[n][\"thumbpath\"]) self.buffer[0] = self.buffer[0][1:] +",
"filename in found: filepath = os.path.join(dir_, filename) output.append({ \"filename\": filename, \"filepath\": filepath })",
"def on_click(event): if event.dblclick and event.xdata is not None: image_pano(event.xdata) def on_key(event): if",
"row.keys(): row[\"datetime\"] = dt.strptime( row[\"datetime\"], \"%Y-%m-%d %H:%M:%S\" ) self.dt_present = True else: self.dt_present",
"function. parse_tags : list of tuples, optional By default, only Image DateTime is",
"cv2.countNonZero(mask) # Like BLURRED, but only sums drawn contours over given limit. def",
"pixels within the clone_to area. Neighboring pixels from \"[A]bove,\" \"[B]elow,\" \"[R]ight,\" and \"[L]eft\"",
"write_row[\"filename\"] = new_name write_row[\"filepath\"] = new_path write_row[\"old_name\"] = row[\"filename\"] write_row[\"old_path\"] = row[\"filepath\"] shutil.copy2(row[\"filepath\"],",
"f.write(\"\\n\") else: f.write(\",\".join(variables) + \"\\n\") f.write(\",\".join(csv_safe(row[v]) for v in variables)) else: raise ValueError(\"No",
"master_set.add(ind) except IndexError: pass for i in master_set: self.jpg_data[i][\"selected\"] = True def plot(self):",
"= divmod(rem, 60) for k, v in d.items(): if k != \"days\": d[k]",
"fig.canvas.mpl_connect(\"key_release_event\", off_key) fig.canvas.mpl_connect(\"button_press_event\", on_click) ax.fill_between( np.arange(0, self.length) + 0.5, -BIG_NUM, 0, facecolor=\"white\", alpha=0.75,",
"\"clone\": clone} print(\"Started processing...\") output = process_jpgs(jpg_data, **process_options) print(\"Done!\") return output # THE",
"# IMAGE PREPROCESSING def CROPPER(image, crop): \"\"\"Returns a cropped image. Parameters ---------- image",
"(w // 2, h // 2))) cv2.waitKey(1) def on_click(event): if event.dblclick and event.xdata",
"the format ((clone_to), (clone_from)). For simplicity, use generate_clone_tuples() to generate this object. \"\"\"",
"ksize) _, mask = cv2.threshold( blurred, threshold, 255, cv2.THRESH_BINARY) return cv2.countNonZero(mask) # Like",
"pair of tuples Matches the format for the clone parameter in process_jpgs(). \"\"\"",
"with open(filename, \"w\") as f: f.write(json.dumps(self.plt_vals) + \"\\n\") f.write(json.dumps(temp_data) + \"\\n\") f.write(json.dumps(self.user_edits)) def",
"self.plt_vals = json.loads(next(f)) self.plt_vals[\"resp_thresh\"] = ( self.plt_vals[\"resp_thresh\"] ** (1 / RESP_NUM)) temp_data =",
"= 0 self.mark_edits(i, \"trans_edit\") if self.dt_present: new_count *= 1 + ( self.plt_vals[\"night_mult\"] *",
"would you like to make it?\") answer = input(\"Y / N > \")",
"len(self.jpg_data) self.user_edits = {int(k): v for k, v in temp_dict.items()} def export(self, directory):",
"cv2.imread(row[\"filepath\"], 0) curr = preprocess(jpg, crop, clone) row[\"shape\"] = jpg.shape row[\"median\"] = hist_median(jpg)",
"def construct_jpg_data( dirpath, parse_tags=DEFAULT_PARSE, sort_key=SORT_BY_DT, process_options={} ): \"\"\"Performs all necessary steps to make",
"g, h) = tups test[a:b, c:d] = test[e:f, g:h] diff = cv2.absdiff(test, image)",
"2 self.attach_diffs(\"median\", \"med_diff\") for row in self.jpg_data: if thumb_dir is not None: row[\"thumbpath\"]",
"to generate this object. threshold : int, in range(0, 256) Parameter to be",
"0 prev = self.jpg_data[0] for i, curr in enumerate(self.jpg_data): prev[\"selected\"] = ( prev[\"new_count\"]",
"shift self.mark_edits(i, \"user_edit\") def update_events(self): \"\"\"Updates jpg_data with new events (runs of detection).",
"mod = self.sliders[slider_key].val ** RESP_NUM self.plt_vals[key] = mod self.sliders[slider_key].valtext.set_text(\"%.2e\" % mod) else: self.plt_vals[key]",
"\"\"\"Interactive viewer to quickly get crop and clone parameters. Parameters ---------- image :",
"w > h: scale = size / w else: scale = size /",
"Cam() object is desired for a load() method call. resp_var : str, optional",
"pyplot as plt from matplotlib.widgets import Slider, RectangleSelector import matplotlib.gridspec as gridspec #",
"process_jpgs(). \"\"\" clone_to = np.array(clone_to) mults = np.array(DIRECTION_MULTS[fill_from[0].upper()]) a, b, c, d =",
"size / h new_w = rint(w * scale) new_h = rint(h * scale)",
"enumerate(self.jpg_data): row[\"user_edit\"] = False row[\"trans_edit\"] = False new_count = row[\"count\"] if row[\"med_diff\"] >",
"crop_clone_preview( cv2.imread(jpg_data[len(jpg_data) // 2][\"filepath\"])) clone = (generate_clone_tuples(clone_to, directs[0]) if clone_to else False) process_options",
"if not is_neg: lapse = curr[\"td_minutes\"] else: lapse = prev[\"td_minutes\"] curr[\"selected\"] = (",
"on_slide(1) plt.show() cv2.destroyAllWindows() if __name__ == \"__main__\": print(\"→ Please input a directory path",
"valinit=init, valfmt=fmt, color=\"#003459\", alpha=0.5) self.sliders[name].on_changed(on_slide) fig.canvas.mpl_connect(\"key_press_event\", on_key) fig.canvas.mpl_connect(\"key_release_event\", off_key) fig.canvas.mpl_connect(\"button_press_event\", on_click) ax.fill_between( np.arange(0,",
"JPG image types, but can be changed if camera exports a different filetype.",
"time.hour + time.minute / 60 + time.second / 3600 def extract_var(data, var): \"\"\"Returns",
"image.shape scale = 10 lo_W, hi_W = (0 - W // scale), (W",
"not in dir_: found = ( f for f in files if f.lower().endswith(img_type)",
"Parameters ---------- jpg_data : list of dictionaries Requires that \"filepath\" and \"filename\" is",
"PROCESSING def process_jpgs( jpg_data, method=CONTOURS, crop=False, clone=False, threshold=False, ksize=11, min_area=100 ): \"\"\"Generates a",
"Examine DEFAULT_PARSE as an example parameter to pass to attach_exif(), if more data",
"use resize_with_exif() on your jpg_data list, and specify the export directory here. These",
"/ RESP_NUM)) temp_data = json.loads(next(f)) temp_dict = json.loads(next(f)) for row in temp_data: if",
"images for export.\") help(Cam.plot) cam.plot() print(\"→ Save once again, so changes are recorded.\")",
"= cv2.imread(row[\"filepath\"], 0) h, w = jpg.shape if not crop: crop = (0,",
"curr[\"selected\"] = ( lapse <= self.plt_vals[\"smooth_time\"]) prev = curr else: nudge = int(self.plt_vals[\"smooth_time\"])",
"= curr if self.dt_present: for move in (1, -1): is_neg = move <",
"fig = plt.figure() ax = fig.add_subplot(111) fig.canvas.set_window_title(\"Response Filtering\") fig.subplots_adjust(0.07, 0.18, 0.97, 0.97) ax.grid(alpha=0.4)",
"now with the median image tone and a count variable, which respresents how",
"from datetime import datetime as dt, timedelta as td from matplotlib import pyplot",
"10) // timer[0] elapsed = time.time() - timer[1] total = elapsed / (progress",
"of 100 pixels. Larger numbers decreases sensitivity. \"\"\" difference = cv2.absdiff(curr, prev) blurred",
"and export image data. Contains the heart of this module, the interactive plot()",
"facecolor=\"white\", alpha=0.75, zorder=2) try: ax.fill_between( np.arange(0, self.length) + 0.5, -BIG_NUM, BIG_NUM, where=extract_var(self.jpg_data, \"is_night\"),",
"'\"' if \",\" in string else string def to_24_hour(datetime): \"\"\"Converts datetime.datetime type to",
"out timestamps, aids in histogram equalization. Parameters ---------- clone_to : tuple Format is",
"\"\"\" str_ = ''.join(x for x in str(raw) if x in string.digits) return",
"prev = curr if self.dt_present: for move in (1, -1): is_neg = move",
"should be called so as not to lose any prior work. Attributes ----------",
"c), min(b, d) tup = (0, h, 0, w) print(\"FUNCTION ABORTED!\\n\" \"Not all",
"new_w = rint(w * scale) new_h = rint(h * scale) return cv2.resize(im, (new_w,",
"which photos have been edited. plot() Interactive plot used to select images for",
"and seconds. Returns ------- str Right justified 2 spaces, filled with zeros. \"\"\"",
"2, i + 2)) while True: if any(n < 0 for n in",
"in self.jpg_data[0].keys() h, w = jpg_data[0][\"shape\"] self.plt_vals[\"ceiling\"] = h * w * 0.02",
"True def update_counts(self): \"\"\"Updates jpg_data with new counts (response metric). Variable new_count is",
"acuity. \"\"\" if not os.path.exists(export_dir): os.makedirs(export_dir) timer = (len(jpg_data) // 10, time.time()) for",
"\"\"\" if not os.path.exists(export_dir): os.makedirs(export_dir) timer = (len(jpg_data) // 10, time.time()) for i,",
"i != self.pano_i: self.pano_i = i array = np.array(range(i - 2, i +",
"1, 1), \"L\": (0, 0, -1, -1) } COL_ORDER = [ \"old_name\", \"old_path\",",
"enumerate(write_data): if i != 0: f.write(\"\\n\") else: f.write(\",\".join(variables) + \"\\n\") f.write(\",\".join(csv_safe(row[v]) for v",
"is an area of 100 pixels. Larger numbers decreases sensitivity. \"\"\" difference =",
"cropped image. Parameters ---------- image : numpy.ndarray Image array, typically from cv2.imread(). crop",
"ax.fill_between( np.arange(0, self.length) + 0.5, -BIG_NUM, BIG_NUM, where=extract_var(self.jpg_data, \"selected\"), facecolor=\"#F00314\") self.lines[\"count\"] = ax.fill_between(",
"100 pixels. Larger numbers decreases sensitivity. Returns ------- list of dictionaries Same as",
"0, w) print(\"FUNCTION ABORTED!\\n\" \"Not all images are of same size, \" \"consider",
"False row[\"trans_edit\"] = False if self.dt_present: self.attach_diffs(\"datetime\", \"timedelta\") for row in self.jpg_data: row[\"24hr\"]",
"= row[\"filepath\"] row[\"count\"] = row[self.resp_var] row[\"med_diff\"] = abs(row[\"med_diff\"]) row[\"selected\"] = False row[\"user_edit\"] =",
"= self.buffer[0][1:] + [n] self.buffer[1] = self.buffer[1][1:] + [img] if self.toggle: gray =",
"a response (movement). Default is an area of 100 pixels. Larger numbers decreases",
"before the jpg_data list can be fed into the Cam() class for response",
"but includes variables denoting selection, edits, event, etc. plot_params : dictionary Parameters used",
"is the last step before the jpg_data list can be fed into the",
"if not (a < 0 or b > H or c < 0",
"1, \"night_mult\": 0 } DIRECTION_MULTS = { \"A\": (-1, -1, 0, 0), \"B\":",
"as dt, timedelta as td from matplotlib import pyplot as plt from matplotlib.widgets",
"tags. sort_key : function, optional By default, dictionaries within the jpg_data list are",
"open(os.path.join(directory, \"_export.csv\"), \"w\") as f: variables = sorted(write_data[0].keys(), key=sort_cols) for i, row in",
"where=extract_var(self.jpg_data, \"is_night\"), facecolor=\"#003459\", alpha=0.5) except KeyError: pass on_slide(1) plt.show() cv2.destroyAllWindows() if __name__ ==",
"from response spike. def image_pano(xdata): i = int(round(xdata)) if i != self.pano_i: self.pano_i",
"mem.clone_tuple = cl_corn trials = [] for direct in (\"A\", \"B\", \"R\", \"L\"):",
"(c, d) = curr.shape[:2], prev.shape[:2] h, w = min(a, c), min(b, d) tup",
"CROPPER(image, crop) return cv2.equalizeHist(image) def CROP_CLONE_EQUALIZE(image, crop, clone): \"\"\"Returns a cropped image, with",
"number. min_area : int, unused Only used in the CONTOURS() function, but retained",
"finding all files ending in img_type. Parameters ---------- dirpath : str Path to",
"time.time()) for i, deep_row in enumerate(jpg_data): row = deep_row.copy() if i == 0:",
"__init__(self, jpg_data=False, resp_var=\"count\", thumb_dir=None): \"\"\" Parameters ---------- jpg_data : list of dictionaries, optional",
"self.jpg_data[i][kind] = True self.jpg_data[i-1][kind] = True def update_counts(self): \"\"\"Updates jpg_data with new counts",
"/ N > \") if answer.lower() in (\"y\", \"yes\"): return filename elif filename:",
"mask = cv2.threshold( difference, threshold, 255, cv2.THRESH_BINARY) return cv2.countNonZero(mask) # Difference, blur (amount",
"type. \"\"\" time = datetime.time() return time.hour + time.minute / 60 + time.second",
"= row[\"median\"]*1.05 try: row[\"count\"] = method(curr, prev, threshold, ksize, min_area) except cv2.error as",
"optional By default, only Image DateTime is retrieved from EXIF data using DEFAULT_PARSE.",
"the cv2.threshold() function. ksize : int, unused Used in the BLURRED() and CONTOURS()",
"TypeError: pass plt.rc(\"font\", **{\"size\": 8}) plt.rcParams[\"keymap.back\"] = \"left, backspace\" fig = plt.figure() ax",
"+ (h_or_w * mults) return (tuple(clone_to), tuple(clone_from)) # IMAGE PREPROCESSING def CROPPER(image, crop):",
"str Right justified 2 spaces, filled with zeros. \"\"\" d = {\"days\": tdelta.days}",
"count in enumerate(hist): tally += count if tally > threshold: return i def",
"is_neg: lapse = curr[\"td_minutes\"] else: lapse = prev[\"td_minutes\"] curr[\"selected\"] = ( lapse <=",
"\"B\", \"R\", \"L\"} Calls directional tuples from DIRECTION_MULTS to fill pixels within the",
"\"z\": self.press = [NEG_NUM, i] elif event.key == \"x\": self.press = [BIG_NUM, i]",
"print(\"→ Please input a file path for an initial save.\") cam.save(input_filename()) print(\"→ Use",
"(0, 0, 1, 1), \"L\": (0, 0, -1, -1) } COL_ORDER = [",
"retained here to shorten the process_jpgs() function. \"\"\" difference = cv2.absdiff(curr, prev) blurred",
"and i: stop_watch(i, timer) from_path = jpg[\"filepath\"] to_path = os.path.join(export_dir, jpg[\"filename\"]) im =",
"elapsed / (progress / 100) remain = strfdelta(td(seconds=total - elapsed), \"{days}:{hours}:{minutes}:{seconds}\") print(f\"{progress}% done.",
"-BIG_NUM, 0, facecolor=\"white\", alpha=0.75, zorder=2) try: ax.fill_between( np.arange(0, self.length) + 0.5, -BIG_NUM, BIG_NUM,",
"import pyplot as plt from matplotlib.widgets import Slider, RectangleSelector import matplotlib.gridspec as gridspec",
"n in array): array -= 1 else: break stack = [] for n",
"if row[\"med_diff\"] > self.plt_vals[\"trans_thresh\"]: new_count = 0 self.mark_edits(i, \"trans_edit\") if self.dt_present: new_count *=",
"+ 0.5, -BIG_NUM, 0, facecolor=\"white\", alpha=0.75, zorder=2) try: ax.fill_between( np.arange(0, self.length) + 0.5,",
"jpg_data, plot_params, and user_edits. \"\"\" temp_data = [ {k: v for k, v",
"0.5, -BIG_NUM, BIG_NUM, where=extract_var(self.jpg_data, \"selected\"), facecolor=\"#F00314\") self.lines[\"count\"] = ax.fill_between( range(self.length), 0, np_counts, facecolor=\"black\")",
"Parameter to be passed to the cv2.threshold() function. ksize : int Parameter to",
"0.5, -BIG_NUM, 0, facecolor=\"white\", alpha=0.75, zorder=2) try: ax.fill_between( np.arange(0, self.length) + 0.5, -BIG_NUM,",
"to the process_jpgs() function. By default, no options are specified. Make sure that",
"stack]) h, w, *_ = pano.shape cv2.namedWindow(\"Gallery\", cv2.WINDOW_NORMAL) cv2.imshow(\"Gallery\", cv2.resize(pano, (w // 2,",
"name in (\"count\", \"threshold\", \"selected\", \"edited\"): self.lines[name] = ax.axhline() for name, pos, minv,",
"\"zxc,\": image_pano(event.xdata) elif event.key == \"v\": self.toggle = not self.toggle image_pano(event.xdata) elif event.key",
"jpg_data list can be fed into the Cam() class for response filtering. Parameters",
"self.lines[\"edited\"] = ax.fill_between( np.arange(0, self.length) + 0.5, -BIG_NUM, BIG_NUM, where=[r[\"trans_edit\"] or r[\"user_edit\"] for",
"if __name__ == \"__main__\": print(\"→ Please input a directory path with camera-trapping images.\")",
"response (movement). Default is an area of 100 pixels. Larger numbers decreases sensitivity.",
"directory. parse_tags : list of tuples, optional By default, only Image DateTime is",
"dirpath : str Path to an image-containing directory. parse_tags : list of tuples,",
"= jpg.shape if not crop: crop = (0, h, 0, w) prev =",
"= cv2.cvtColor(mod, cv2.COLOR_BGR2RGB) ax_mod.imshow(mod) fig.canvas.draw_idle() rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) H, W, *_ =",
"on images read from jpg_data filepaths before being passed on to frame differencing",
"like slicing images as np.arrays. clone : pair of tuples Matches the format",
"generate a response metric. This is the last step before the jpg_data list",
"\"\"\" try: self.jpg_data except AttributeError as inst: raise inst mod = self.plt_vals[\"resp_thresh\"] **",
"[None, None] update() except TypeError: pass plt.rc(\"font\", **{\"size\": 8}) plt.rcParams[\"keymap.back\"] = \"left, backspace\"",
"BLURRED, COUNTOURS} Determines the frame differencing method to use. Ordered from left to",
"= False if \"timedelta\" in row.keys(): try: row[\"timedelta\"] = td(seconds=row[\"timedelta\"]) except AttributeError: pass",
"very well, little noise; slower than others. Parameters ---------- curr : numpy.ndarray Image",
"= str(v).rjust(2, \"0\") return fmt.format(**d) def resize_long_edge(im, size): h, w, *_ = im.shape",
"np.array(day_hr).reshape(-1, 1) kmeans = KMeans(n_clusters=3).fit(X) night_indices = [np.argmin(kmeans.cluster_centers_), np.argmax(kmeans.cluster_centers_)] for n, index in",
"0, -1, -1) } COL_ORDER = [ \"old_name\", \"old_path\", \"filename\", \"filepath\", \"shape\", \"datetime\",",
"direct)) choose = [] for (tups, direct) in trials: test = image.copy() (a,",
"\"\"\" return [x[var] for x in data] def stop_watch(i, timer): progress = (i",
"to pass to attach_exif(), if more data is desired from EXIF tags. sort_key",
"str Contains format calls to days, hours, minutes, and seconds. Returns ------- str",
"str, optional If the interactive plot is laggy, use resize_with_exif() on your jpg_data",
"the contours are above the min_area parameter, they are counted as a response",
"print(\"→ Crop and clone out any timestamps from images.\") crop, clone_to, directs =",
"- elapsed), \"{days}:{hours}:{minutes}:{seconds}\") print(f\"{progress}% done. {remain} left.\") def strfdelta(tdelta, fmt): \"\"\"Formats a timedelta",
"with the median image tone and a count variable, which respresents how many",
"but retained here to shorten the process_jpgs() function. min_area : int, unused Only",
"= new_path write_row[\"old_name\"] = row[\"filename\"] write_row[\"old_path\"] = row[\"filepath\"] shutil.copy2(row[\"filepath\"], new_path) write_data.append(write_row) if write_data:",
"and release to DECREASE response value to 0. , - Hold and release",
"Filtering\") fig.subplots_adjust(0.07, 0.18, 0.97, 0.97) ax.grid(alpha=0.4) ax.set_axisbelow(True) ax.set_ylim([0, self.plt_vals[\"ceiling\"]]) ax.set_xlim([0, min(500, self.length)]) ax.set_xlabel(\"Frame\")",
"key=sort_cols) for i, row in enumerate(write_data): if i != 0: f.write(\"\\n\") else: f.write(\",\".join(variables)",
"the Cam() class for response filtering. Parameters ---------- jpg_data : list of dictionaries",
"jpg_data with new events (runs of detection). An event is a contiguous sequence",
"Use the interactive plot to select images for export.\") help(Cam.plot) cam.plot() print(\"→ Save",
"print(\"File already exists, would you like to overwrite it?\") answer = input(\"Y /",
"= extract_var(self.jpg_data, \"24hr\") # meds = extract_var(self.jpg_data, \"median\") X = np.array(day_hr).reshape(-1, 1) kmeans",
"- c h_or_w = np.array([h, h, w, w]) clone_from = clone_to + (h_or_w",
"respresents how many pixels have changed between a photo and its previous, after",
"json.loads(next(f)) for row in temp_data: if \"datetime\" in row.keys(): row[\"datetime\"] = dt.strptime( row[\"datetime\"],",
"row[\"datetime\"], \"%Y%m%dT%H%M%S\" ) else: dt_ISO = str(i) new_name = \"_\".join((dt_ISO, row[\"filename\"])) new_path =",
"crop_clone_preview( cv2.imread(jpg_data[len(jpg_data) // 2][\"filepath\"])) clone = generate_clone_tuples(clone_to, directs[0]) if clone_to else False print(\"→",
"jpg.shape row[\"median\"] = hist_median(jpg) if not thresh_init: threshold = row[\"median\"]*1.05 try: row[\"count\"] =",
"return output def construct_jpg_data( dirpath, parse_tags=DEFAULT_PARSE, sort_key=SORT_BY_DT, process_options={} ): \"\"\"Performs all necessary steps",
"that \"filepath\" and \"filename\" is in dictionary keys, which is easily provided by",
"g, h) = clone image[a:b, c:d] = image[e:f, g:h] image = CROPPER(image, crop)",
"an equalized histogram. Parameters ---------- image : numpy.ndarray Image array, typically from cv2.imread().",
"mark_edits(self, i, kind): \"\"\"Marks which photos to label as edited based on [i]ndex.",
"cl_corn, cl_ig = safe_corners(clone_RS.geometry) mod = image.copy() if not cl_ig: mem.clone_tuple = cl_corn",
"= len(self.jpg_data) self.user_edits = {int(k): v for k, v in temp_dict.items()} def export(self,",
"0, 10, self.plt_vals[\"smooth_time\"], \"%.1f\"), (\"NIGHT\", 0.02, -1, 50, self.plt_vals[\"night_mult\"], \"%.1f\") ] def update():",
"needed to feed a Cam() object with its initial data. \"\"\" jpg_paths =",
"timer = (len(jpg_data) // 10, time.time()) for i, jpg in enumerate(jpg_data): if not",
"directory = input(\"DIRPATH > \") if os.path.isdir(directory): return directory else: print(\"Directory does not",
"calls to days, hours, minutes, and seconds. Returns ------- str Right justified 2",
"\"\"\"Formats a timedelta object as a string. Parameters ---------- tdelta : datetime.timedelta Timedelta",
"= int(round(event.xdata)) if event.key == \"z\": self.press = [NEG_NUM, i] elif event.key ==",
"os.makedirs(export_dir) timer = (len(jpg_data) // 10, time.time()) for i, jpg in enumerate(jpg_data): if",
"save() and export() should be called so as not to lose any prior",
"KMeans from datetime import datetime as dt, timedelta as td from matplotlib import",
"= new_name write_row[\"filepath\"] = new_path write_row[\"old_name\"] = row[\"filename\"] write_row[\"old_path\"] = row[\"filepath\"] shutil.copy2(row[\"filepath\"], new_path)",
"FRAME DIFFERENCING METHODS # Bare-bones. Take difference, threshold, and sum the mask. def",
"dictionaries. \"\"\" prev = self.jpg_data[0][var] for row in self.jpg_data: curr = row[var] row[new_var]",
"np.arrays. clone : pair of tuples Matches the format ((clone_to), (clone_from)). For simplicity,",
"// scale), (H + H // scale) gs = gridspec.GridSpec(2, 2, height_ratios=[1, 1.25])",
"clone=clone) if type(processed_data) is not tuple: cam = Cam(processed_data) print(\"→ Please input a",
"sklearn.cluster import KMeans from datetime import datetime as dt, timedelta as td from",
"crop_clone_preview(image): \"\"\"Interactive viewer to quickly get crop and clone parameters. Parameters ---------- image",
"images selected for export.\") def attach_diffs(self, var, new_var): \"\"\"Finds the difference between the",
"(\"count\", \"threshold\", \"selected\", \"edited\"): self.lines[name] = ax.axhline() for name, pos, minv, maxv, init,",
"the median tone of a grayscale image. \"\"\" px_count = image.shape[0] * image.shape[1]",
"contours: area = cv2.contourArea(cnt) if area > min_area: count += area return count",
"min_area=None): \"\"\"Useful, mid-grade frame differencing method. Takes two images, then finds their absolute",
"f.write(json.dumps(temp_data) + \"\\n\") f.write(json.dumps(self.user_edits)) def load(self, filename): \"\"\"Loads a .sav file, the Cam()",
"An event is a contiguous sequence of images. First, images are identified as",
"i] elif event.key == \"x\": self.press = [BIG_NUM, i] elif event.key == \",\":",
"event.key in \"zxc,\": image_pano(event.xdata) elif event.key == \"v\": self.toggle = not self.toggle image_pano(event.xdata)",
"self.buffer[0][1:] + [n] self.buffer[1] = self.buffer[1][1:] + [img] if self.toggle: gray = cv2.cvtColor(img,",
"tally = 0 threshold = px_count / 2 for i, count in enumerate(hist):",
"not self.toggle image_pano(event.xdata) elif event.key == \".\": self.user_edits = {} def off_key(event): try:",
"BIG_NUM def input_filename(): while True: filename = input(\"FILEPATH > \") if os.path.exists(filename): print(\"File",
"sorted((self.press[1], i)) lo_to_hi = range(max(0, low), min(self.length, high+1)) if event.key in \"zx\": new_edits",
"two images from response spike. def image_pano(xdata): i = int(round(xdata)) if i !=",
"int, optional By default, images will be resized to 1024 pixels on the",
"0 or d > W): trials.append((tups, direct)) choose = [] for (tups, direct)",
"CROP_EQUALIZE(image, crop, clone=None): \"\"\"Returns a cropped image with an equalized histogram. Parameters ----------",
"\"interactive\": True } # GENERAL FUNCTIONS class Mem(): def __init__(self): pass def rint(n):",
"key found in jpg_data, typically the \"count\" variable is used as a response,",
"fig.canvas.draw_idle() rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) H, W, *_ = image.shape scale = 10",
"generate_clone_tuples() to generate this object. \"\"\" image = CROPPER(image, crop) return cv2.equalizeHist(image) def",
"---------- tdelta : datetime.timedelta Timedelta object to format. fmt : str Contains format",
"* mults) return (tuple(clone_to), tuple(clone_from)) # IMAGE PREPROCESSING def CROPPER(image, crop): \"\"\"Returns a",
"for i, jpg in enumerate(jpg_data): if not i % timer[0] and i: stop_watch(i,",
"= (generate_clone_tuples(clone_to, directs[0]) if clone_to else False) process_options = {\"crop\": crop, \"clone\": clone}",
"to a variable name. >>> foo = [{\"name\": \"Shane\", \"age\": 22}, {\"name\": \"Eve\",",
"0: self.jpg_data[i][kind] = True else: self.jpg_data[i][kind] = True self.jpg_data[i-1][kind] = True def update_counts(self):",
"clone_to, directs = crop_clone_preview( cv2.imread(jpg_data[len(jpg_data) // 2][\"filepath\"])) clone = (generate_clone_tuples(clone_to, directs[0]) if clone_to",
"% mod) else: self.plt_vals[key] = self.sliders[slider_key].val update() # Displays last two and next",
"+ 0.5, -BIG_NUM, BIG_NUM, where=extract_var(self.jpg_data, \"selected\"), facecolor=\"#F00314\") self.lines[\"count\"] = ax.fill_between( range(self.length), 0, np_counts,",
"sizes speed up performance, but decrease acuity. \"\"\" if not os.path.exists(export_dir): os.makedirs(export_dir) timer",
"files if f.lower().endswith(img_type) ) for filename in found: filepath = os.path.join(dir_, filename) output.append({",
"(y1, y2, x1, x2), just like slicing images as np.arrays. clone : pair",
"f in files if f.lower().endswith(img_type) ) for filename in found: filepath = os.path.join(dir_,",
"= True def plot(self): \"\"\"Interactive plot used to select images for export. QUICK",
"input_filename(): while True: filename = input(\"FILEPATH > \") if os.path.exists(filename): print(\"File already exists,",
"Interactive plot used to select images for export. save(filename) Dumps a JSON object",
"clone = generate_clone_tuples(clone_to, directs[0]) if clone_to else False print(\"→ Images are being processed.\")",
"Parameters ---------- dirpath : str Path to an image-containing directory. parse_tags : list",
"for construct_jpg_data(). \"\"\" return row[\"datetime\"] DEFAULT_PARSE = [ ((\"0th\", 306), \"datetime\", PARSE_DT) ]",
"== \".\": self.user_edits = {} def off_key(event): try: if event.xdata is not None",
"if jpg_data: self.jpg_data = list(jpg_data) self.length = len(self.jpg_data) self.dt_present = \"datetime\" in self.jpg_data[0].keys()",
"0.97) ax.grid(alpha=0.4) ax.set_axisbelow(True) ax.set_ylim([0, self.plt_vals[\"ceiling\"]]) ax.set_xlim([0, min(500, self.length)]) ax.set_xlabel(\"Frame\") ax.set_ylabel(\"Response\") plt.yticks(rotation=45) for name",
"jpg_data feedable to Cam(). Parameters ---------- dirpath : str Path to an image-containing",
"in (1, -1): is_neg = move < 0 prev = self.jpg_data[-is_neg] for i",
"else: f.write(\",\".join(variables) + \"\\n\") f.write(\",\".join(csv_safe(row[v]) for v in variables)) else: raise ValueError(\"No images",
"finds JPG image types, but can be changed if camera exports a different",
"jpg_data filepaths before being passed on to frame differencing methods that generate a",
"def mark_edits(self, i, kind): \"\"\"Marks which photos to label as edited based on",
"parse_tags=DEFAULT_PARSE, sort_key=SORT_BY_DT, process_options={} ): \"\"\"Performs all necessary steps to make jpg_data feedable to",
"jpg_data=False, resp_var=\"count\", thumb_dir=None): \"\"\" Parameters ---------- jpg_data : list of dictionaries, optional Typically",
"for n in array): array -= 1 else: break stack = [] for",
"cloning, and histogram equalization on images read from jpg_data filepaths before being passed",
"over given limit. def CONTOURS(curr, prev, threshold, ksize=11, min_area=100): \"\"\"Slower, but powerful frame",
"x2), just like slicing images as np.arrays. \"\"\" y1, y2, x1, x2 =",
"if boo: if not is_neg: lapse = curr[\"td_minutes\"] else: lapse = prev[\"td_minutes\"] curr[\"selected\"]",
"filename) output.append({ \"filename\": filename, \"filepath\": filepath }) return output def attach_exif(jpg_data, parse_tags=DEFAULT_PARSE): \"\"\"Loops",
"images for export. save(filename) Dumps a JSON object as a .sav file. update_counts()",
"self.lines[\"threshold\"] = ax.axhline( self.plt_vals[\"resp_thresh\"], color=\"#14B37D\") fig.canvas.draw_idle() def on_slide(val): for key in self.plt_vals.keys(): if",
"axe.set_xticklabels([]) axe.set_yticklabels([]) axe.set_xlim(lo_W, hi_W) axe.set_ylim(hi_H, lo_H) ax_crop.imshow(rgb) ax_clone.imshow(rgb) ax_mod.imshow(rgb) plt.connect(\"draw_event\", update) plt.show() return",
": list of tuples, optional By default, only Image DateTime is retrieved from",
"from EXIF tags. sort_key : function, optional By default, dictionaries within the jpg_data",
"try: row[\"timedelta\"] = td(seconds=row[\"timedelta\"]) except AttributeError: pass if \"selected\" in row.keys(): row[\"selected\"] =",
"if w > h: scale = size / w else: scale = size",
"img in stack) pano = np.hstack([img[:min_y, :] for img in stack]) h, w,",
"is an area of 100 pixels. Larger numbers decreases sensitivity. Returns ------- list",
"parameters for graphing, and plot function. class Cam(): \"\"\" A class used to",
"(response metric). Variable new_count is attached to jpg_data. Day to night transitions are",
"for name in (\"count\", \"threshold\", \"selected\", \"edited\"): self.lines[name] = ax.axhline() for name, pos,",
"values, re- assign DEFAULT_PLOT_PARAMS to this attribute. Methods ------- attach_diffs(var, new_var) Finds the",
"kmeans = KMeans(n_clusters=3).fit(X) night_indices = [np.argmin(kmeans.cluster_centers_), np.argmax(kmeans.cluster_centers_)] for n, index in enumerate(kmeans.labels_): self.jpg_data[n][\"is_night\"]",
"ax.fill_between( np.arange(0, self.length) + 0.5, -BIG_NUM, BIG_NUM, where=[r[\"trans_edit\"] or r[\"user_edit\"] for r in",
"and \"[L]eft\" are used for filling the area. Returns ------- pair of tuples",
"process_jpgs() function. min_area : int, unused Only used in the CONTOURS() function, but",
"h, 0, w) prev = preprocess(jpg, crop, clone) elif i % timer[0] ==",
"w else: scale = size / h new_w = rint(w * scale) new_h",
"% timer[0] and i: stop_watch(i, timer) from_path = jpg[\"filepath\"] to_path = os.path.join(export_dir, jpg[\"filename\"])",
"to preform image cropping, cloning, and histogram equalization on images read from jpg_data",
"!= self.pano_i: self.pano_i = i array = np.array(range(i - 2, i + 2))",
"time.minute / 60 + time.second / 3600 def extract_var(data, var): \"\"\"Returns a list",
"c:d] = image[e:f, g:h] image = CROPPER(image, crop) return cv2.equalizeHist(image) def crop_clone_preview(image): \"\"\"Interactive",
"deep_row in enumerate(jpg_data): row = deep_row.copy() if i == 0: jpg = cv2.imread(row[\"filepath\"],",
"update_events(self): \"\"\"Updates jpg_data with new events (runs of detection). An event is a",
"desired.\") crop, clone_to, directs = crop_clone_preview( cv2.imread(jpg_data[len(jpg_data) // 2][\"filepath\"])) clone = (generate_clone_tuples(clone_to, directs[0])",
"and a .csv file. load(filename) Loads a .sav file. mark_edits(i) Marks which photos",
"lapse <= self.plt_vals[\"smooth_time\"]) prev = curr else: nudge = int(self.plt_vals[\"smooth_time\"]) master_set = set()",
"which photos to label as edited based on [i]ndex. \"\"\" if i ==",
"events (runs of detection). An event is a contiguous sequence of images. First,",
"): \"\"\"Generates a response (movement) metric between images. Works hierarchically to preform image",
"if event.key == \"z\": self.press = [NEG_NUM, i] elif event.key == \"x\": self.press",
"for n in array: if n in self.buffer[0]: ind = self.buffer[0].index(n) img =",
"class for response filtering. Parameters ---------- jpg_data : list of dictionaries Requires that",
"to store, plot, filter, and export image data. Contains the heart of this",
"= to_24_hour(row[\"datetime\"]) row[\"td_minutes\"] = round( row[\"timedelta\"].total_seconds() / 60, 2) day_hr = extract_var(self.jpg_data, \"24hr\")",
"new_h = rint(h * scale) return cv2.resize(im, (new_w, new_h)) def generate_thumbnails(jpg_data, export_dir, long_edge=1024):",
"= min(W, max(geometry[1, :])) ignore = (min_y > H or max_y < 0",
"c - Hold to VIEW IMAGES in gallery. x - Hold and release",
"(progress / 100) remain = strfdelta(td(seconds=total - elapsed), \"{days}:{hours}:{minutes}:{seconds}\") print(f\"{progress}% done. {remain} left.\")",
"ind = self.buffer[0].index(n) img = self.buffer[1][ind] self.buffer[0].append(self.buffer[0].pop(ind)) self.buffer[1].append(self.buffer[1].pop(ind)) else: img = cv2.imread(self.jpg_data[n][\"thumbpath\"]) self.buffer[0]",
"data to initialize. # This way, someone can load() older, processed data. if",
"[x[var] for x in data] def stop_watch(i, timer): progress = (i * 10)",
"False if self.dt_present: self.attach_diffs(\"datetime\", \"timedelta\") for row in self.jpg_data: row[\"24hr\"] = to_24_hour(row[\"datetime\"]) row[\"td_minutes\"]",
"h, w = b - a, d - c h_or_w = np.array([h, h,",
"= [NEG_NUM, i] elif event.key == \"x\": self.press = [BIG_NUM, i] elif event.key",
"\") if os.path.isdir(directory): return directory else: print(\"Directory does not exist, would you like",
"): \"\"\"Performs all necessary steps to make jpg_data feedable to Cam(). Parameters ----------",
"timer[0] elapsed = time.time() - timer[1] total = elapsed / (progress / 100)",
"i % timer[0] and i: stop_watch(i, timer) from_path = jpg[\"filepath\"] to_path = os.path.join(export_dir,",
"return count # JPG PROCESSING def process_jpgs( jpg_data, method=CONTOURS, crop=False, clone=False, threshold=False, ksize=11,",
"= deep_row.copy() tags = piexif.load(row[\"filepath\"]) for (key, tag), var, anon in parse_tags: row[var]",
"and \"filename\" is in dictionary keys, which is easily provided by find_imgs() prior",
"i in master_set: self.jpg_data[i][\"selected\"] = True def plot(self): \"\"\"Interactive plot used to select",
"to this function. parse_tags : list of tuples, optional By default, only Image",
"os.path.join(dir_, filename) output.append({ \"filename\": filename, \"filepath\": filepath }) return output def attach_exif(jpg_data, parse_tags=DEFAULT_PARSE):",
"< 0 or d > W): trials.append((tups, direct)) choose = [] for (tups,",
"= cv2.absdiff(test, image) choose.append((sum(cv2.sumElems(diff)), direct, test)) choose.sort() if choose: _, directs, imgs =",
"jpg_data[0][\"shape\"] self.plt_vals[\"ceiling\"] = h * w * 0.02 self.plt_vals[\"resp_thresh\"] = self.plt_vals[\"ceiling\"] / 2",
"# Difference, blur (amount changes with ksize), mask and sum. def BLURRED(curr, prev,",
"\"\"\"Puts quotes around strings with commas in them. \"\"\" string = str(obj) return",
"is easily provided by find_imgs() prior to this function. parse_tags : list of",
"y1, y2, x1, x2 = crop return image[y1:y2, x1:x2] def CROP_EQUALIZE(image, crop, clone=None):",
"jpg_data.sort(key=lambda x: x[\"datetime\"]) print(\"→ Crop and clone out any timestamps from images.\") crop,",
"identified as being selected or not. Then, events are lumped based on time",
"100) remain = strfdelta(td(seconds=total - elapsed), \"{days}:{hours}:{minutes}:{seconds}\") print(f\"{progress}% done. {remain} left.\") def strfdelta(tdelta,",
"a new directory path.\") def csv_safe(obj): \"\"\"Puts quotes around strings with commas in",
"return output def hist_median(image): \"\"\"Quickly finds the median tone of a grayscale image.",
"jpgs without processing them first. thumb_dir : str, optional If the interactive plot",
"self.length) + 0.5, -BIG_NUM, 0, facecolor=\"white\", alpha=0.75, zorder=2) try: ax.fill_between( np.arange(0, self.length) +",
"images as np.arrays. \"\"\" y1, y2, x1, x2 = crop return image[y1:y2, x1:x2]",
"7}] >>> extract_var(data=foo, var=\"name\") [\"Shane\", \"Eve\"] \"\"\" return [x[var] for x in data]",
"Hold and release to INCREASE response value to Inf. z - Hold and",
"= mod self.sliders[slider_key].valtext.set_text(\"%.2e\" % mod) else: self.plt_vals[key] = self.sliders[slider_key].val update() # Displays last",
"resized) piexif.transplant(from_path, to_path) # SPECIFIC FUNCTIONS def find_imgs(dirpath, img_type=(\".jpg\", \".jpeg\")): \"\"\"Walks directory path,",
"clone parameter, or any other direction in the directs list (all have been",
"def to_24_hour(datetime): \"\"\"Converts datetime.datetime type to 24 hour float type. \"\"\" time =",
"slower than others. Parameters ---------- curr : numpy.ndarray Image array, typically from cv2.imread().",
"mem.clone_tuple, mem.clone_directs # FRAME DIFFERENCING METHODS # Bare-bones. Take difference, threshold, and sum",
"else: master_set.add(ind) except IndexError: pass for i in master_set: self.jpg_data[i][\"selected\"] = True def",
"\"Eve\"] \"\"\" return [x[var] for x in data] def stop_watch(i, timer): progress =",
"in jpg_data, typically the \"count\" variable is used as a response, but alternatives",
"== \"resp_thresh\": mod = self.sliders[slider_key].val ** RESP_NUM self.plt_vals[key] = mod self.sliders[slider_key].valtext.set_text(\"%.2e\" % mod)",
"0, 120, self.plt_vals[\"trans_thresh\"], \"%.1f\"), (\"SMOOTH\", 0.04, 0, 10, self.plt_vals[\"smooth_time\"], \"%.1f\"), (\"NIGHT\", 0.02, -1,",
"in lo_to_hi: self.user_edits.pop(i, None) self.press = [None, None] update() except TypeError: pass plt.rc(\"font\",",
"\"\"\" time = datetime.time() return time.hour + time.minute / 60 + time.second /",
"graphing, and plot function. class Cam(): \"\"\" A class used to store, plot,",
"self.lines.keys(): self.lines[name].remove() np_counts = np.array(extract_var(self.jpg_data, \"new_count\")) self.lines[\"edited\"] = ax.fill_between( np.arange(0, self.length) + 0.5,",
"\"0\") return fmt.format(**d) def resize_long_edge(im, size): h, w, *_ = im.shape if w",
"response metric. This is the last step before the jpg_data list can be",
"(H + H // scale) gs = gridspec.GridSpec(2, 2, height_ratios=[1, 1.25]) fig =",
"object. \"\"\" (a, b, c, d), (e, f, g, h) = clone image[a:b,",
"= (len(jpg_data) // 10, time.time()) for i, deep_row in enumerate(jpg_data): row = deep_row.copy()",
"can load() older, processed data. if jpg_data: self.jpg_data = list(jpg_data) self.length = len(self.jpg_data)",
"def stop_watch(i, timer): progress = (i * 10) // timer[0] elapsed = time.time()",
"clone): \"\"\"Returns a cropped image, with specified cloning and equalization. Parameters ---------- image",
"jpg_data, reading filepaths and attaching EXIF data. Useful for cloning out timestamps, aids",
"on_click(event): if event.dblclick and event.xdata is not None: image_pano(event.xdata) def on_key(event): if event.xdata",
"min(self.length, high+1)) if event.key in \"zx\": new_edits = {i: self.press[0] for i in",
"(tups, direct) in trials: test = image.copy() (a, b, c, d), (e, f,",
"photos to label as edited based on [i]ndex. \"\"\" if i == 0:",
"h, w = jpg_data[0][\"shape\"] self.plt_vals[\"ceiling\"] = h * w * 0.02 self.plt_vals[\"resp_thresh\"] =",
"RectangleSelector import matplotlib.gridspec as gridspec # CONSTANTS BIG_NUM = int(1e9) NEG_NUM = -0.1",
"height_ratios=[1, 1.25]) fig = plt.figure() fig.canvas.set_window_title(\"Crop and Clone Preview\") ax_crop = fig.add_subplot(gs[0, 0])",
"been edited. plot() Interactive plot used to select images for export. save(filename) Dumps",
"------- list of dictionaries Same as incoming jpg_data, but now with the median",
"= attach_exif(jpg_paths) jpg_data.sort(key=lambda x: x[\"datetime\"]) print(\"→ Crop and clone out any timestamps from",
"import Slider, RectangleSelector import matplotlib.gridspec as gridspec # CONSTANTS BIG_NUM = int(1e9) NEG_NUM",
"\"\"\"Returns a cropped image. Parameters ---------- image : numpy.ndarray Image array, typically from",
"= cv2.medianBlur(difference, ksize) _, mask = cv2.threshold( blurred, threshold, 255, cv2.THRESH_BINARY) contours, _",
"attach_diffs(var, new_var) Finds the difference between the current and previous items. export(directory) Exports",
"min(img.shape[0] for img in stack) pano = np.hstack([img[:min_y, :] for img in stack])",
"clone_RS.update() def safe_corners(geometry): min_y = max(0, min(geometry[0, :])) max_y = min(H, max(geometry[0, :]))",
"on your jpg_data list, and specify the export directory here. These smaller images",
"pixels from \"[A]bove,\" \"[B]elow,\" \"[R]ight,\" and \"[L]eft\" are used for filling the area.",
"cr_ig = safe_corners(crop_RS.geometry) cl_corn, cl_ig = safe_corners(clone_RS.geometry) mod = image.copy() if not cl_ig:",
"pixels. If the contours are above the min_area parameter, they are counted as",
"(movement) metric between images. Works hierarchically to preform image cropping, cloning, and histogram",
"self.jpg_data = list(jpg_data) self.length = len(self.jpg_data) self.dt_present = \"datetime\" in self.jpg_data[0].keys() h, w",
"temp_dict.items()} def export(self, directory): \"\"\"Exports selected images and a .csv file to specified",
"new_path write_row[\"old_name\"] = row[\"filename\"] write_row[\"old_path\"] = row[\"filepath\"] shutil.copy2(row[\"filepath\"], new_path) write_data.append(write_row) if write_data: with",
"in (\"A\", \"B\", \"R\", \"L\"): tups = generate_clone_tuples(cl_corn, direct) a, b, c, d",
"= [{\"name\": \"Shane\", \"age\": 22}, {\"name\": \"Eve\", \"age\": 7}] >>> extract_var(data=foo, var=\"name\") [\"Shane\",",
"for f in files if f.lower().endswith(img_type) ) for filename in found: filepath =",
"RS_event, **RS_PARAMS) ax_crop.set_title(\"Crop\") ax_clone.set_title(\"Clone\") ax_mod.set_title(\"Result\") for axe in (ax_crop, ax_clone): axe.set_xticklabels([]) axe.set_yticklabels([]) axe.set_xlim(lo_W,",
"numpy.ndarray Image array, typically from cv2.imread(). One of the two images for the",
"directs, imgs = list(zip(*choose)) mem.clone_directs = directs mod = imgs[0] del choose else:",
"are multiplied based on slider. Manual user edits are applied. \"\"\" for i,",
"stop_watch(i, timer): progress = (i * 10) // timer[0] elapsed = time.time() -",
"+ [img] if self.toggle: gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img = cv2.cv2.equalizeHist(gray) stack.append(img) min_y",
"safe_corners(geometry): min_y = max(0, min(geometry[0, :])) max_y = min(H, max(geometry[0, :])) min_x =",
"x2, y2 = erelease.xdata, erelease.ydata cr_corn, cr_ig = safe_corners(crop_RS.geometry) cl_corn, cl_ig = safe_corners(clone_RS.geometry)",
"list, and specify the export directory here. These smaller images will be displayed",
"import operator import os import shutil import string import sys import time import",
"event.key in \"zx\": new_edits = {i: self.press[0] for i in lo_to_hi} self.user_edits =",
"-1, 50, self.plt_vals[\"night_mult\"], \"%.1f\") ] def update(): self.update_counts() self.update_events() draw() def draw(): for",
"b, c, d), (e, f, g, h) = clone image[a:b, c:d] = image[e:f,",
"function. \"\"\" difference = cv2.absdiff(curr, prev) blurred = cv2.medianBlur(difference, ksize) _, mask =",
"as a response (movement). Works very well, little noise; slower than others. Parameters",
"\"is_night\"), facecolor=\"#003459\", alpha=0.5) except KeyError: pass on_slide(1) plt.show() cv2.destroyAllWindows() if __name__ == \"__main__\":",
"prev = preprocess(jpg, crop, clone) elif i % timer[0] == 0: stop_watch(i, timer)",
"* 64, [None] * 64] self.recent_folder = os.path.expanduser(\"~\") # Cam objects don\"t need",
"np_counts = np.array(extract_var(self.jpg_data, \"new_count\")) self.lines[\"edited\"] = ax.fill_between( np.arange(0, self.length) + 0.5, -BIG_NUM, BIG_NUM,",
"thresholding, contours are drawn around the resulting white pixels. If the contours are",
"will be displayed in the Gallery tab. \"\"\" self.resp_var = resp_var self.plt_vals =",
"self.jpg_data: if thumb_dir is not None: row[\"thumbpath\"] = os.path.join(thumb_dir, row[\"filename\"]) else: row[\"thumbpath\"] =",
"equalization on images read from jpg_data filepaths before being passed on to frame",
"row in enumerate(self.jpg_data): write_row = row.copy() if row[\"selected\"]: if self.dt_present: dt_ISO = dt.strftime(",
"so as not to lose any prior work. Attributes ---------- jpg_data : list",
"i, kind): \"\"\"Marks which photos to label as edited based on [i]ndex. \"\"\"",
"if \",\" in string else string def to_24_hour(datetime): \"\"\"Converts datetime.datetime type to 24",
"After filtering images with the plot, save() and export() should be called so",
"size / w else: scale = size / h new_w = rint(w *",
"is not None and event.key in \"zx,\": i = int(round(event.xdata)) low, high =",
"image.shape[1] hist = cv2.calcHist([image], [0], None, [256], [0, 256]) tally = 0 threshold",
"self.press = [None, None] self.toggle = False self.buffer = [[None] * 64, [None]",
"a .csv file. load(filename) Loads a .sav file. mark_edits(i) Marks which photos have",
"1]) ax_mod = fig.add_subplot(gs[1, :]) crop_RS = RectangleSelector( ax_crop, RS_event, **RS_PARAMS) clone_RS =",
"the process_jpgs() function. \"\"\" difference = cv2.absdiff(curr, prev) blurred = cv2.medianBlur(difference, ksize) _,",
"[1, 3], \"minspanx\": 5, \"minspany\": 5, \"spancoords\": \"pixels\", \"interactive\": True } # GENERAL",
"images are of same size, \" \"consider using the crop parameter.\\n\" f\"Try crop={tup}.\")",
"DEFAULT_PLOT_PARAMS self.lines = {} self.sliders = {} self.user_edits = {} self.press = [None,",
"To reset these values, re- assign DEFAULT_PLOT_PARAMS to this attribute. Methods ------- attach_diffs(var,",
"directory print(\"Please input a new directory path.\") def csv_safe(obj): \"\"\"Puts quotes around strings",
"clone_directs). The crop_tuple variable can be fed directly into process_jpgs(). Then, use \"generate_clone_tuples(clone_to,",
"== \"x\": self.press = [BIG_NUM, i] elif event.key == \",\": self.press = [0,",
"h new_w = rint(w * scale) new_h = rint(h * scale) return cv2.resize(im,",
"= True else: self.jpg_data[i][kind] = True self.jpg_data[i-1][kind] = True def update_counts(self): \"\"\"Updates jpg_data",
"hour float type. \"\"\" time = datetime.time() return time.hour + time.minute / 60",
"draw(): for name in self.lines.keys(): self.lines[name].remove() np_counts = np.array(extract_var(self.jpg_data, \"new_count\")) self.lines[\"edited\"] = ax.fill_between(",
"is easily provided by find_imgs() prior to this function. method : function, {SIMPLE,",
"Cam(construct_jpg_data()). After filtering images with the plot, save() and export() should be called",
"thresholding, the resulting white pixels are counted toward response (movement). Works decently, a",
"have data to initialize. # This way, someone can load() older, processed data.",
"\".\": self.user_edits = {} def off_key(event): try: if event.xdata is not None and",
"exporting thumbnails. long_edge : int, optional By default, images will be resized to",
"and its previous, after preprocessing / thresholding. \"\"\" if not threshold: thresh_init =",
"image_pano(xdata): i = int(round(xdata)) if i != self.pano_i: self.pano_i = i array =",
"d > W): trials.append((tups, direct)) choose = [] for (tups, direct) in trials:",
"directs[0])\" to get the clone parameter, or any other direction in the directs",
"for sequence. process_options : dictionary, optional Passes along paramters to the process_jpgs() function.",
"ax_clone, RS_event, **RS_PARAMS) ax_crop.set_title(\"Crop\") ax_clone.set_title(\"Clone\") ax_mod.set_title(\"Result\") for axe in (ax_crop, ax_clone): axe.set_xticklabels([]) axe.set_yticklabels([])",
"except IndexError: pass for i in master_set: self.jpg_data[i][\"selected\"] = True def plot(self): \"\"\"Interactive",
"= curr def mark_edits(self, i, kind): \"\"\"Marks which photos to label as edited",
"+ 0.5, -BIG_NUM, BIG_NUM, where=[r[\"trans_edit\"] or r[\"user_edit\"] for r in self.jpg_data], facecolor=\"#D8BFAA\", alpha=0.5)",
"Parameters ---------- jpg_data : list of dictionaries, optional Typically requires the output of",
"to this function. export_dir : str Directory path that is used for exporting",
"is mappable. Returns ------- list of dictionaries Each row contains everything that is",
"zeros. \"\"\" d = {\"days\": tdelta.days} d[\"hours\"], rem = divmod(tdelta.seconds, 3600) d[\"minutes\"], d[\"seconds\"]",
"x1, x2), just like slicing images as np.arrays. clone : pair of tuples",
"fed directly into process_jpgs(). Then, use \"generate_clone_tuples(clone_to, directs[0])\" to get the clone parameter,",
"in self.jpg_data] for row in temp_data: if \"datetime\" in row.keys(): row[\"datetime\"] = dt.strftime(",
"ax_clone = fig.add_subplot(gs[0, 1]) ax_mod = fig.add_subplot(gs[1, :]) crop_RS = RectangleSelector( ax_crop, RS_event,",
"= np.array(day_hr).reshape(-1, 1) kmeans = KMeans(n_clusters=3).fit(X) night_indices = [np.argmin(kmeans.cluster_centers_), np.argmax(kmeans.cluster_centers_)] for n, index",
"method(curr, prev, threshold, ksize, min_area) except cv2.error as inst: if \"(-209:Sizes\" in str(inst):",
"306), \"datetime\", PARSE_DT) ] DEFAULT_PLOT_PARAMS = { \"ceiling\": 40000, \"resp_thresh\": 20000, \"trans_thresh\": 30,",
">>> foo = [{\"name\": \"Shane\", \"age\": 22}, {\"name\": \"Eve\", \"age\": 7}] >>> extract_var(data=foo,",
"and a count variable, which respresents how many pixels have changed between a",
": str, optional A key found in jpg_data, typically the \"count\" variable is",
"json import operator import os import shutil import string import sys import time",
"images as np.arrays. clone : pair of tuples Matches the format ((clone_to), (clone_from)).",
"export() should be called so as not to lose any prior work. Attributes",
"%H:%M:%S\") if \"timedelta\" in row.keys(): row[\"timedelta\"] = row[\"timedelta\"].total_seconds() if \"selected\" in row.keys(): row[\"selected\"]",
"def on_slide(val): for key in self.plt_vals.keys(): if key != \"ceiling\": slider_key = key[:key.find(\"_\")].upper()",
"= self.buffer[1][1:] + [img] if self.toggle: gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img = cv2.cv2.equalizeHist(gray)",
"jpg_data.sort(key=sort_key) if process_options == {}: print(\"Crop and clone image as desired.\") crop, clone_to,",
"y2, x1, x2), just like slicing images as np.arrays. fill_from : {\"A\", \"B\",",
"plt.figure() ax = fig.add_subplot(111) fig.canvas.set_window_title(\"Response Filtering\") fig.subplots_adjust(0.07, 0.18, 0.97, 0.97) ax.grid(alpha=0.4) ax.set_axisbelow(True) ax.set_ylim([0,",
"processed.\") processed_data = process_jpgs(jpg_data, crop=crop, clone=clone) if type(processed_data) is not tuple: cam =",
"quickly get crop and clone parameters. Parameters ---------- image : numpy.ndarray Image array,",
"max_x = min(W, max(geometry[1, :])) ignore = (min_y > H or max_y <",
": str Path to an image-containing directory. parse_tags : list of tuples, optional",
"= cv2.findContours( mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2:] count = 0 for cnt in contours: area",
"in string else string def to_24_hour(datetime): \"\"\"Converts datetime.datetime type to 24 hour float",
"import sys import time import cv2 import piexif import numpy as np from",
"a .sav file. mark_edits(i) Marks which photos have been edited. plot() Interactive plot",
"jpg in enumerate(jpg_data): if not i % timer[0] and i: stop_watch(i, timer) from_path",
"of dictionaries Each row contains everything that is needed to feed a Cam()",
"DEFAULT_PARSE = [ ((\"0th\", 306), \"datetime\", PARSE_DT) ] DEFAULT_PLOT_PARAMS = { \"ceiling\": 40000,",
"} # GENERAL FUNCTIONS class Mem(): def __init__(self): pass def rint(n): return round(int(n))",
"counted toward response (movement). Works decently, a little faster than COUNTOURS. Parameters ----------",
"resulting white pixels are counted toward response (movement). Very noisy, but fast. Parameters",
"array, typically from cv2.imread(). crop : tuple Format is (y1, y2, x1, x2),",
"H, 0, W) mem.crop_tuple = False else: mem.crop_tuple = cr_corn y1, y2, x1,",
"jpg = cv2.imread(row[\"filepath\"], 0) curr = preprocess(jpg, crop, clone) row[\"shape\"] = jpg.shape row[\"median\"]",
"> self.plt_vals[\"resp_thresh\"]) prev = curr if self.dt_present: for move in (1, -1): is_neg",
"row in enumerate(self.jpg_data): if row[\"selected\"]: for func in (operator.add, operator.sub): for j in",
"image (for dark images). \"\"\" try: self.jpg_data except AttributeError as inst: raise inst",
"if more data is desired from EXIF tags. Returns ------- list of dictionaries",
"# JPG PROCESSING def process_jpgs( jpg_data, method=CONTOURS, crop=False, clone=False, threshold=False, ksize=11, min_area=100 ):",
"self.pano_i: self.pano_i = i array = np.array(range(i - 2, i + 2)) while",
"list are sorted by their \"Image DateTime\" EXIF tag. This can be changed",
"as plt from matplotlib.widgets import Slider, RectangleSelector import matplotlib.gridspec as gridspec # CONSTANTS",
"Same as incoming jpg_data, but now with the median image tone and a",
"Mem() mem.crop_tuple = False mem.clone_tuple = False mem.clone_directs = False def update(event): if",
"20000, \"trans_thresh\": 30, \"smooth_time\": 1, \"night_mult\": 0 } DIRECTION_MULTS = { \"A\": (-1,",
"resulting white pixels are counted toward response (movement). Works decently, a little faster",
"# Requires data from process_jpg(). Object essentially holds data # used in exporting,",
"threshold is called, the resulting white pixels are counted toward response (movement). Very",
"= self.jpg_data[-is_neg] for i in range(-is_neg, (self.length * move) - is_neg, move): curr",
"= plt.figure() ax = fig.add_subplot(111) fig.canvas.set_window_title(\"Response Filtering\") fig.subplots_adjust(0.07, 0.18, 0.97, 0.97) ax.grid(alpha=0.4) ax.set_axisbelow(True)",
"a response metric. This is the last step before the jpg_data list can",
"(runs of detection). An event is a contiguous sequence of images. First, images",
"just like slicing images as np.arrays. \"\"\" y1, y2, x1, x2 = crop",
"self.buffer[1] = self.buffer[1][1:] + [img] if self.toggle: gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img =",
"cloning out timestamps, aids in histogram equalization. Parameters ---------- clone_to : tuple Format",
"import cv2 import piexif import numpy as np from sklearn.cluster import KMeans from",
"metric). Variable new_count is attached to jpg_data. Day to night transitions are filtered",
"Parameters ---------- tdelta : datetime.timedelta Timedelta object to format. fmt : str Contains",
"self.press = [BIG_NUM, i] elif event.key == \",\": self.press = [0, i] if",
"= max(0, min(geometry[1, :])) max_x = min(W, max(geometry[1, :])) ignore = (min_y >",
"input(\"Y / N > \") if answer.lower() in (\"y\", \"yes\"): os.makedirs(directory) return directory",
"etc. plot_params : dictionary Parameters used in the plot() method. To reset these",
"is used as a response, but alternatives like \"median\" can be used to",
"\") if os.path.exists(filename): print(\"File already exists, would you like to overwrite it?\") answer",
"directly into process_jpgs(). Then, use \"generate_clone_tuples(clone_to, directs[0])\" to get the clone parameter, or",
"thresh_init: threshold = row[\"median\"]*1.05 try: row[\"count\"] = method(curr, prev, threshold, ksize, min_area) except",
"By default, no options are specified. Make sure that this parameter is mappable.",
"0.04, 0, 10, self.plt_vals[\"smooth_time\"], \"%.1f\"), (\"NIGHT\", 0.02, -1, 50, self.plt_vals[\"night_mult\"], \"%.1f\") ] def",
"progress = (i * 10) // timer[0] elapsed = time.time() - timer[1] total",
"clone_to, directs = crop_clone_preview( cv2.imread(jpg_data[len(jpg_data) // 2][\"filepath\"])) clone = generate_clone_tuples(clone_to, directs[0]) if clone_to",
"z - Hold and release to DECREASE response value to 0. , -",
"f: f.write(json.dumps(self.plt_vals) + \"\\n\") f.write(json.dumps(temp_data) + \"\\n\") f.write(json.dumps(self.user_edits)) def load(self, filename): \"\"\"Loads a",
"By default, finds JPG image types, but can be changed if camera exports",
"is 11. Must be positive, odd number. min_area : int, unused Only used",
"= curr - prev prev = curr def mark_edits(self, i, kind): \"\"\"Marks which",
"[i]ndex. \"\"\" if i == 0: self.jpg_data[i][kind] = True else: self.jpg_data[i][kind] = True",
"10 lo_W, hi_W = (0 - W // scale), (W + W //",
"f: self.plt_vals = json.loads(next(f)) self.plt_vals[\"resp_thresh\"] = ( self.plt_vals[\"resp_thresh\"] ** (1 / RESP_NUM)) temp_data",
"reduce noise. After thresholding, the resulting white pixels are counted toward response (movement).",
"False print(\"→ Images are being processed.\") processed_data = process_jpgs(jpg_data, crop=crop, clone=clone) if type(processed_data)",
"mod) else: self.plt_vals[key] = self.sliders[slider_key].val update() # Displays last two and next two",
"event.key == \"z\": self.press = [NEG_NUM, i] elif event.key == \"x\": self.press =",
"(0, h, 0, w) print(\"FUNCTION ABORTED!\\n\" \"Not all images are of same size,",
": pair of tuples Matches the format ((clone_to), (clone_from)). For simplicity, use generate_clone_tuples()",
"dictionaries Similar to what is inputted, but includes variables denoting selection, edits, event,",
"in them. \"\"\" string = str(obj) return '\"' + string + '\"' if",
"None: if self.press[0] is None: i = int(round(event.xdata)) if event.key == \"z\": self.press",
"image[e:f, g:h] image = CROPPER(image, crop) return cv2.equalizeHist(image) def crop_clone_preview(image): \"\"\"Interactive viewer to",
"= self.sliders[slider_key].val update() # Displays last two and next two images from response",
"the cv2.threshold() function. ksize : int Parameter to be passed to the cv2.medianBlur()",
"[ ((\"0th\", 306), \"datetime\", PARSE_DT) ] DEFAULT_PLOT_PARAMS = { \"ceiling\": 40000, \"resp_thresh\": 20000,",
"blurred, threshold, 255, cv2.THRESH_BINARY) return cv2.countNonZero(mask) # Like BLURRED, but only sums drawn",
"around the resulting white pixels. If the contours are above the min_area parameter,",
"output.append(row) return output def construct_jpg_data( dirpath, parse_tags=DEFAULT_PARSE, sort_key=SORT_BY_DT, process_options={} ): \"\"\"Performs all necessary",
"5, \"spancoords\": \"pixels\", \"interactive\": True } # GENERAL FUNCTIONS class Mem(): def __init__(self):",
"= piexif.load(row[\"filepath\"]) for (key, tag), var, anon in parse_tags: row[var] = anon(tags[key][tag]) output.append(row)",
"numpy as np from sklearn.cluster import KMeans from datetime import datetime as dt,",
"quotes around strings with commas in them. \"\"\" string = str(obj) return '\"'",
"being selected or not. Then, events are lumped based on time since last",
"for an initial save.\") cam.save(input_filename()) print(\"→ Use the interactive plot to select images",
"A class used to store, plot, filter, and export image data. Contains the",
"curr - prev prev = curr def mark_edits(self, i, kind): \"\"\"Marks which photos",
"so changes are recorded.\") cam.save(input_filename()) print(\"→ Finally, choose a location for export.\") cam.export(input_directory())",
"the BLURRED() and CONTOURS() functions, but retained here to shorten the process_jpgs() function.",
"holds data # used in exporting, parameters for graphing, and plot function. class",
"print(\"→ Use the interactive plot to select images for export.\") help(Cam.plot) cam.plot() print(\"→",
"axe.set_ylim(hi_H, lo_H) ax_crop.imshow(rgb) ax_clone.imshow(rgb) ax_mod.imshow(rgb) plt.connect(\"draw_event\", update) plt.show() return mem.crop_tuple, mem.clone_tuple, mem.clone_directs #",
"list(zip(*choose)) mem.clone_directs = directs mod = imgs[0] del choose else: mem.clone_tuple = False",
"\"Image DateTime\" tag. \"\"\" str_ = ''.join(x for x in str(raw) if x",
"/ 3600 def extract_var(data, var): \"\"\"Returns a list of values corresponding to a",
"= ( f for f in files if f.lower().endswith(img_type) ) for filename in",
"COUNTOURS} Determines the frame differencing method to use. Ordered from left to right",
"i = int(round(event.xdata)) if event.key == \"z\": self.press = [NEG_NUM, i] elif event.key",
"return [x[var] for x in data] def stop_watch(i, timer): progress = (i *",
"the process_jpgs() function. By default, no options are specified. Make sure that this",
"can be changed if camera exports a different filetype. Returns ------- list of",
"of the image. Smaller sizes speed up performance, but decrease acuity. \"\"\" if",
"if not clone: preprocess = CROP_EQUALIZE else: preprocess = CROP_CLONE_EQUALIZE output = []",
"[n] self.buffer[1] = self.buffer[1][1:] + [img] if self.toggle: gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img",
"threshold, 255, cv2.THRESH_BINARY) contours, _ = cv2.findContours( mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2:] count = 0",
"histogram equalization on images read from jpg_data filepaths before being passed on to",
"difference between the current and previous items. export(directory) Exports selected images and a",
"in row.keys(): row[\"selected\"] = bool(row[\"selected\"]) self.jpg_data = temp_data.copy() self.length = len(self.jpg_data) self.user_edits =",
"* row[\"is_night\"]) row[\"new_count\"] = new_count for i, shift in self.user_edits.items(): self.jpg_data[i][\"new_count\"] = shift",
"used to select images for export. QUICK GUIDE: c - Hold to VIEW",
"increasing accuracy, decreasing speed. crop : tuple Format is (y1, y2, x1, x2),",
"and clone image as desired.\") crop, clone_to, directs = crop_clone_preview( cv2.imread(jpg_data[len(jpg_data) // 2][\"filepath\"]))",
"overwrite it?\") answer = input(\"Y / N > \") if answer.lower() in (\"y\",",
"changed if camera exports a different filetype. Returns ------- list of dictionaries Contains",
"parameter, or any other direction in the directs list (all have been checked",
"parameter, they are counted as a response (movement). Works very well, little noise;",
"Works very well, little noise; slower than others. Parameters ---------- curr : numpy.ndarray",
"inst: if \"(-209:Sizes\" in str(inst): (a, b), (c, d) = curr.shape[:2], prev.shape[:2] h,",
"not (a < 0 or b > H or c < 0 or",
"parameter is mappable. Returns ------- list of dictionaries Each row contains everything that",
"a variable name. >>> foo = [{\"name\": \"Shane\", \"age\": 22}, {\"name\": \"Eve\", \"age\":",
"= min(a, c), min(b, d) tup = (0, h, 0, w) print(\"FUNCTION ABORTED!\\n\"",
"work. Attributes ---------- jpg_data : list of dictionaries Similar to what is inputted,",
"to count as a response (movement). Default is an area of 100 pixels.",
"variable, which respresents how many pixels have changed between a photo and its",
"cv2.THRESH_BINARY) contours, _ = cv2.findContours( mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2:] count = 0 for cnt",
"if area > min_area: count += area return count # JPG PROCESSING def",
"= True else: self.dt_present = False if \"timedelta\" in row.keys(): try: row[\"timedelta\"] =",
"of tuples Matches the format for the clone parameter in process_jpgs(). \"\"\" clone_to",
"Calls directional tuples from DIRECTION_MULTS to fill pixels within the clone_to area. Neighboring",
"you like to make it?\") answer = input(\"Y / N > \") if",
"optional By default, dictionaries within the jpg_data list are sorted by their \"Image",
"by their \"Image DateTime\" EXIF tag. This can be changed if images don\"t",
"thumbnails. long_edge : int, optional By default, images will be resized to 1024",
"clone = (generate_clone_tuples(clone_to, directs[0]) if clone_to else False) process_options = {\"crop\": crop, \"clone\":",
"def RS_event(eclick, erelease): x1, y1 = eclick.xdata, eclick.ydata x2, y2 = erelease.xdata, erelease.ydata",
"= dt.strftime( row[\"datetime\"], \"%Y-%m-%d %H:%M:%S\") if \"timedelta\" in row.keys(): row[\"timedelta\"] = row[\"timedelta\"].total_seconds() if",
"= preprocess(jpg, crop, clone) elif i % timer[0] == 0: stop_watch(i, timer) jpg",
"str(inst): (a, b), (c, d) = curr.shape[:2], prev.shape[:2] h, w = min(a, c),",
"self.user_edits.items(): self.jpg_data[i][\"new_count\"] = shift self.mark_edits(i, \"user_edit\") def update_events(self): \"\"\"Updates jpg_data with new events",
"optional Passes along paramters to the process_jpgs() function. By default, no options are",
"range(-is_neg, (self.length * move) - is_neg, move): curr = self.jpg_data[i] boo = (not",
"a cropped image. Parameters ---------- image : numpy.ndarray Image array, typically from cv2.imread().",
"tuples from DIRECTION_MULTS to fill pixels within the clone_to area. Neighboring pixels from",
"\"\"\" d = {\"days\": tdelta.days} d[\"hours\"], rem = divmod(tdelta.seconds, 3600) d[\"minutes\"], d[\"seconds\"] =",
"self.dt_present = False if \"timedelta\" in row.keys(): try: row[\"timedelta\"] = td(seconds=row[\"timedelta\"]) except AttributeError:",
"in row.keys(): try: row[\"timedelta\"] = td(seconds=row[\"timedelta\"]) except AttributeError: pass if \"selected\" in row.keys():",
"attach_diffs(self, var, new_var): \"\"\"Finds the difference between the current and previous variable. Requires",
"night transitions are filtered out based on slider. Counts taken at with nighttime",
"b - a, d - c h_or_w = np.array([h, h, w, w]) clone_from",
"generate this object. \"\"\" (a, b, c, d), (e, f, g, h) =",
"or c < 0 or d > W): trials.append((tups, direct)) choose = []",
"W // scale), (W + W // scale) lo_H, hi_H = (0 -",
"\"_selected\" not in dir_: found = ( f for f in files if",
"= list(jpg_data) self.length = len(self.jpg_data) self.dt_present = \"datetime\" in self.jpg_data[0].keys() h, w =",
"self.sliders[slider_key].valtext.set_text(\"%.2e\" % mod) else: self.plt_vals[key] = self.sliders[slider_key].val update() # Displays last two and",
"release to INCREASE response value to Inf. z - Hold and release to",
"def __init__(self, jpg_data=False, resp_var=\"count\", thumb_dir=None): \"\"\" Parameters ---------- jpg_data : list of dictionaries,",
"= gridspec.GridSpec(2, 2, height_ratios=[1, 1.25]) fig = plt.figure() fig.canvas.set_window_title(\"Crop and Clone Preview\") ax_crop",
"row[\"trans_edit\"] = False new_count = row[\"count\"] if row[\"med_diff\"] > self.plt_vals[\"trans_thresh\"]: new_count = 0",
"clone : pair of tuples Matches the format ((clone_to), (clone_from)). For simplicity, use",
"for i, row in enumerate(self.jpg_data): write_row = row.copy() if row[\"selected\"]: if self.dt_present: dt_ISO",
"Press for EQUALIZED image (for dark images). \"\"\" try: self.jpg_data except AttributeError as",
"crop, clone_to, directs = crop_clone_preview( cv2.imread(jpg_data[len(jpg_data) // 2][\"filepath\"])) clone = generate_clone_tuples(clone_to, directs[0]) if",
": str Directory path that is used for exporting thumbnails. long_edge : int,",
"if event.xdata is not None: if self.press[0] is None: i = int(round(event.xdata)) if",
"image with an equalized histogram. Parameters ---------- image : numpy.ndarray Image array, typically",
"max_x < 0) return tuple(map( lambda x: int(round(x)), (min_y, max_y, min_x, max_x))), ignore",
"to select images for export.\") help(Cam.plot) cam.plot() print(\"→ Save once again, so changes",
"clone image as desired.\") crop, clone_to, directs = crop_clone_preview( cv2.imread(jpg_data[len(jpg_data) // 2][\"filepath\"])) clone",
"images.\") crop, clone_to, directs = crop_clone_preview( cv2.imread(jpg_data[len(jpg_data) // 2][\"filepath\"])) clone = generate_clone_tuples(clone_to, directs[0])",
"reading filepaths and attaching EXIF data. Useful for cloning out timestamps, aids in",
"passed to the cv2.threshold() function. ksize : int, unused Used in the BLURRED()",
"are lumped based on time since last image (SMOOTH slider value). \"\"\" self.pano_i",
"color=\"#14B37D\") fig.canvas.draw_idle() def on_slide(val): for key in self.plt_vals.keys(): if key != \"ceiling\": slider_key",
"ignore = (min_y > H or max_y < 0 or min_x > W",
"an initial save.\") cam.save(input_filename()) print(\"→ Use the interactive plot to select images for",
"but alternatives like \"median\" can be used to plot jpgs without processing them",
"((clone_to), (clone_from)). For simplicity, use generate_clone_tuples() to generate this object. \"\"\" image =",
"False if cr_ig: cr_corn = (0, H, 0, W) mem.crop_tuple = False else:",
"mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2:] count = 0 for cnt in contours: area = cv2.contourArea(cnt)",
"60 + time.second / 3600 def extract_var(data, var): \"\"\"Returns a list of values",
"in contours: area = cv2.contourArea(cnt) if area > min_area: count += area return",
"== operator.sub: master_set.add(ind) break else: master_set.add(ind) except IndexError: pass for i in master_set:",
"imgs = list(zip(*choose)) mem.clone_directs = directs mod = imgs[0] del choose else: mem.clone_tuple",
"be used to plot jpgs without processing them first. thumb_dir : str, optional",
"return cv2.countNonZero(mask) # Like BLURRED, but only sums drawn contours over given limit.",
"zorder=2) try: ax.fill_between( np.arange(0, self.length) + 0.5, -BIG_NUM, BIG_NUM, where=extract_var(self.jpg_data, \"is_night\"), facecolor=\"#003459\", alpha=0.5)",
"\",\" in string else string def to_24_hour(datetime): \"\"\"Converts datetime.datetime type to 24 hour",
"easily provided by find_imgs() prior to this function. parse_tags : list of tuples,",
"w, *_ = pano.shape cv2.namedWindow(\"Gallery\", cv2.WINDOW_NORMAL) cv2.imshow(\"Gallery\", cv2.resize(pano, (w // 2, h //",
": list of dictionaries Requires that \"filepath\" is in dictionary keys, which is",
"max(0, min(geometry[0, :])) max_y = min(H, max(geometry[0, :])) min_x = max(0, min(geometry[1, :]))",
"sum. def BLURRED(curr, prev, threshold, ksize=11, min_area=None): \"\"\"Useful, mid-grade frame differencing method. Takes",
"Prior to thresholding, the differenced image is blurred to reduce noise. After thresholding,",
"event, etc. plot_params : dictionary Parameters used in the plot() method. To reset",
"H // scale) gs = gridspec.GridSpec(2, 2, height_ratios=[1, 1.25]) fig = plt.figure() fig.canvas.set_window_title(\"Crop",
"EXIF data attached. \"\"\" output = [] for deep_row in jpg_data: row =",
"for k, v in temp_dict.items()} def export(self, directory): \"\"\"Exports selected images and a",
"format ((clone_to), (clone_from)). For simplicity, use generate_clone_tuples() to generate this object. \"\"\" image",
">>> extract_var(data=foo, var=\"name\") [\"Shane\", \"Eve\"] \"\"\" return [x[var] for x in data] def",
"than COUNTOURS. Parameters ---------- curr : numpy.ndarray Image array, typically from cv2.imread(). One",
"n in array: if n in self.buffer[0]: ind = self.buffer[0].index(n) img = self.buffer[1][ind]",
"enumerate(self.jpg_data): prev[\"selected\"] = ( prev[\"new_count\"] > self.plt_vals[\"resp_thresh\"] or curr[\"new_count\"] > self.plt_vals[\"resp_thresh\"]) if i",
"prior to this function. parse_tags : list of tuples, optional By default, only",
"Each row contains everything that is needed to feed a Cam() object with",
"cv2.calcHist([image], [0], None, [256], [0, 256]) tally = 0 threshold = px_count /",
"eclick.xdata, eclick.ydata x2, y2 = erelease.xdata, erelease.ydata cr_corn, cr_ig = safe_corners(crop_RS.geometry) cl_corn, cl_ig",
"d = {\"days\": tdelta.days} d[\"hours\"], rem = divmod(tdelta.seconds, 3600) d[\"minutes\"], d[\"seconds\"] = divmod(rem,",
"/ N > \") if answer.lower() in (\"y\", \"yes\"): os.makedirs(directory) return directory print(\"Please",
"resp_var self.plt_vals = DEFAULT_PLOT_PARAMS self.lines = {} self.sliders = {} self.user_edits = {}",
"np.array(DIRECTION_MULTS[fill_from[0].upper()]) a, b, c, d = clone_to h, w = b - a,",
"10, time.time()) for i, deep_row in enumerate(jpg_data): row = deep_row.copy() if i ==",
"False if \"timedelta\" in row.keys(): try: row[\"timedelta\"] = td(seconds=row[\"timedelta\"]) except AttributeError: pass if",
"os.path.join(thumb_dir, row[\"filename\"]) else: row[\"thumbpath\"] = row[\"filepath\"] row[\"count\"] = row[self.resp_var] row[\"med_diff\"] = abs(row[\"med_diff\"]) row[\"selected\"]",
"you like to overwrite it?\") answer = input(\"Y / N > \") if",
"= row[\"filepath\"] shutil.copy2(row[\"filepath\"], new_path) write_data.append(write_row) if write_data: with open(os.path.join(directory, \"_export.csv\"), \"w\") as f:",
"------- str Right justified 2 spaces, filled with zeros. \"\"\" d = {\"days\":",
"pass to attach_exif(), if more data is desired from EXIF tags. sort_key :",
"drawn around the resulting white pixels. If the contours are above the min_area",
"\"Eve\", \"age\": 7}] >>> extract_var(data=foo, var=\"name\") [\"Shane\", \"Eve\"] \"\"\" return [x[var] for x",
"using the crop parameter.\\n\" f\"Try crop={tup}.\") return tup else: print(inst) prev = curr",
"> \") if answer.lower() in (\"y\", \"yes\"): os.makedirs(directory) return directory print(\"Please input a",
"this function. parse_tags : list of tuples, optional By default, only Image DateTime",
"from process_jpg(). Object essentially holds data # used in exporting, parameters for graphing,",
"c:d] = test[e:f, g:h] diff = cv2.absdiff(test, image) choose.append((sum(cv2.sumElems(diff)), direct, test)) choose.sort() if",
": list of dictionaries, optional Typically requires the output of process_jpgs(). Can be",
"60, 2) day_hr = extract_var(self.jpg_data, \"24hr\") # meds = extract_var(self.jpg_data, \"median\") X =",
"is not None: image_pano(event.xdata) def on_key(event): if event.xdata is not None: if self.press[0]",
"cr_corn mod = mod[y1:y2, x1:x2] mod = cv2.cvtColor(mod, cv2.COLOR_BGR2RGB) ax_mod.imshow(mod) fig.canvas.draw_idle() rgb =",
".sav file, the Cam() object is now identical to the last. \"\"\" with",
"row[new_var] = curr - prev prev = curr def mark_edits(self, i, kind): \"\"\"Marks",
"from jpg_data filepaths before being passed on to frame differencing methods that generate",
"\"\"\" string = str(obj) return '\"' + string + '\"' if \",\" in",
"bounds, unlike generate_clone_tuples). \"\"\" mem = Mem() mem.crop_tuple = False mem.clone_tuple = False",
"for filename in found: filepath = os.path.join(dir_, filename) output.append({ \"filename\": filename, \"filepath\": filepath",
"crop and clone parameters. Parameters ---------- image : numpy.ndarray Image array, typically from",
"METHODS # Bare-bones. Take difference, threshold, and sum the mask. def SIMPLE(curr, prev,",
"new_count *= 1 + ( self.plt_vals[\"night_mult\"] * row[\"is_night\"]) row[\"new_count\"] = new_count for i,",
"to generate this object. \"\"\" image = CROPPER(image, crop) return cv2.equalizeHist(image) def CROP_CLONE_EQUALIZE(image,",
"row.items()} for row in self.jpg_data] for row in temp_data: if \"datetime\" in row.keys():",
"make jpg_data feedable to Cam(). Parameters ---------- dirpath : str Path to an",
"// 2][\"filepath\"])) clone = (generate_clone_tuples(clone_to, directs[0]) if clone_to else False) process_options = {\"crop\":",
"= find_imgs(input_directory()) jpg_data = attach_exif(jpg_paths) jpg_data.sort(key=lambda x: x[\"datetime\"]) print(\"→ Crop and clone out",
"a photo and its previous, after preprocessing / thresholding. \"\"\" if not threshold:",
"just like slicing images as np.arrays. clone : pair of tuples Matches the",
"called so as not to lose any prior work. Attributes ---------- jpg_data :",
"string + '\"' if \",\" in string else string def to_24_hour(datetime): \"\"\"Converts datetime.datetime",
"in (\"y\", \"yes\"): return filename elif filename: return filename def input_directory(): while True:",
"mappable. Returns ------- list of dictionaries Each row contains everything that is needed",
"x2), just like slicing images as np.arrays. clone : pair of tuples Matches",
"except cv2.error as inst: if \"(-209:Sizes\" in str(inst): (a, b), (c, d) =",
"make it?\") answer = input(\"Y / N > \") if answer.lower() in (\"y\",",
"BLURRED, but only sums drawn contours over given limit. def CONTOURS(curr, prev, threshold,",
"By default, only Image DateTime is retrieved from EXIF data using DEFAULT_PARSE. Examine",
"elif any(n >= self.length for n in array): array -= 1 else: break",
"data is desired from EXIF tags. sort_key : function, optional By default, dictionaries",
"row[\"new_count\"] < 0: if func == operator.sub: master_set.add(ind) break else: master_set.add(ind) except IndexError:",
"in row.keys(): row[\"timedelta\"] = row[\"timedelta\"].total_seconds() if \"selected\" in row.keys(): row[\"selected\"] = int(row[\"selected\"]) with",
"= crop_clone_preview( cv2.imread(jpg_data[len(jpg_data) // 2][\"filepath\"])) clone = (generate_clone_tuples(clone_to, directs[0]) if clone_to else False)",
"One of the two images for the absolute difference to be taken. prev",
"the min_area parameter, they are counted as a response (movement). Works very well,",
"__name__ == \"__main__\": print(\"→ Please input a directory path with camera-trapping images.\") jpg_paths",
"*_ = im.shape if w > h: scale = size / w else:",
"RESP_NUM self.plt_vals[key] = mod self.sliders[slider_key].valtext.set_text(\"%.2e\" % mod) else: self.plt_vals[key] = self.sliders[slider_key].val update() #",
"attached. \"\"\" output = [] for deep_row in jpg_data: row = deep_row.copy() tags",
":])) min_x = max(0, min(geometry[1, :])) max_x = min(W, max(geometry[1, :])) ignore =",
"tag. \"\"\" str_ = ''.join(x for x in str(raw) if x in string.digits)",
"print(\"Directory does not exist, would you like to make it?\") answer = input(\"Y",
"H or max_y < 0 or min_x > W or max_x < 0)",
"mod = image.copy() if not cl_ig: mem.clone_tuple = cl_corn trials = [] for",
"method=CONTOURS, crop=False, clone=False, threshold=False, ksize=11, min_area=100 ): \"\"\"Generates a response (movement) metric between",
"POTATOES # Requires data from process_jpg(). Object essentially holds data # used in",
"key == \"resp_thresh\": mod = self.sliders[slider_key].val ** RESP_NUM self.plt_vals[key] = mod self.sliders[slider_key].valtext.set_text(\"%.2e\" %",
"= int(round(event.xdata)) low, high = sorted((self.press[1], i)) lo_to_hi = range(max(0, low), min(self.length, high+1))",
"if \"datetime\" in row.keys(): row[\"datetime\"] = dt.strptime( row[\"datetime\"], \"%Y-%m-%d %H:%M:%S\" ) self.dt_present =",
"parameter in process_jpgs(). \"\"\" clone_to = np.array(clone_to) mults = np.array(DIRECTION_MULTS[fill_from[0].upper()]) a, b, c,",
"\"selected\" in row.keys(): row[\"selected\"] = int(row[\"selected\"]) with open(filename, \"w\") as f: f.write(json.dumps(self.plt_vals) +",
"d[k] = str(v).rjust(2, \"0\") return fmt.format(**d) def resize_long_edge(im, size): h, w, *_ =",
"- timer[1] total = elapsed / (progress / 100) remain = strfdelta(td(seconds=total -",
"return tup else: print(inst) prev = curr output.append(row) return output def construct_jpg_data( dirpath,",
"Default is 11. Must be positive, odd number. min_area : int, unused Only",
"img_type : tuple, optional By default, finds JPG image types, but can be",
"except AttributeError: pass if \"selected\" in row.keys(): row[\"selected\"] = bool(row[\"selected\"]) self.jpg_data = temp_data.copy()",
"parse_tags) jpg_data.sort(key=sort_key) if process_options == {}: print(\"Crop and clone image as desired.\") crop,",
"test[e:f, g:h] diff = cv2.absdiff(test, image) choose.append((sum(cv2.sumElems(diff)), direct, test)) choose.sort() if choose: _,",
"= eclick.xdata, eclick.ydata x2, y2 = erelease.xdata, erelease.ydata cr_corn, cr_ig = safe_corners(crop_RS.geometry) cl_corn,",
"finds their absolute difference. A simple threshold is called, the resulting white pixels",
"def rint(n): return round(int(n)) def sort_cols(var_name): if var_name in COL_ORDER: return COL_ORDER.index(var_name) else:",
"0, 100, mod, \"%.2e\"), (\"TRANS\", 0.06, 0, 120, self.plt_vals[\"trans_thresh\"], \"%.1f\"), (\"SMOOTH\", 0.04, 0,",
"= set() for i, row in enumerate(self.jpg_data): if row[\"selected\"]: for func in (operator.add,",
"process_jpgs() function. \"\"\" difference = cv2.absdiff(curr, prev) blurred = cv2.medianBlur(difference, ksize) _, mask",
"parse_tags=DEFAULT_PARSE): \"\"\"Loops through jpg_data, reading filepaths and attaching EXIF data. Parameters ---------- jpg_data",
"= False mem.clone_directs = False if cr_ig: cr_corn = (0, H, 0, W)",
"images for the absolute difference to be taken. prev : numpy.ndarray Like curr.",
"size): h, w, *_ = im.shape if w > h: scale = size",
"write_data.append(write_row) if write_data: with open(os.path.join(directory, \"_export.csv\"), \"w\") as f: variables = sorted(write_data[0].keys(), key=sort_cols)",
"and histogram equalization on images read from jpg_data filepaths before being passed on",
"to INCREASE response value to Inf. z - Hold and release to DECREASE",
"= RectangleSelector( ax_clone, RS_event, **RS_PARAMS) ax_crop.set_title(\"Crop\") ax_clone.set_title(\"Clone\") ax_mod.set_title(\"Result\") for axe in (ax_crop, ax_clone):",
"directory else: print(\"Directory does not exist, would you like to make it?\") answer",
"deep_row in jpg_data: row = deep_row.copy() tags = piexif.load(row[\"filepath\"]) for (key, tag), var,",
"= imgs[0] del choose else: mem.clone_tuple = False mem.clone_directs = False if cr_ig:",
"name. >>> foo = [{\"name\": \"Shane\", \"age\": 22}, {\"name\": \"Eve\", \"age\": 7}] >>>",
"self.sliders = {} self.user_edits = {} self.press = [None, None] self.toggle = False",
"fig.canvas.mpl_connect(\"key_press_event\", on_key) fig.canvas.mpl_connect(\"key_release_event\", off_key) fig.canvas.mpl_connect(\"button_press_event\", on_click) ax.fill_between( np.arange(0, self.length) + 0.5, -BIG_NUM, 0,",
"is attached to jpg_data. Day to night transitions are filtered out based on",
"pass to attach_exif(), if more data is desired from EXIF tags. Returns -------",
"a response (movement) metric between images. Works hierarchically to preform image cropping, cloning,",
"using DEFAULT_PARSE. Examine DEFAULT_PARSE as an example parameter to pass to attach_exif(), if",
"given limit. def CONTOURS(curr, prev, threshold, ksize=11, min_area=100): \"\"\"Slower, but powerful frame differencing",
"open(filename, \"r\") as f: self.plt_vals = json.loads(next(f)) self.plt_vals[\"resp_thresh\"] = ( self.plt_vals[\"resp_thresh\"] ** (1",
"its previous, after preprocessing / thresholding. \"\"\" if not threshold: thresh_init = False",
"EXIF data using DEFAULT_PARSE. Examine DEFAULT_PARSE as an example parameter to pass to",
"= curr output.append(row) return output def construct_jpg_data( dirpath, parse_tags=DEFAULT_PARSE, sort_key=SORT_BY_DT, process_options={} ): \"\"\"Performs",
"int(round(event.xdata)) if event.key == \"z\": self.press = [NEG_NUM, i] elif event.key == \"x\":",
"the CONTOURS() function, but retained here to shorten the process_jpgs() function. \"\"\" difference",
"= preprocess(jpg, crop, clone) row[\"shape\"] = jpg.shape row[\"median\"] = hist_median(jpg) if not thresh_init:",
"if \"selected\" in row.keys(): row[\"selected\"] = int(row[\"selected\"]) with open(filename, \"w\") as f: f.write(json.dumps(self.plt_vals)",
"= move < 0 prev = self.jpg_data[-is_neg] for i in range(-is_neg, (self.length *",
"mults) return (tuple(clone_to), tuple(clone_from)) # IMAGE PREPROCESSING def CROPPER(image, crop): \"\"\"Returns a cropped",
"not None: row[\"thumbpath\"] = os.path.join(thumb_dir, row[\"filename\"]) else: row[\"thumbpath\"] = row[\"filepath\"] row[\"count\"] = row[self.resp_var]",
"= { \"ceiling\": 40000, \"resp_thresh\": 20000, \"trans_thresh\": 30, \"smooth_time\": 1, \"night_mult\": 0 }",
"def sort_cols(var_name): if var_name in COL_ORDER: return COL_ORDER.index(var_name) else: return BIG_NUM def input_filename():",
"x[\"datetime\"]) print(\"→ Crop and clone out any timestamps from images.\") crop, clone_to, directs",
"= generate_clone_tuples(clone_to, directs[0]) if clone_to else False print(\"→ Images are being processed.\") processed_data",
"the clone parameter in process_jpgs(). \"\"\" clone_to = np.array(clone_to) mults = np.array(DIRECTION_MULTS[fill_from[0].upper()]) a,",
"timer[1] total = elapsed / (progress / 100) remain = strfdelta(td(seconds=total - elapsed),",
"Exports selected images and a .csv file. load(filename) Loads a .sav file. mark_edits(i)",
"for row in temp_data: if \"datetime\" in row.keys(): row[\"datetime\"] = dt.strptime( row[\"datetime\"], \"%Y-%m-%d",
"\"\"\" px_count = image.shape[0] * image.shape[1] hist = cv2.calcHist([image], [0], None, [256], [0,",
"read from jpg_data filepaths before being passed on to frame differencing methods that",
"= fig.add_subplot(111) fig.canvas.set_window_title(\"Response Filtering\") fig.subplots_adjust(0.07, 0.18, 0.97, 0.97) ax.grid(alpha=0.4) ax.set_axisbelow(True) ax.set_ylim([0, self.plt_vals[\"ceiling\"]]) ax.set_xlim([0,",
"a response (movement). Works very well, little noise; slower than others. Parameters ----------",
"Marks which photos have been edited. plot() Interactive plot used to select images",
"= [None, None] self.toggle = False self.buffer = [[None] * 64, [None] *",
"plt.rc(\"font\", **{\"size\": 8}) plt.rcParams[\"keymap.back\"] = \"left, backspace\" fig = plt.figure() ax = fig.add_subplot(111)",
"Cam(processed_data) print(\"→ Please input a file path for an initial save.\") cam.save(input_filename()) print(\"→",
"to this function. method : function, {SIMPLE, BLURRED, COUNTOURS} Determines the frame differencing",
"= RectangleSelector( ax_crop, RS_event, **RS_PARAMS) clone_RS = RectangleSelector( ax_clone, RS_event, **RS_PARAMS) ax_crop.set_title(\"Crop\") ax_clone.set_title(\"Clone\")",
"i % timer[0] == 0: stop_watch(i, timer) jpg = cv2.imread(row[\"filepath\"], 0) curr =",
"= method(curr, prev, threshold, ksize, min_area) except cv2.error as inst: if \"(-209:Sizes\" in",
"row[\"shape\"] = jpg.shape row[\"median\"] = hist_median(jpg) if not thresh_init: threshold = row[\"median\"]*1.05 try:",
"Slider, RectangleSelector import matplotlib.gridspec as gridspec # CONSTANTS BIG_NUM = int(1e9) NEG_NUM =",
"filled with zeros. \"\"\" d = {\"days\": tdelta.days} d[\"hours\"], rem = divmod(tdelta.seconds, 3600)",
"absolute difference. A simple threshold is called, the resulting white pixels are counted",
"datetime, but do have a variable for sequence. process_options : dictionary, optional Passes",
"help(Cam.plot) cam.plot() print(\"→ Save once again, so changes are recorded.\") cam.save(input_filename()) print(\"→ Finally,",
"list of dictionaries Contains filenames and filepaths. \"\"\" output = [] for dir_,",
"variable name. >>> foo = [{\"name\": \"Shane\", \"age\": 22}, {\"name\": \"Eve\", \"age\": 7}]",
"time import cv2 import piexif import numpy as np from sklearn.cluster import KMeans",
"str Directory path that is used for exporting thumbnails. long_edge : int, optional",
"def load(self, filename): \"\"\"Loads a .sav file, the Cam() object is now identical",
"interactive plot is laggy, use resize_with_exif() on your jpg_data list, and specify the",
"feedable to Cam(). Parameters ---------- dirpath : str Path to an image-containing directory.",
"a, d - c h_or_w = np.array([h, h, w, w]) clone_from = clone_to",
"elif event.key == \",\": self.press = [0, i] if event.key in \"zxc,\": image_pano(event.xdata)",
"= False new_count = row[\"count\"] if row[\"med_diff\"] > self.plt_vals[\"trans_thresh\"]: new_count = 0 self.mark_edits(i,",
"\"\"\"Walks directory path, finding all files ending in img_type. Parameters ---------- dirpath :",
"\"trans_edit\") if self.dt_present: new_count *= 1 + ( self.plt_vals[\"night_mult\"] * row[\"is_night\"]) row[\"new_count\"] =",
"row = self.jpg_data[ind] if row[\"new_count\"] < 0: if func == operator.sub: master_set.add(ind) break",
"extract_var(self.jpg_data, \"24hr\") # meds = extract_var(self.jpg_data, \"median\") X = np.array(day_hr).reshape(-1, 1) kmeans =",
"Contains format calls to days, hours, minutes, and seconds. Returns ------- str Right",
"alpha=0.5) self.lines[\"selected\"] = ax.fill_between( np.arange(0, self.length) + 0.5, -BIG_NUM, BIG_NUM, where=extract_var(self.jpg_data, \"selected\"), facecolor=\"#F00314\")",
"cv2.error as inst: if \"(-209:Sizes\" in str(inst): (a, b), (c, d) = curr.shape[:2],",
"self.dt_present: self.attach_diffs(\"datetime\", \"timedelta\") for row in self.jpg_data: row[\"24hr\"] = to_24_hour(row[\"datetime\"]) row[\"td_minutes\"] = round(",
"self.length) + 0.5, -BIG_NUM, BIG_NUM, where=extract_var(self.jpg_data, \"is_night\"), facecolor=\"#003459\", alpha=0.5) except KeyError: pass on_slide(1)",
"other direction in the directs list (all have been checked for bounds, unlike",
"after preprocessing / thresholding. \"\"\" if not threshold: thresh_init = False if not",
"if i == 0: self.jpg_data[i][kind] = True else: self.jpg_data[i][kind] = True self.jpg_data[i-1][kind] =",
"ax.axhline() for name, pos, minv, maxv, init, fmt in SLIDER_PARAMS: slider_ax = fig.add_axes([0.125,",
"and filepaths. \"\"\" output = [] for dir_, _, files in os.walk(dirpath): if",
"unlike generate_clone_tuples). \"\"\" mem = Mem() mem.crop_tuple = False mem.clone_tuple = False mem.clone_directs",
"fig.add_subplot(gs[1, :]) crop_RS = RectangleSelector( ax_crop, RS_event, **RS_PARAMS) clone_RS = RectangleSelector( ax_clone, RS_event,",
"numbers decreases sensitivity. Returns ------- list of dictionaries Same as incoming jpg_data, but",
":] for img in stack]) h, w, *_ = pano.shape cv2.namedWindow(\"Gallery\", cv2.WINDOW_NORMAL) cv2.imshow(\"Gallery\",",
"data. Parameters ---------- jpg_data : list of dictionaries Requires that \"filepath\" is in",
"False mem.clone_directs = False def update(event): if crop_RS.active: crop_RS.update() if clone_RS.active: clone_RS.update() def",
"For simplicity, use generate_clone_tuples() to generate this object. \"\"\" image = CROPPER(image, crop)",
"crop parameter.\\n\" f\"Try crop={tup}.\") return tup else: print(inst) prev = curr output.append(row) return",
"lo_H) ax_crop.imshow(rgb) ax_clone.imshow(rgb) ax_mod.imshow(rgb) plt.connect(\"draw_event\", update) plt.show() return mem.crop_tuple, mem.clone_tuple, mem.clone_directs # FRAME",
"to make jpg_data feedable to Cam(). Parameters ---------- dirpath : str Path to",
"= np.array(clone_to) mults = np.array(DIRECTION_MULTS[fill_from[0].upper()]) a, b, c, d = clone_to h, w",
"< 0 or b > H or c < 0 or d >",
"the cv2.medianBlur() function. Default is 11. Must be positive, odd number. min_area :",
"for row in self.jpg_data: if thumb_dir is not None: row[\"thumbpath\"] = os.path.join(thumb_dir, row[\"filename\"])",
"d - c h_or_w = np.array([h, h, w, w]) clone_from = clone_to +",
"// 2][\"filepath\"])) clone = generate_clone_tuples(clone_to, directs[0]) if clone_to else False print(\"→ Images are",
"of dictionaries Requires that \"filepath\" and \"filename\" is in dictionary keys, which is",
"\"count\" variable is used as a response, but alternatives like \"median\" can be",
"Requires a list of dictionaries. \"\"\" prev = self.jpg_data[0][var] for row in self.jpg_data:",
"BIG_NUM, where=[r[\"trans_edit\"] or r[\"user_edit\"] for r in self.jpg_data], facecolor=\"#D8BFAA\", alpha=0.5) self.lines[\"selected\"] = ax.fill_between(",
"crop, clone) row[\"shape\"] = jpg.shape row[\"median\"] = hist_median(jpg) if not thresh_init: threshold =",
"are counted toward response (movement). Works decently, a little faster than COUNTOURS. Parameters",
"threshold, 255, cv2.THRESH_BINARY) return cv2.countNonZero(mask) # Like BLURRED, but only sums drawn contours",
"dt_ISO = str(i) new_name = \"_\".join((dt_ISO, row[\"filename\"])) new_path = os.path.join(directory, new_name) write_row[\"filename\"] =",
"test)) choose.sort() if choose: _, directs, imgs = list(zip(*choose)) mem.clone_directs = directs mod",
"area to count as a response (movement). Default is an area of 100",
"is desired for a load() method call. resp_var : str, optional A key",
"in gallery. x - Hold and release to INCREASE response value to Inf.",
"mark_edits(i) Marks which photos have been edited. plot() Interactive plot used to select",
"stack.append(img) min_y = min(img.shape[0] for img in stack) pano = np.hstack([img[:min_y, :] for",
"self.sliders[slider_key].val update() # Displays last two and next two images from response spike.",
"tuple(clone_from)) # IMAGE PREPROCESSING def CROPPER(image, crop): \"\"\"Returns a cropped image. Parameters ----------",
"= hist_median(jpg) if not thresh_init: threshold = row[\"median\"]*1.05 try: row[\"count\"] = method(curr, prev,",
"Object essentially holds data # used in exporting, parameters for graphing, and plot",
"function. min_area : int, unused Only used in the CONTOURS() function, but retained",
"if self.toggle: gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img = cv2.cv2.equalizeHist(gray) stack.append(img) min_y = min(img.shape[0]",
"blurred = cv2.medianBlur(difference, ksize) _, mask = cv2.threshold( blurred, threshold, 255, cv2.THRESH_BINARY) return",
"facecolor=\"#003459\", alpha=0.5) except KeyError: pass on_slide(1) plt.show() cv2.destroyAllWindows() if __name__ == \"__main__\": print(\"→",
"remain = strfdelta(td(seconds=total - elapsed), \"{days}:{hours}:{minutes}:{seconds}\") print(f\"{progress}% done. {remain} left.\") def strfdelta(tdelta, fmt):",
"for bounds, unlike generate_clone_tuples). \"\"\" mem = Mem() mem.crop_tuple = False mem.clone_tuple =",
"in self.lines.keys(): self.lines[name].remove() np_counts = np.array(extract_var(self.jpg_data, \"new_count\")) self.lines[\"edited\"] = ax.fill_between( np.arange(0, self.length) +",
"exist, would you like to make it?\") answer = input(\"Y / N >",
"smaller images will be displayed in the Gallery tab. \"\"\" self.resp_var = resp_var",
"def hist_median(image): \"\"\"Quickly finds the median tone of a grayscale image. \"\"\" px_count",
"current and previous items. export(directory) Exports selected images and a .csv file. load(filename)",
"temp_data = json.loads(next(f)) temp_dict = json.loads(next(f)) for row in temp_data: if \"datetime\" in",
"SORT_BY_DT(row): \"\"\"Default sort for construct_jpg_data(). \"\"\" return row[\"datetime\"] DEFAULT_PARSE = [ ((\"0th\", 306),",
"an example parameter to pass to attach_exif(), if more data is desired from",
"in the directs list (all have been checked for bounds, unlike generate_clone_tuples). \"\"\"",
"pass def rint(n): return round(int(n)) def sort_cols(var_name): if var_name in COL_ORDER: return COL_ORDER.index(var_name)",
"ValueError(\"No images selected for export.\") def attach_diffs(self, var, new_var): \"\"\"Finds the difference between",
"generate_thumbnails(jpg_data, export_dir, long_edge=1024): \"\"\"Formats a timedelta object as a string. Parameters ---------- jpg_data",
"the interactive plot is laggy, use resize_with_exif() on your jpg_data list, and specify",
"# SPECIFIC FUNCTIONS def find_imgs(dirpath, img_type=(\".jpg\", \".jpeg\")): \"\"\"Walks directory path, finding all files",
"used to store, plot, filter, and export image data. Contains the heart of",
"camera exports a different filetype. Returns ------- list of dictionaries Contains filenames and",
"for r in self.jpg_data], facecolor=\"#D8BFAA\", alpha=0.5) self.lines[\"selected\"] = ax.fill_between( np.arange(0, self.length) + 0.5,",
"= new_count for i, shift in self.user_edits.items(): self.jpg_data[i][\"new_count\"] = shift self.mark_edits(i, \"user_edit\") def",
"= range(max(0, low), min(self.length, high+1)) if event.key in \"zx\": new_edits = {i: self.press[0]",
"> threshold: return i def generate_clone_tuples(clone_to, fill_from): \"\"\"Loops through jpg_data, reading filepaths and",
"---------- dirpath : str Path to an image-containing directory. parse_tags : list of",
"have changed between a photo and its previous, after preprocessing / thresholding. \"\"\"",
"= [None, None] update() except TypeError: pass plt.rc(\"font\", **{\"size\": 8}) plt.rcParams[\"keymap.back\"] = \"left,",
"use generate_clone_tuples() to generate this object. \"\"\" image = CROPPER(image, crop) return cv2.equalizeHist(image)",
"count as a response (movement). Default is an area of 100 pixels. Larger",
"= fig.add_subplot(gs[0, 0]) ax_clone = fig.add_subplot(gs[0, 1]) ax_mod = fig.add_subplot(gs[1, :]) crop_RS =",
"Default is an area of 100 pixels. Larger numbers decreases sensitivity. \"\"\" difference",
"function. ksize : int, unused Used in the BLURRED() and CONTOURS() functions, but",
"selected images and a .csv file. load(filename) Loads a .sav file. mark_edits(i) Marks",
"print(\"Please input a new directory path.\") def csv_safe(obj): \"\"\"Puts quotes around strings with",
"0.5, -BIG_NUM, BIG_NUM, where=extract_var(self.jpg_data, \"is_night\"), facecolor=\"#003459\", alpha=0.5) except KeyError: pass on_slide(1) plt.show() cv2.destroyAllWindows()",
"be fed directly into process_jpgs(). Then, use \"generate_clone_tuples(clone_to, directs[0])\" to get the clone",
"row[\"trans_edit\"] = False if self.dt_present: self.attach_diffs(\"datetime\", \"timedelta\") for row in self.jpg_data: row[\"24hr\"] =",
"event.key == \",\": for i in lo_to_hi: self.user_edits.pop(i, None) self.press = [None, None]",
"curr = preprocess(jpg, crop, clone) row[\"shape\"] = jpg.shape row[\"median\"] = hist_median(jpg) if not",
"cv2.threshold() function. ksize : int, unused Used in the BLURRED() and CONTOURS() functions,",
"fig.add_subplot(gs[0, 0]) ax_clone = fig.add_subplot(gs[0, 1]) ax_mod = fig.add_subplot(gs[1, :]) crop_RS = RectangleSelector(",
"as np from sklearn.cluster import KMeans from datetime import datetime as dt, timedelta",
"of dictionaries Same as incoming jpg_data, but now with the median image tone",
"v - Press for EQUALIZED image (for dark images). \"\"\" try: self.jpg_data except",
"c, d), (e, f, g, h) = clone image[a:b, c:d] = image[e:f, g:h]",
"= cr_corn y1, y2, x1, x2 = cr_corn mod = mod[y1:y2, x1:x2] mod",
"slider_key = key[:key.find(\"_\")].upper() if key == \"resp_thresh\": mod = self.sliders[slider_key].val ** RESP_NUM self.plt_vals[key]",
"generate_clone_tuples). \"\"\" mem = Mem() mem.crop_tuple = False mem.clone_tuple = False mem.clone_directs =",
"dirpath, parse_tags=DEFAULT_PARSE, sort_key=SORT_BY_DT, process_options={} ): \"\"\"Performs all necessary steps to make jpg_data feedable",
"return cv2.resize(im, (new_w, new_h)) def generate_thumbnails(jpg_data, export_dir, long_edge=1024): \"\"\"Formats a timedelta object as",
"plt.figure() fig.canvas.set_window_title(\"Crop and Clone Preview\") ax_crop = fig.add_subplot(gs[0, 0]) ax_clone = fig.add_subplot(gs[0, 1])",
"as np.arrays. \"\"\" y1, y2, x1, x2 = crop return image[y1:y2, x1:x2] def",
"and attaching EXIF data. Parameters ---------- jpg_data : list of dictionaries Requires that",
"ax_mod.imshow(rgb) plt.connect(\"draw_event\", update) plt.show() return mem.crop_tuple, mem.clone_tuple, mem.clone_directs # FRAME DIFFERENCING METHODS #",
"not crop: crop = (0, h, 0, w) prev = preprocess(jpg, crop, clone)",
"lose any prior work. Attributes ---------- jpg_data : list of dictionaries Similar to",
"resize_long_edge(im, long_edge) cv2.imwrite(to_path, resized) piexif.transplant(from_path, to_path) # SPECIFIC FUNCTIONS def find_imgs(dirpath, img_type=(\".jpg\", \".jpeg\")):",
"Parameters ---------- dirpath : str Path to an image-containing directory. img_type : tuple,",
"image is blurred to reduce noise. After thresholding, the resulting white pixels are",
"filetype. Returns ------- list of dictionaries Contains filenames and filepaths. \"\"\" output =",
"\"new_count\", \"selected\", \"user_edit\", \"trans_edit\" ] RS_PARAMS = { \"drawtype\": \"box\", \"useblit\": True, \"button\":",
"from matplotlib.widgets import Slider, RectangleSelector import matplotlib.gridspec as gridspec # CONSTANTS BIG_NUM =",
"= jpg[\"filepath\"] to_path = os.path.join(export_dir, jpg[\"filename\"]) im = cv2.imread(from_path) resized = resize_long_edge(im, long_edge)",
"sort_key : function, optional By default, dictionaries within the jpg_data list are sorted",
"to DECREASE response value to 0. , - Hold and release to REMOVE",
"self.lines = {} self.sliders = {} self.user_edits = {} self.press = [None, None]",
"directory): \"\"\"Exports selected images and a .csv file to specified directory. \"\"\" if",
"b), (c, d) = curr.shape[:2], prev.shape[:2] h, w = min(a, c), min(b, d)",
"After thresholding, contours are drawn around the resulting white pixels. If the contours",
": list of dictionaries Similar to what is inputted, but includes variables denoting",
"np.arange(0, self.length) + 0.5, -BIG_NUM, 0, facecolor=\"white\", alpha=0.75, zorder=2) try: ax.fill_between( np.arange(0, self.length)",
"construct_jpg_data(). \"\"\" return row[\"datetime\"] DEFAULT_PARSE = [ ((\"0th\", 306), \"datetime\", PARSE_DT) ] DEFAULT_PLOT_PARAMS",
"can be fed into the Cam() class for response filtering. Parameters ---------- jpg_data",
"------- attach_diffs(var, new_var) Finds the difference between the current and previous items. export(directory)",
"cv2.imread(). crop : tuple Format is (y1, y2, x1, x2), just like slicing",
"a cropped image, with specified cloning and equalization. Parameters ---------- image : numpy.ndarray",
"jpg_data = attach_exif(jpg_paths) jpg_data.sort(key=lambda x: x[\"datetime\"]) print(\"→ Crop and clone out any timestamps",
"= CROPPER(image, crop) return cv2.equalizeHist(image) def CROP_CLONE_EQUALIZE(image, crop, clone): \"\"\"Returns a cropped image,",
"minv, maxv, init, fmt in SLIDER_PARAMS: slider_ax = fig.add_axes([0.125, pos, 0.8, 0.02]) self.sliders[name]",
"/ RESP_NUM) SLIDER_PARAMS = [ (\"RESP\", 0.08, 0, 100, mod, \"%.2e\"), (\"TRANS\", 0.06,",
"row contains everything that is needed to feed a Cam() object with its",
"with zeros. \"\"\" d = {\"days\": tdelta.days} d[\"hours\"], rem = divmod(tdelta.seconds, 3600) d[\"minutes\"],",
"input(\"DIRPATH > \") if os.path.isdir(directory): return directory else: print(\"Directory does not exist, would",
": pair of tuples, optional Matches the format ((clone_to), (clone_from)). For simplicity, use",
"decently, a little faster than COUNTOURS. Parameters ---------- curr : numpy.ndarray Image array,",
"{}: print(\"Crop and clone image as desired.\") crop, clone_to, directs = crop_clone_preview( cv2.imread(jpg_data[len(jpg_data)",
"= np.array(DIRECTION_MULTS[fill_from[0].upper()]) a, b, c, d = clone_to h, w = b -",
"cam = Cam(processed_data) print(\"→ Please input a file path for an initial save.\")",
"*= 1 + ( self.plt_vals[\"night_mult\"] * row[\"is_night\"]) row[\"new_count\"] = new_count for i, shift",
"CONTOURS() functions, but retained here to shorten the process_jpgs() function. min_area : int,",
"thresholding, the differenced image is blurred to reduce noise. After thresholding, the resulting",
"temp_data.copy() self.length = len(self.jpg_data) self.user_edits = {int(k): v for k, v in temp_dict.items()}",
"pass for i in master_set: self.jpg_data[i][\"selected\"] = True def plot(self): \"\"\"Interactive plot used",
"+ time.minute / 60 + time.second / 3600 def extract_var(data, var): \"\"\"Returns a",
"Default is an area of 100 pixels. Larger numbers decreases sensitivity. Returns -------",
"= min(img.shape[0] for img in stack) pano = np.hstack([img[:min_y, :] for img in",
"= b - a, d - c h_or_w = np.array([h, h, w, w])",
"new_path = os.path.join(directory, new_name) write_row[\"filename\"] = new_name write_row[\"filepath\"] = new_path write_row[\"old_name\"] = row[\"filename\"]",
"sum the mask. def SIMPLE(curr, prev, threshold, ksize=None, min_area=None): \"\"\"Most basic frame differencing",
"\"filepath\", \"shape\", \"datetime\", \"24hr\", \"is_night\", \"timedelta\", \"td_minutes\", \"median\", \"med_diff\", \"count\", \"new_count\", \"selected\", \"user_edit\",",
"row[\"filepath\"] row[\"count\"] = row[self.resp_var] row[\"med_diff\"] = abs(row[\"med_diff\"]) row[\"selected\"] = False row[\"user_edit\"] = False",
"< 0 prev = self.jpg_data[-is_neg] for i in range(-is_neg, (self.length * move) -",
"if os.path.exists(filename): print(\"File already exists, would you like to overwrite it?\") answer =",
"to_path) # SPECIFIC FUNCTIONS def find_imgs(dirpath, img_type=(\".jpg\", \".jpeg\")): \"\"\"Walks directory path, finding all",
"response (movement). Very noisy, but fast. Parameters ---------- curr : numpy.ndarray Image array,",
"this attribute. Methods ------- attach_diffs(var, new_var) Finds the difference between the current and",
"\"box\", \"useblit\": True, \"button\": [1, 3], \"minspanx\": 5, \"minspany\": 5, \"spancoords\": \"pixels\", \"interactive\":",
"x2), just like slicing images as np.arrays. clone : pair of tuples, optional",
"W): trials.append((tups, direct)) choose = [] for (tups, direct) in trials: test =",
"// scale), (W + W // scale) lo_H, hi_H = (0 - H",
"if \"(-209:Sizes\" in str(inst): (a, b), (c, d) = curr.shape[:2], prev.shape[:2] h, w",
"array -= 1 else: break stack = [] for n in array: if",
"filtering. Parameters ---------- jpg_data : list of dictionaries Requires that \"filepath\" is in",
"is not None: if self.press[0] is None: i = int(round(event.xdata)) if event.key ==",
"ax.set_xlabel(\"Frame\") ax.set_ylabel(\"Response\") plt.yticks(rotation=45) for name in (\"count\", \"threshold\", \"selected\", \"edited\"): self.lines[name] = ax.axhline()",
"jpg_paths = find_imgs(input_directory()) jpg_data = attach_exif(jpg_paths) jpg_data.sort(key=lambda x: x[\"datetime\"]) print(\"→ Crop and clone",
"filename): \"\"\"Loads a .sav file, the Cam() object is now identical to the",
"y2 = erelease.xdata, erelease.ydata cr_corn, cr_ig = safe_corners(crop_RS.geometry) cl_corn, cl_ig = safe_corners(clone_RS.geometry) mod",
"frame differencing method. Takes two images, then finds their absolute difference. Prior to",
"== \",\": self.press = [0, i] if event.key in \"zxc,\": image_pano(event.xdata) elif event.key",
"the difference between the current and previous items. export(directory) Exports selected images and",
"/ w else: scale = size / h new_w = rint(w * scale)",
"is inputted, but includes variables denoting selection, edits, event, etc. plot_params : dictionary",
"self.toggle image_pano(event.xdata) elif event.key == \".\": self.user_edits = {} def off_key(event): try: if",
"optional By default, images will be resized to 1024 pixels on the long",
"self.plt_vals[\"resp_thresh\"] ** (1 / RESP_NUM) SLIDER_PARAMS = [ (\"RESP\", 0.08, 0, 100, mod,",
"Then, use \"generate_clone_tuples(clone_to, directs[0])\" to get the clone parameter, or any other direction",
"\"x\": self.press = [BIG_NUM, i] elif event.key == \",\": self.press = [0, i]",
"**process_options) print(\"Done!\") return output # THE MEAT AND POTATOES # Requires data from",
"in enumerate(kmeans.labels_): self.jpg_data[n][\"is_night\"] = index in night_indices def save(self, filename): \"\"\"Dumps a JSON",
"in self.buffer[0]: ind = self.buffer[0].index(n) img = self.buffer[1][ind] self.buffer[0].append(self.buffer[0].pop(ind)) self.buffer[1].append(self.buffer[1].pop(ind)) else: img =",
"\"selected\", \"edited\"): self.lines[name] = ax.axhline() for name, pos, minv, maxv, init, fmt in",
"the jpg_data list are sorted by their \"Image DateTime\" EXIF tag. This can",
"master_set.add(ind) break else: master_set.add(ind) except IndexError: pass for i in master_set: self.jpg_data[i][\"selected\"] =",
"event.dblclick and event.xdata is not None: image_pano(event.xdata) def on_key(event): if event.xdata is not",
"// timer[0] elapsed = time.time() - timer[1] total = elapsed / (progress /",
"export_dir : str Directory path that is used for exporting thumbnails. long_edge :",
"in files if f.lower().endswith(img_type) ) for filename in found: filepath = os.path.join(dir_, filename)",
"in COL_ORDER: return COL_ORDER.index(var_name) else: return BIG_NUM def input_filename(): while True: filename =",
"i)) lo_to_hi = range(max(0, low), min(self.length, high+1)) if event.key in \"zx\": new_edits =",
"then finds their absolute difference. A simple threshold is called, the resulting white",
"cv2.findContours( mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2:] count = 0 for cnt in contours: area =",
"(movement). Default is an area of 100 pixels. Larger numbers decreases sensitivity. \"\"\"",
"[[None] * 64, [None] * 64] self.recent_folder = os.path.expanduser(\"~\") # Cam objects don\"t",
"if not os.path.exists(directory): os.makedirs(directory) write_data = [] for i, row in enumerate(self.jpg_data): write_row",
"or any other direction in the directs list (all have been checked for",
"draw() def draw(): for name in self.lines.keys(): self.lines[name].remove() np_counts = np.array(extract_var(self.jpg_data, \"new_count\")) self.lines[\"edited\"]",
"def on_key(event): if event.xdata is not None: if self.press[0] is None: i =",
"0 self.mark_edits(i, \"trans_edit\") if self.dt_present: new_count *= 1 + ( self.plt_vals[\"night_mult\"] * row[\"is_night\"])",
"# used in exporting, parameters for graphing, and plot function. class Cam(): \"\"\"",
"the current and previous variable. Requires a list of dictionaries. \"\"\" prev =",
"difference between the current and previous variable. Requires a list of dictionaries. \"\"\"",
"cv2.medianBlur() function. Default is 11. Must be positive, odd number. min_area : int,",
"v in variables)) else: raise ValueError(\"No images selected for export.\") def attach_diffs(self, var,",
"self.sliders[name].on_changed(on_slide) fig.canvas.mpl_connect(\"key_press_event\", on_key) fig.canvas.mpl_connect(\"key_release_event\", off_key) fig.canvas.mpl_connect(\"button_press_event\", on_click) ax.fill_between( np.arange(0, self.length) + 0.5, -BIG_NUM,",
"x: x[\"datetime\"]) print(\"→ Crop and clone out any timestamps from images.\") crop, clone_to,",
"filtering images with the plot, save() and export() should be called so as",
"Parameters ---------- image : numpy.ndarray Image array, typically from cv2.imread(). crop : tuple",
"stop_watch(i, timer) from_path = jpg[\"filepath\"] to_path = os.path.join(export_dir, jpg[\"filename\"]) im = cv2.imread(from_path) resized",
"left to right based on increasing accuracy, decreasing speed. crop : tuple Format",
"processing them first. thumb_dir : str, optional If the interactive plot is laggy,",
"fmt): \"\"\"Formats a timedelta object as a string. Parameters ---------- tdelta : datetime.timedelta",
"values corresponding to a variable name. >>> foo = [{\"name\": \"Shane\", \"age\": 22},",
"input_directory(): while True: directory = input(\"DIRPATH > \") if os.path.isdir(directory): return directory else:",
"= dt.strftime( row[\"datetime\"], \"%Y%m%dT%H%M%S\" ) else: dt_ISO = str(i) new_name = \"_\".join((dt_ISO, row[\"filename\"]))",
"sorted(write_data[0].keys(), key=sort_cols) for i, row in enumerate(write_data): if i != 0: f.write(\"\\n\") else:",
"\"ceiling\": 40000, \"resp_thresh\": 20000, \"trans_thresh\": 30, \"smooth_time\": 1, \"night_mult\": 0 } DIRECTION_MULTS =",
"\"{days}:{hours}:{minutes}:{seconds}\") print(f\"{progress}% done. {remain} left.\") def strfdelta(tdelta, fmt): \"\"\"Formats a timedelta object as",
"edited based on [i]ndex. \"\"\" if i == 0: self.jpg_data[i][kind] = True else:",
"= ax.fill_between( np.arange(0, self.length) + 0.5, -BIG_NUM, BIG_NUM, where=extract_var(self.jpg_data, \"selected\"), facecolor=\"#F00314\") self.lines[\"count\"] =",
"y1 = eclick.xdata, eclick.ydata x2, y2 = erelease.xdata, erelease.ydata cr_corn, cr_ig = safe_corners(crop_RS.geometry)",
"---------- jpg_data : list of dictionaries Requires that \"filepath\" and \"filename\" is in",
"in range(-is_neg, (self.length * move) - is_neg, move): curr = self.jpg_data[i] boo =",
"of dictionaries Similar to what is inputted, but includes variables denoting selection, edits,",
"\"\"\"Default parser for EXIF \"Image DateTime\" tag. \"\"\" str_ = ''.join(x for x",
"operator.sub): for j in range(nudge+1): ind = func(i, j) try: row = self.jpg_data[ind]",
"lo_H, hi_H = (0 - H // scale), (H + H // scale)",
"def generate_clone_tuples(clone_to, fill_from): \"\"\"Loops through jpg_data, reading filepaths and attaching EXIF data. Useful",
"to plot jpgs without processing them first. thumb_dir : str, optional If the",
": str Contains format calls to days, hours, minutes, and seconds. Returns -------",
"which is easily provided by find_imgs() prior to this function. parse_tags : list",
"''.join(x for x in str(raw) if x in string.digits) return dt.strptime(str_, \"%Y%m%d%H%M%S\") def",
"CONSTANTS BIG_NUM = int(1e9) NEG_NUM = -0.1 RESP_NUM = 3.5 def PARSE_DT(raw): \"\"\"Default",
"cv2.equalizeHist(image) def CROP_CLONE_EQUALIZE(image, crop, clone): \"\"\"Returns a cropped image, with specified cloning and",
"simplicity, use generate_clone_tuples() to generate this object. \"\"\" image = CROPPER(image, crop) return",
"sums drawn contours over given limit. def CONTOURS(curr, prev, threshold, ksize=11, min_area=100): \"\"\"Slower,",
"d.items(): if k != \"days\": d[k] = str(v).rjust(2, \"0\") return fmt.format(**d) def resize_long_edge(im,",
"of dictionaries Same as jpg_data, but now with desired EXIF data attached. \"\"\"",
"\"shape\", \"datetime\", \"24hr\", \"is_night\", \"timedelta\", \"td_minutes\", \"median\", \"med_diff\", \"count\", \"new_count\", \"selected\", \"user_edit\", \"trans_edit\"",
"typically the \"count\" variable is used as a response, but alternatives like \"median\"",
"of process_jpgs(). Can be omitted if a empty Cam() object is desired for",
"= (0 - W // scale), (W + W // scale) lo_H, hi_H",
"into process_jpgs(). Then, use \"generate_clone_tuples(clone_to, directs[0])\" to get the clone parameter, or any",
"cr_corn y1, y2, x1, x2 = cr_corn mod = mod[y1:y2, x1:x2] mod =",
"answer.lower() in (\"y\", \"yes\"): return filename elif filename: return filename def input_directory(): while",
"dark images). \"\"\" try: self.jpg_data except AttributeError as inst: raise inst mod =",
"matplotlib.gridspec as gridspec # CONSTANTS BIG_NUM = int(1e9) NEG_NUM = -0.1 RESP_NUM =",
"hours, minutes, and seconds. Returns ------- str Right justified 2 spaces, filled with",
"as np.arrays. clone : pair of tuples, optional Matches the format ((clone_to), (clone_from)).",
"min_area : int, unused Only used in the CONTOURS() function, but retained here",
"string. Parameters ---------- tdelta : datetime.timedelta Timedelta object to format. fmt : str",
"jpg_data : list of dictionaries Requires that \"filepath\" is in dictionary keys, which",
"row in self.jpg_data: if thumb_dir is not None: row[\"thumbpath\"] = os.path.join(thumb_dir, row[\"filename\"]) else:",
"var_name in COL_ORDER: return COL_ORDER.index(var_name) else: return BIG_NUM def input_filename(): while True: filename",
"True: filename = input(\"FILEPATH > \") if os.path.exists(filename): print(\"File already exists, would you",
"to get the clone parameter, or any other direction in the directs list",
"an image-containing directory. parse_tags : list of tuples, optional By default, only Image",
"if \"datetime\" in row.keys(): row[\"datetime\"] = dt.strftime( row[\"datetime\"], \"%Y-%m-%d %H:%M:%S\") if \"timedelta\" in",
"export.\") def attach_diffs(self, var, new_var): \"\"\"Finds the difference between the current and previous",
"filtered out based on slider. Counts taken at with nighttime are multiplied based",
"os.path.join(directory, new_name) write_row[\"filename\"] = new_name write_row[\"filepath\"] = new_path write_row[\"old_name\"] = row[\"filename\"] write_row[\"old_path\"] =",
"the process_jpgs() function. min_area : int, unused Only used in the CONTOURS() function,",
"format. fmt : str Contains format calls to days, hours, minutes, and seconds.",
"their \"Image DateTime\" EXIF tag. This can be changed if images don\"t have",
"self.user_edits = {**self.user_edits, **new_edits} elif event.key == \",\": for i in lo_to_hi: self.user_edits.pop(i,",
"!= \"days\": d[k] = str(v).rjust(2, \"0\") return fmt.format(**d) def resize_long_edge(im, size): h, w,",
"---------- image : numpy.ndarray Image array, typically from cv2.imread(). Returns ------- tuple Format",
"threshold, ksize=11, min_area=100): \"\"\"Slower, but powerful frame differencing method. Takes two images, then",
"True else: self.jpg_data[i][kind] = True self.jpg_data[i-1][kind] = True def update_counts(self): \"\"\"Updates jpg_data with",
"as a string. Parameters ---------- jpg_data : list of dictionaries Requires that \"filepath\"",
"input(\"FILEPATH > \") if os.path.exists(filename): print(\"File already exists, would you like to overwrite",
"np from sklearn.cluster import KMeans from datetime import datetime as dt, timedelta as",
"self.length for n in array): array -= 1 else: break stack = []",
"decreasing speed. crop : tuple Format is (y1, y2, x1, x2), just like",
"which is easily provided by find_imgs() prior to this function. export_dir : str",
"is (y1, y2, x1, x2), just like slicing images as np.arrays. clone :",
"used in exporting, parameters for graphing, and plot function. class Cam(): \"\"\" A",
"datetime.time() return time.hour + time.minute / 60 + time.second / 3600 def extract_var(data,",
"i != 0: f.write(\"\\n\") else: f.write(\",\".join(variables) + \"\\n\") f.write(\",\".join(csv_safe(row[v]) for v in variables))",
"the current and previous items. export(directory) Exports selected images and a .csv file.",
"lo_to_hi} self.user_edits = {**self.user_edits, **new_edits} elif event.key == \",\": for i in lo_to_hi:",
"parameter.\\n\" f\"Try crop={tup}.\") return tup else: print(inst) prev = curr output.append(row) return output",
"def CONTOURS(curr, prev, threshold, ksize=11, min_area=100): \"\"\"Slower, but powerful frame differencing method. Takes",
"difference, threshold, and sum the mask. def SIMPLE(curr, prev, threshold, ksize=None, min_area=None): \"\"\"Most",
"of dictionaries Requires that \"filepath\" is in dictionary keys, which is easily provided",
"True, \"button\": [1, 3], \"minspanx\": 5, \"minspany\": 5, \"spancoords\": \"pixels\", \"interactive\": True }",
": numpy.ndarray Image array, typically from cv2.imread(). One of the two images for",
"(movement). Default is an area of 100 pixels. Larger numbers decreases sensitivity. Returns",
"prev[\"new_count\"] > self.plt_vals[\"resp_thresh\"] or curr[\"new_count\"] > self.plt_vals[\"resp_thresh\"]) if i == self.length-1: curr[\"selected\"] =",
"new_var) Finds the difference between the current and previous items. export(directory) Exports selected",
"use generate_clone_tuples() to generate this object. threshold : int, in range(0, 256) Parameter",
"h, w, *_ = im.shape if w > h: scale = size /",
"self.user_edits = {} self.press = [None, None] self.toggle = False self.buffer = [[None]",
"Difference, blur (amount changes with ksize), mask and sum. def BLURRED(curr, prev, threshold,",
"\"resp_thresh\": 20000, \"trans_thresh\": 30, \"smooth_time\": 1, \"night_mult\": 0 } DIRECTION_MULTS = { \"A\":",
"if k != \"days\": d[k] = str(v).rjust(2, \"0\") return fmt.format(**d) def resize_long_edge(im, size):",
"of dictionaries Contains filenames and filepaths. \"\"\" output = [] for dir_, _,",
"with ksize), mask and sum. def BLURRED(curr, prev, threshold, ksize=11, min_area=None): \"\"\"Useful, mid-grade",
"= (i * 10) // timer[0] elapsed = time.time() - timer[1] total =",
"fast. Parameters ---------- curr : numpy.ndarray Image array, typically from cv2.imread(). One of",
"self.plt_vals[\"resp_thresh\"] or curr[\"new_count\"] > self.plt_vals[\"resp_thresh\"]) if i == self.length-1: curr[\"selected\"] = ( curr[\"new_count\"]",
"strfdelta(tdelta, fmt): \"\"\"Formats a timedelta object as a string. Parameters ---------- tdelta :",
"finds the median tone of a grayscale image. \"\"\" px_count = image.shape[0] *",
"cr_corn, cr_ig = safe_corners(crop_RS.geometry) cl_corn, cl_ig = safe_corners(clone_RS.geometry) mod = image.copy() if not",
"but decrease acuity. \"\"\" if not os.path.exists(export_dir): os.makedirs(export_dir) timer = (len(jpg_data) // 10,",
"function, {SIMPLE, BLURRED, COUNTOURS} Determines the frame differencing method to use. Ordered from",
"= str(i) new_name = \"_\".join((dt_ISO, row[\"filename\"])) new_path = os.path.join(directory, new_name) write_row[\"filename\"] = new_name",
"= int(round(xdata)) if i != self.pano_i: self.pano_i = i array = np.array(range(i -",
"d), (e, f, g, h) = clone image[a:b, c:d] = image[e:f, g:h] image",
"numbers decreases sensitivity. \"\"\" difference = cv2.absdiff(curr, prev) blurred = cv2.medianBlur(difference, ksize) _,",
"of tuples Matches the format ((clone_to), (clone_from)). For simplicity, use generate_clone_tuples() to generate",
"[] for (tups, direct) in trials: test = image.copy() (a, b, c, d),",
"Cam objects don\"t need to have data to initialize. # This way, someone",
"if self.press[0] is None: i = int(round(event.xdata)) if event.key == \"z\": self.press =",
"= json.loads(next(f)) temp_dict = json.loads(next(f)) for row in temp_data: if \"datetime\" in row.keys():",
"a string. Parameters ---------- tdelta : datetime.timedelta Timedelta object to format. fmt :",
"self.plt_vals[\"resp_thresh\"]) prev = curr if self.dt_present: for move in (1, -1): is_neg =",
"select images for export. QUICK GUIDE: c - Hold to VIEW IMAGES in",
"image : numpy.ndarray Image array, typically from cv2.imread(). crop : tuple Format is",
"for move in (1, -1): is_neg = move < 0 prev = self.jpg_data[-is_neg]",
"timestamps, aids in histogram equalization. Parameters ---------- clone_to : tuple Format is (y1,",
"curr. The second image to be differenced. threshold : int, in range(0, 256)",
"requires the output of process_jpgs(). Can be omitted if a empty Cam() object",
"FUNCTIONS class Mem(): def __init__(self): pass def rint(n): return round(int(n)) def sort_cols(var_name): if",
"selected images and a .csv file to specified directory. \"\"\" if not os.path.exists(directory):",
"0.08, 0, 100, mod, \"%.2e\"), (\"TRANS\", 0.06, 0, 120, self.plt_vals[\"trans_thresh\"], \"%.1f\"), (\"SMOOTH\", 0.04,",
"two images, then finds their absolute difference. A simple threshold is called, the",
"# Like BLURRED, but only sums drawn contours over given limit. def CONTOURS(curr,",
"np.arange(0, self.length) + 0.5, -BIG_NUM, BIG_NUM, where=[r[\"trans_edit\"] or r[\"user_edit\"] for r in self.jpg_data],",
"\"filename\": filename, \"filepath\": filepath }) return output def attach_exif(jpg_data, parse_tags=DEFAULT_PARSE): \"\"\"Loops through jpg_data,",
"first. thumb_dir : str, optional If the interactive plot is laggy, use resize_with_exif()",
"row[\"new_count\"] = new_count for i, shift in self.user_edits.items(): self.jpg_data[i][\"new_count\"] = shift self.mark_edits(i, \"user_edit\")",
"try: ax.fill_between( np.arange(0, self.length) + 0.5, -BIG_NUM, BIG_NUM, where=extract_var(self.jpg_data, \"is_night\"), facecolor=\"#003459\", alpha=0.5) except",
"= False row[\"trans_edit\"] = False if self.dt_present: self.attach_diffs(\"datetime\", \"timedelta\") for row in self.jpg_data:",
"differenced image is blurred to reduce noise. After thresholding, the resulting white pixels",
"min(a, c), min(b, d) tup = (0, h, 0, w) print(\"FUNCTION ABORTED!\\n\" \"Not",
"prev prev = curr def mark_edits(self, i, kind): \"\"\"Marks which photos to label",
"export(directory) Exports selected images and a .csv file. load(filename) Loads a .sav file.",
"mask. def SIMPLE(curr, prev, threshold, ksize=None, min_area=None): \"\"\"Most basic frame differencing method. Takes",
"user_edits. \"\"\" temp_data = [ {k: v for k, v in row.items()} for",
"directory. img_type : tuple, optional By default, finds JPG image types, but can",
"is retrieved from EXIF data using DEFAULT_PARSE. Examine DEFAULT_PARSE as an example parameter",
"are used for filling the area. Returns ------- pair of tuples Matches the",
"= cl_corn trials = [] for direct in (\"A\", \"B\", \"R\", \"L\"): tups",
"float type. \"\"\" time = datetime.time() return time.hour + time.minute / 60 +",
"slicing images as np.arrays. clone : pair of tuples, optional Matches the format",
"crop_RS.update() if clone_RS.active: clone_RS.update() def safe_corners(geometry): min_y = max(0, min(geometry[0, :])) max_y =",
"Manual user edits are applied. \"\"\" for i, row in enumerate(self.jpg_data): row[\"user_edit\"] =",
"imgs[0] del choose else: mem.clone_tuple = False mem.clone_directs = False if cr_ig: cr_corn",
"\",\": self.press = [0, i] if event.key in \"zxc,\": image_pano(event.xdata) elif event.key ==",
"self.mark_edits(i, \"user_edit\") def update_events(self): \"\"\"Updates jpg_data with new events (runs of detection). An",
"[ {k: v for k, v in row.items()} for row in self.jpg_data] for",
"specified cloning and equalization. Parameters ---------- image : numpy.ndarray Image array, typically from",
"min(W, max(geometry[1, :])) ignore = (min_y > H or max_y < 0 or",
"scale), (W + W // scale) lo_H, hi_H = (0 - H //",
"i: stop_watch(i, timer) from_path = jpg[\"filepath\"] to_path = os.path.join(export_dir, jpg[\"filename\"]) im = cv2.imread(from_path)",
"\"[A]bove,\" \"[B]elow,\" \"[R]ight,\" and \"[L]eft\" are used for filling the area. Returns -------",
"crop={tup}.\") return tup else: print(inst) prev = curr output.append(row) return output def construct_jpg_data(",
"= (0, H, 0, W) mem.crop_tuple = False else: mem.crop_tuple = cr_corn y1,",
"desired for a load() method call. resp_var : str, optional A key found",
"contour area to count as a response (movement). Default is an area of",
"cv2.imread(jpg_data[len(jpg_data) // 2][\"filepath\"])) clone = (generate_clone_tuples(clone_to, directs[0]) if clone_to else False) process_options =",
"Like curr. The second image to be differenced. threshold : int, in range(0,",
"pos, 0.8, 0.02]) self.sliders[name] = Slider( slider_ax, name, minv, maxv, valinit=init, valfmt=fmt, color=\"#003459\",",
"index in night_indices def save(self, filename): \"\"\"Dumps a JSON object with jpg_data, plot_params,",
"differenced image is blurred to reduce noise. After thresholding, contours are drawn around",
"for i in master_set: self.jpg_data[i][\"selected\"] = True def plot(self): \"\"\"Interactive plot used to",
"= ( lapse <= self.plt_vals[\"smooth_time\"]) prev = curr else: nudge = int(self.plt_vals[\"smooth_time\"]) master_set",
"(\"SMOOTH\", 0.04, 0, 10, self.plt_vals[\"smooth_time\"], \"%.1f\"), (\"NIGHT\", 0.02, -1, 50, self.plt_vals[\"night_mult\"], \"%.1f\") ]",
"process_options == {}: print(\"Crop and clone image as desired.\") crop, clone_to, directs =",
"x1, y1 = eclick.xdata, eclick.ydata x2, y2 = erelease.xdata, erelease.ydata cr_corn, cr_ig =",
"\" \"consider using the crop parameter.\\n\" f\"Try crop={tup}.\") return tup else: print(inst) prev",
"min_area : int Minimum contour area to count as a response (movement). Default",
"equalized histogram. Parameters ---------- image : numpy.ndarray Image array, typically from cv2.imread(). crop",
"default, finds JPG image types, but can be changed if camera exports a",
"By default, dictionaries within the jpg_data list are sorted by their \"Image DateTime\"",
"if key == \"resp_thresh\": mod = self.sliders[slider_key].val ** RESP_NUM self.plt_vals[key] = mod self.sliders[slider_key].valtext.set_text(\"%.2e\"",
"simplicity, use generate_clone_tuples() to generate this object. threshold : int, in range(0, 256)",
"with camera-trapping images.\") jpg_paths = find_imgs(input_directory()) jpg_data = attach_exif(jpg_paths) jpg_data.sort(key=lambda x: x[\"datetime\"]) print(\"→",
"images and a .csv file. load(filename) Loads a .sav file. mark_edits(i) Marks which",
"{i: self.press[0] for i in lo_to_hi} self.user_edits = {**self.user_edits, **new_edits} elif event.key ==",
"cv2.waitKey(1) def on_click(event): if event.dblclick and event.xdata is not None: image_pano(event.xdata) def on_key(event):",
"tuples Matches the format for the clone parameter in process_jpgs(). \"\"\" clone_to =",
"is (y1, y2, x1, x2), just like slicing images as np.arrays. \"\"\" y1,",
"\"\\n\") f.write(json.dumps(self.user_edits)) def load(self, filename): \"\"\"Loads a .sav file, the Cam() object is",
"= list(zip(*choose)) mem.clone_directs = directs mod = imgs[0] del choose else: mem.clone_tuple =",
"self.jpg_data: row[\"24hr\"] = to_24_hour(row[\"datetime\"]) row[\"td_minutes\"] = round( row[\"timedelta\"].total_seconds() / 60, 2) day_hr =",
"def attach_diffs(self, var, new_var): \"\"\"Finds the difference between the current and previous variable.",
"image_pano(event.xdata) elif event.key == \"v\": self.toggle = not self.toggle image_pano(event.xdata) elif event.key ==",
"trials = [] for direct in (\"A\", \"B\", \"R\", \"L\"): tups = generate_clone_tuples(cl_corn,",
"import matplotlib.gridspec as gridspec # CONSTANTS BIG_NUM = int(1e9) NEG_NUM = -0.1 RESP_NUM",
"dictionaries Same as jpg_data, but now with desired EXIF data attached. \"\"\" output",
"from cv2.imread(). Returns ------- tuple Format is (crop, clone_to, clone_directs). The crop_tuple variable",
"DEFAULT_PLOT_PARAMS to this attribute. Methods ------- attach_diffs(var, new_var) Finds the difference between the",
"only Image DateTime is retrieved from EXIF data using DEFAULT_PARSE. Examine DEFAULT_PARSE as",
"to lose any prior work. Attributes ---------- jpg_data : list of dictionaries Similar",
"dt_ISO = dt.strftime( row[\"datetime\"], \"%Y%m%dT%H%M%S\" ) else: dt_ISO = str(i) new_name = \"_\".join((dt_ISO,",
"self.plt_vals[key] = self.sliders[slider_key].val update() # Displays last two and next two images from",
"fig.canvas.draw_idle() def on_slide(val): for key in self.plt_vals.keys(): if key != \"ceiling\": slider_key =",
"// 10, time.time()) for i, jpg in enumerate(jpg_data): if not i % timer[0]",
"(1, -1): is_neg = move < 0 prev = self.jpg_data[-is_neg] for i in",
"self.plt_vals[\"ceiling\"]]) ax.set_xlim([0, min(500, self.length)]) ax.set_xlabel(\"Frame\") ax.set_ylabel(\"Response\") plt.yticks(rotation=45) for name in (\"count\", \"threshold\", \"selected\",",
"is not None: row[\"thumbpath\"] = os.path.join(thumb_dir, row[\"filename\"]) else: row[\"thumbpath\"] = row[\"filepath\"] row[\"count\"] =",
"applied. \"\"\" for i, row in enumerate(self.jpg_data): row[\"user_edit\"] = False row[\"trans_edit\"] = False",
"> H or max_y < 0 or min_x > W or max_x <",
"and CONTOURS() functions, but retained here to shorten the process_jpgs() function. min_area :",
"write_row[\"filepath\"] = new_path write_row[\"old_name\"] = row[\"filename\"] write_row[\"old_path\"] = row[\"filepath\"] shutil.copy2(row[\"filepath\"], new_path) write_data.append(write_row) if",
"Returns ------- pair of tuples Matches the format for the clone parameter in",
"= {\"crop\": crop, \"clone\": clone} print(\"Started processing...\") output = process_jpgs(jpg_data, **process_options) print(\"Done!\") return",
"for func in (operator.add, operator.sub): for j in range(nudge+1): ind = func(i, j)",
"in (operator.add, operator.sub): for j in range(nudge+1): ind = func(i, j) try: row",
"for i, shift in self.user_edits.items(): self.jpg_data[i][\"new_count\"] = shift self.mark_edits(i, \"user_edit\") def update_events(self): \"\"\"Updates",
"= CROP_EQUALIZE else: preprocess = CROP_CLONE_EQUALIZE output = [] timer = (len(jpg_data) //",
"to jpg_data. Day to night transitions are filtered out based on slider. Counts",
"and clone parameters. Parameters ---------- image : numpy.ndarray Image array, typically from cv2.imread().",
"new_count for i, shift in self.user_edits.items(): self.jpg_data[i][\"new_count\"] = shift self.mark_edits(i, \"user_edit\") def update_events(self):",
"= jpg_data[0][\"shape\"] self.plt_vals[\"ceiling\"] = h * w * 0.02 self.plt_vals[\"resp_thresh\"] = self.plt_vals[\"ceiling\"] /",
"im = cv2.imread(from_path) resized = resize_long_edge(im, long_edge) cv2.imwrite(to_path, resized) piexif.transplant(from_path, to_path) # SPECIFIC",
"crop) return cv2.equalizeHist(image) def CROP_CLONE_EQUALIZE(image, crop, clone): \"\"\"Returns a cropped image, with specified",
"= ( self.plt_vals[\"resp_thresh\"] ** (1 / RESP_NUM)) temp_data = json.loads(next(f)) temp_dict = json.loads(next(f))",
"time.time()) for i, jpg in enumerate(jpg_data): if not i % timer[0] and i:",
"int(self.plt_vals[\"smooth_time\"]) master_set = set() for i, row in enumerate(self.jpg_data): if row[\"selected\"]: for func",
"through jpg_data, reading filepaths and attaching EXIF data. Parameters ---------- jpg_data : list",
":]) crop_RS = RectangleSelector( ax_crop, RS_event, **RS_PARAMS) clone_RS = RectangleSelector( ax_clone, RS_event, **RS_PARAMS)",
"h, 0, w) print(\"FUNCTION ABORTED!\\n\" \"Not all images are of same size, \"",
"try: row = self.jpg_data[ind] if row[\"new_count\"] < 0: if func == operator.sub: master_set.add(ind)",
"d) tup = (0, h, 0, w) print(\"FUNCTION ABORTED!\\n\" \"Not all images are",
"px_count = image.shape[0] * image.shape[1] hist = cv2.calcHist([image], [0], None, [256], [0, 256])",
"attribute with new events. \"\"\" def __init__(self, jpg_data=False, resp_var=\"count\", thumb_dir=None): \"\"\" Parameters ----------",
"if cr_ig: cr_corn = (0, H, 0, W) mem.crop_tuple = False else: mem.crop_tuple",
"= [np.argmin(kmeans.cluster_centers_), np.argmax(kmeans.cluster_centers_)] for n, index in enumerate(kmeans.labels_): self.jpg_data[n][\"is_night\"] = index in night_indices",
"on slider. Manual user edits are applied. \"\"\" for i, row in enumerate(self.jpg_data):",
"Format is (y1, y2, x1, x2), just like slicing images as np.arrays. \"\"\"",
"images, then finds their absolute difference. A simple threshold is called, the resulting",
"is None: i = int(round(event.xdata)) if event.key == \"z\": self.press = [NEG_NUM, i]",
"str(v).rjust(2, \"0\") return fmt.format(**d) def resize_long_edge(im, size): h, w, *_ = im.shape if",
"prior to this function. export_dir : str Directory path that is used for",
"\") if answer.lower() in (\"y\", \"yes\"): os.makedirs(directory) return directory print(\"Please input a new",
"for exporting thumbnails. long_edge : int, optional By default, images will be resized",
"GENERAL FUNCTIONS class Mem(): def __init__(self): pass def rint(n): return round(int(n)) def sort_cols(var_name):",
"safe_corners(clone_RS.geometry) mod = image.copy() if not cl_ig: mem.clone_tuple = cl_corn trials = []",
"def off_key(event): try: if event.xdata is not None and event.key in \"zx,\": i",
"255, cv2.THRESH_BINARY) return cv2.countNonZero(mask) # Like BLURRED, but only sums drawn contours over",
"object with its initial data. \"\"\" jpg_paths = find_imgs(dirpath) print(f\"{len(jpg_paths)} images found.\") jpg_data",
"be taken. prev : numpy.ndarray Like curr. The second image to be differenced.",
"alpha=0.75, zorder=2) try: ax.fill_between( np.arange(0, self.length) + 0.5, -BIG_NUM, BIG_NUM, where=extract_var(self.jpg_data, \"is_night\"), facecolor=\"#003459\",",
"self.plt_vals[\"ceiling\"] = h * w * 0.02 self.plt_vals[\"resp_thresh\"] = self.plt_vals[\"ceiling\"] / 2 self.attach_diffs(\"median\",",
"new_count is attached to jpg_data. Day to night transitions are filtered out based",
"return '\"' + string + '\"' if \",\" in string else string def",
"parse_tags: row[var] = anon(tags[key][tag]) output.append(row) return output def hist_median(image): \"\"\"Quickly finds the median",
"scale = 10 lo_W, hi_W = (0 - W // scale), (W +",
"the plot() method. To reset these values, re- assign DEFAULT_PLOT_PARAMS to this attribute.",
"dictionaries Contains filenames and filepaths. \"\"\" output = [] for dir_, _, files",
"elapsed), \"{days}:{hours}:{minutes}:{seconds}\") print(f\"{progress}% done. {remain} left.\") def strfdelta(tdelta, fmt): \"\"\"Formats a timedelta object",
"plot used to select images for export. save(filename) Dumps a JSON object as",
"- Hold and release to DECREASE response value to 0. , - Hold",
"to RESET ALL EDITS. v - Press for EQUALIZED image (for dark images).",
"\"Not all images are of same size, \" \"consider using the crop parameter.\\n\"",
"= self.buffer[1][ind] self.buffer[0].append(self.buffer[0].pop(ind)) self.buffer[1].append(self.buffer[1].pop(ind)) else: img = cv2.imread(self.jpg_data[n][\"thumbpath\"]) self.buffer[0] = self.buffer[0][1:] + [n]",
"the image. Smaller sizes speed up performance, but decrease acuity. \"\"\" if not",
"timer) jpg = cv2.imread(row[\"filepath\"], 0) curr = preprocess(jpg, crop, clone) row[\"shape\"] = jpg.shape",
"os.path.expanduser(\"~\") # Cam objects don\"t need to have data to initialize. # This",
"to overwrite it?\") answer = input(\"Y / N > \") if answer.lower() in",
"found.\") jpg_data = attach_exif(jpg_paths, parse_tags) jpg_data.sort(key=sort_key) if process_options == {}: print(\"Crop and clone",
"list of dictionaries, optional Typically requires the output of process_jpgs(). Can be omitted",
"cv2.contourArea(cnt) if area > min_area: count += area return count # JPG PROCESSING",
"functions, but retained here to shorten the process_jpgs() function. min_area : int, unused",
"last step before the jpg_data list can be fed into the Cam() class",
"+ \"\\n\") f.write(json.dumps(temp_data) + \"\\n\") f.write(json.dumps(self.user_edits)) def load(self, filename): \"\"\"Loads a .sav file,",
"tone of a grayscale image. \"\"\" px_count = image.shape[0] * image.shape[1] hist =",
"clone_to h, w = b - a, d - c h_or_w = np.array([h,",
"range(0, 256) Parameter to be passed to the cv2.threshold() function. ksize : int,",
"= cr_corn mod = mod[y1:y2, x1:x2] mod = cv2.cvtColor(mod, cv2.COLOR_BGR2RGB) ax_mod.imshow(mod) fig.canvas.draw_idle() rgb",
"the resulting white pixels are counted toward response (movement). Very noisy, but fast.",
"prior work. Attributes ---------- jpg_data : list of dictionaries Similar to what is",
"timer) from_path = jpg[\"filepath\"] to_path = os.path.join(export_dir, jpg[\"filename\"]) im = cv2.imread(from_path) resized =",
"and event.xdata is not None: image_pano(event.xdata) def on_key(event): if event.xdata is not None:",
"{\"A\", \"B\", \"R\", \"L\"} Calls directional tuples from DIRECTION_MULTS to fill pixels within",
"exporting, parameters for graphing, and plot function. class Cam(): \"\"\" A class used",
"\"count\", \"new_count\", \"selected\", \"user_edit\", \"trans_edit\" ] RS_PARAMS = { \"drawtype\": \"box\", \"useblit\": True,",
"\"L\"} Calls directional tuples from DIRECTION_MULTS to fill pixels within the clone_to area.",
"self.update_counts() self.update_events() draw() def draw(): for name in self.lines.keys(): self.lines[name].remove() np_counts = np.array(extract_var(self.jpg_data,",
"except KeyError: pass on_slide(1) plt.show() cv2.destroyAllWindows() if __name__ == \"__main__\": print(\"→ Please input",
"= (not curr[\"selected\"] and prev[\"selected\"] and not (prev[\"user_edit\"] and curr[\"user_edit\"])) if boo: if",
"absolute difference. Prior to thresholding, the differenced image is blurred to reduce noise.",
"parser for EXIF \"Image DateTime\" tag. \"\"\" str_ = ''.join(x for x in",
"import piexif import numpy as np from sklearn.cluster import KMeans from datetime import",
"in range(nudge+1): ind = func(i, j) try: row = self.jpg_data[ind] if row[\"new_count\"] <",
"commas in them. \"\"\" string = str(obj) return '\"' + string + '\"'",
"RS_event(eclick, erelease): x1, y1 = eclick.xdata, eclick.ydata x2, y2 = erelease.xdata, erelease.ydata cr_corn,",
"index in enumerate(kmeans.labels_): self.jpg_data[n][\"is_night\"] = index in night_indices def save(self, filename): \"\"\"Dumps a",
"= ''.join(x for x in str(raw) if x in string.digits) return dt.strptime(str_, \"%Y%m%d%H%M%S\")",
"Larger numbers decreases sensitivity. \"\"\" difference = cv2.absdiff(curr, prev) blurred = cv2.medianBlur(difference, ksize)",
"not thresh_init: threshold = row[\"median\"]*1.05 try: row[\"count\"] = method(curr, prev, threshold, ksize, min_area)",
"clone_to else False) process_options = {\"crop\": crop, \"clone\": clone} print(\"Started processing...\") output =",
"if func == operator.sub: master_set.add(ind) break else: master_set.add(ind) except IndexError: pass for i",
"direction in the directs list (all have been checked for bounds, unlike generate_clone_tuples).",
"(e, f, g, h) = clone image[a:b, c:d] = image[e:f, g:h] image =",
"threshold = px_count / 2 for i, count in enumerate(hist): tally += count",
"= cv2.imread(self.jpg_data[n][\"thumbpath\"]) self.buffer[0] = self.buffer[0][1:] + [n] self.buffer[1] = self.buffer[1][1:] + [img] if",
"prev[\"selected\"] and not (prev[\"user_edit\"] and curr[\"user_edit\"])) if boo: if not is_neg: lapse =",
"master_set: self.jpg_data[i][\"selected\"] = True def plot(self): \"\"\"Interactive plot used to select images for",
"= find_imgs(dirpath) print(f\"{len(jpg_paths)} images found.\") jpg_data = attach_exif(jpg_paths, parse_tags) jpg_data.sort(key=sort_key) if process_options ==",
"as edited based on [i]ndex. \"\"\" if i == 0: self.jpg_data[i][kind] = True",
"else: nudge = int(self.plt_vals[\"smooth_time\"]) master_set = set() for i, row in enumerate(self.jpg_data): if",
"or d > W): trials.append((tups, direct)) choose = [] for (tups, direct) in",
"images. Works hierarchically to preform image cropping, cloning, and histogram equalization on images",
"cloning and equalization. Parameters ---------- image : numpy.ndarray Image array, typically from cv2.imread().",
"find_imgs(dirpath) print(f\"{len(jpg_paths)} images found.\") jpg_data = attach_exif(jpg_paths, parse_tags) jpg_data.sort(key=sort_key) if process_options == {}:",
"output def hist_median(image): \"\"\"Quickly finds the median tone of a grayscale image. \"\"\"",
"that \"filepath\" is in dictionary keys, which is easily provided by find_imgs() prior",
"self.length)]) ax.set_xlabel(\"Frame\") ax.set_ylabel(\"Response\") plt.yticks(rotation=45) for name in (\"count\", \"threshold\", \"selected\", \"edited\"): self.lines[name] =",
"a, b, c, d = tups[1] if not (a < 0 or b",
"for the absolute difference to be taken. prev : numpy.ndarray Like curr. The",
"24 hour float type. \"\"\" time = datetime.time() return time.hour + time.minute /",
"not is_neg: lapse = curr[\"td_minutes\"] else: lapse = prev[\"td_minutes\"] curr[\"selected\"] = ( lapse",
"directory. \"\"\" if not os.path.exists(directory): os.makedirs(directory) write_data = [] for i, row in",
"crop, \"clone\": clone} print(\"Started processing...\") output = process_jpgs(jpg_data, **process_options) print(\"Done!\") return output #",
"!= \"ceiling\": slider_key = key[:key.find(\"_\")].upper() if key == \"resp_thresh\": mod = self.sliders[slider_key].val **",
"function, but retained here to shorten the process_jpgs() function. \"\"\" difference = cv2.absdiff(curr,",
"format ((clone_to), (clone_from)). For simplicity, use generate_clone_tuples() to generate this object. \"\"\" (a,",
"100 pixels. Larger numbers decreases sensitivity. \"\"\" difference = cv2.absdiff(curr, prev) blurred =",
"Counts taken at with nighttime are multiplied based on slider. Manual user edits",
"with new events (runs of detection). An event is a contiguous sequence of",
"stack = [] for n in array: if n in self.buffer[0]: ind =",
"= { \"A\": (-1, -1, 0, 0), \"B\": (1, 1, 0, 0), \"R\":",
"of values corresponding to a variable name. >>> foo = [{\"name\": \"Shane\", \"age\":",
"round( row[\"timedelta\"].total_seconds() / 60, 2) day_hr = extract_var(self.jpg_data, \"24hr\") # meds = extract_var(self.jpg_data,",
"curr[\"user_edit\"])) if boo: if not is_neg: lapse = curr[\"td_minutes\"] else: lapse = prev[\"td_minutes\"]",
"Displays last two and next two images from response spike. def image_pano(xdata): i",
"row[self.resp_var] row[\"med_diff\"] = abs(row[\"med_diff\"]) row[\"selected\"] = False row[\"user_edit\"] = False row[\"trans_edit\"] = False",
"for k, v in row.items()} for row in self.jpg_data] for row in temp_data:",
"in master_set: self.jpg_data[i][\"selected\"] = True def plot(self): \"\"\"Interactive plot used to select images",
"in img_type. Parameters ---------- dirpath : str Path to an image-containing directory. img_type",
"enumerate(jpg_data): if not i % timer[0] and i: stop_watch(i, timer) from_path = jpg[\"filepath\"]",
"np.arange(0, self.length) + 0.5, -BIG_NUM, BIG_NUM, where=extract_var(self.jpg_data, \"selected\"), facecolor=\"#F00314\") self.lines[\"count\"] = ax.fill_between( range(self.length),",
"filename): \"\"\"Dumps a JSON object with jpg_data, plot_params, and user_edits. \"\"\" temp_data =",
"scale = size / w else: scale = size / h new_w =",
"i, deep_row in enumerate(jpg_data): row = deep_row.copy() if i == 0: jpg =",
"if a empty Cam() object is desired for a load() method call. resp_var",
"shorten the process_jpgs() function. min_area : int, unused Only used in the CONTOURS()",
"---------- jpg_data : list of dictionaries, optional Typically requires the output of process_jpgs().",
"and sum the mask. def SIMPLE(curr, prev, threshold, ksize=None, min_area=None): \"\"\"Most basic frame",
"self.jpg_data[-is_neg] for i in range(-is_neg, (self.length * move) - is_neg, move): curr =",
"0: stop_watch(i, timer) jpg = cv2.imread(row[\"filepath\"], 0) curr = preprocess(jpg, crop, clone) row[\"shape\"]",
"safe_corners(crop_RS.geometry) cl_corn, cl_ig = safe_corners(clone_RS.geometry) mod = image.copy() if not cl_ig: mem.clone_tuple =",
"event.key == \",\": self.press = [0, i] if event.key in \"zxc,\": image_pano(event.xdata) elif",
"in (\"y\", \"yes\"): os.makedirs(directory) return directory print(\"Please input a new directory path.\") def",
"x1:x2] def CROP_EQUALIZE(image, crop, clone=None): \"\"\"Returns a cropped image with an equalized histogram.",
"= False mem.clone_directs = False def update(event): if crop_RS.active: crop_RS.update() if clone_RS.active: clone_RS.update()",
"/ (progress / 100) remain = strfdelta(td(seconds=total - elapsed), \"{days}:{hours}:{minutes}:{seconds}\") print(f\"{progress}% done. {remain}",
"---------- jpg_data : list of dictionaries Similar to what is inputted, but includes",
"the Cam() object is now identical to the last. \"\"\" with open(filename, \"r\")",
"response filtering. Parameters ---------- jpg_data : list of dictionaries Requires that \"filepath\" is",
": {\"A\", \"B\", \"R\", \"L\"} Calls directional tuples from DIRECTION_MULTS to fill pixels",
"mod = imgs[0] del choose else: mem.clone_tuple = False mem.clone_directs = False if",
"method. To reset these values, re- assign DEFAULT_PLOT_PARAMS to this attribute. Methods -------",
"load(self, filename): \"\"\"Loads a .sav file, the Cam() object is now identical to",
"AttributeError: pass if \"selected\" in row.keys(): row[\"selected\"] = bool(row[\"selected\"]) self.jpg_data = temp_data.copy() self.length",
"(prev[\"user_edit\"] and curr[\"user_edit\"])) if boo: if not is_neg: lapse = curr[\"td_minutes\"] else: lapse",
"[{\"name\": \"Shane\", \"age\": 22}, {\"name\": \"Eve\", \"age\": 7}] >>> extract_var(data=foo, var=\"name\") [\"Shane\", \"Eve\"]",
"master_set = set() for i, row in enumerate(self.jpg_data): if row[\"selected\"]: for func in",
"import time import cv2 import piexif import numpy as np from sklearn.cluster import",
"equalization. Parameters ---------- image : numpy.ndarray Image array, typically from cv2.imread(). crop :",
"if self.dt_present: for move in (1, -1): is_neg = move < 0 prev",
"\"\"\" (a, b, c, d), (e, f, g, h) = clone image[a:b, c:d]",
"and event.key in \"zx,\": i = int(round(event.xdata)) low, high = sorted((self.press[1], i)) lo_to_hi",
"d) = curr.shape[:2], prev.shape[:2] h, w = min(a, c), min(b, d) tup =",
"response spike. def image_pano(xdata): i = int(round(xdata)) if i != self.pano_i: self.pano_i =",
"get crop and clone parameters. Parameters ---------- image : numpy.ndarray Image array, typically",
"raise inst mod = self.plt_vals[\"resp_thresh\"] ** (1 / RESP_NUM) SLIDER_PARAMS = [ (\"RESP\",",
"to quickly get crop and clone parameters. Parameters ---------- image : numpy.ndarray Image",
"\"\"\"Quickly finds the median tone of a grayscale image. \"\"\" px_count = image.shape[0]",
"and next two images from response spike. def image_pano(xdata): i = int(round(xdata)) if",
"f\"Try crop={tup}.\") return tup else: print(inst) prev = curr output.append(row) return output def",
"gridspec # CONSTANTS BIG_NUM = int(1e9) NEG_NUM = -0.1 RESP_NUM = 3.5 def",
"\"yes\"): os.makedirs(directory) return directory print(\"Please input a new directory path.\") def csv_safe(obj): \"\"\"Puts",
"absolute difference to be taken. prev : numpy.ndarray Like curr. The second image",
": function, optional By default, dictionaries within the jpg_data list are sorted by",
"- is_neg, move): curr = self.jpg_data[i] boo = (not curr[\"selected\"] and prev[\"selected\"] and",
"< 0) return tuple(map( lambda x: int(round(x)), (min_y, max_y, min_x, max_x))), ignore def",
"timedelta as td from matplotlib import pyplot as plt from matplotlib.widgets import Slider,",
"DEFAULT_PLOT_PARAMS = { \"ceiling\": 40000, \"resp_thresh\": 20000, \"trans_thresh\": 30, \"smooth_time\": 1, \"night_mult\": 0",
"pixels are counted toward response (movement). Very noisy, but fast. Parameters ---------- curr",
"fig.canvas.set_window_title(\"Response Filtering\") fig.subplots_adjust(0.07, 0.18, 0.97, 0.97) ax.grid(alpha=0.4) ax.set_axisbelow(True) ax.set_ylim([0, self.plt_vals[\"ceiling\"]]) ax.set_xlim([0, min(500, self.length)])",
"ending in img_type. Parameters ---------- dirpath : str Path to an image-containing directory.",
"= sorted((self.press[1], i)) lo_to_hi = range(max(0, low), min(self.length, high+1)) if event.key in \"zx\":",
"plt.connect(\"draw_event\", update) plt.show() return mem.crop_tuple, mem.clone_tuple, mem.clone_directs # FRAME DIFFERENCING METHODS # Bare-bones.",
"= rint(w * scale) new_h = rint(h * scale) return cv2.resize(im, (new_w, new_h))",
"label as edited based on [i]ndex. \"\"\" if i == 0: self.jpg_data[i][kind] =",
"timedelta object as a string. Parameters ---------- tdelta : datetime.timedelta Timedelta object to",
"(i * 10) // timer[0] elapsed = time.time() - timer[1] total = elapsed",
"processed data. if jpg_data: self.jpg_data = list(jpg_data) self.length = len(self.jpg_data) self.dt_present = \"datetime\"",
"crop, clone=None): \"\"\"Returns a cropped image with an equalized histogram. Parameters ---------- image",
"def save(self, filename): \"\"\"Dumps a JSON object with jpg_data, plot_params, and user_edits. \"\"\"",
"row[\"filename\"] write_row[\"old_path\"] = row[\"filepath\"] shutil.copy2(row[\"filepath\"], new_path) write_data.append(write_row) if write_data: with open(os.path.join(directory, \"_export.csv\"), \"w\")",
"path that is used for exporting thumbnails. long_edge : int, optional By default,",
"plt.show() return mem.crop_tuple, mem.clone_tuple, mem.clone_directs # FRAME DIFFERENCING METHODS # Bare-bones. Take difference,",
"row[\"timedelta\"] = row[\"timedelta\"].total_seconds() if \"selected\" in row.keys(): row[\"selected\"] = int(row[\"selected\"]) with open(filename, \"w\")",
"max_x))), ignore def RS_event(eclick, erelease): x1, y1 = eclick.xdata, eclick.ydata x2, y2 =",
"\"selected\", \"user_edit\", \"trans_edit\" ] RS_PARAMS = { \"drawtype\": \"box\", \"useblit\": True, \"button\": [1,",
"to an image-containing directory. parse_tags : list of tuples, optional By default, only",
"== \",\": for i in lo_to_hi: self.user_edits.pop(i, None) self.press = [None, None] update()",
"image-containing directory. img_type : tuple, optional By default, finds JPG image types, but",
"object. \"\"\" image = CROPPER(image, crop) return cv2.equalizeHist(image) def CROP_CLONE_EQUALIZE(image, crop, clone): \"\"\"Returns",
"(ax_crop, ax_clone): axe.set_xticklabels([]) axe.set_yticklabels([]) axe.set_xlim(lo_W, hi_W) axe.set_ylim(hi_H, lo_H) ax_crop.imshow(rgb) ax_clone.imshow(rgb) ax_mod.imshow(rgb) plt.connect(\"draw_event\", update)",
"deep_row.copy() tags = piexif.load(row[\"filepath\"]) for (key, tag), var, anon in parse_tags: row[var] =",
"b, c, d = clone_to h, w = b - a, d -",
"ksize) _, mask = cv2.threshold( blurred, threshold, 255, cv2.THRESH_BINARY) contours, _ = cv2.findContours(",
"in str(raw) if x in string.digits) return dt.strptime(str_, \"%Y%m%d%H%M%S\") def SORT_BY_DT(row): \"\"\"Default sort",
"\"minspany\": 5, \"spancoords\": \"pixels\", \"interactive\": True } # GENERAL FUNCTIONS class Mem(): def",
"jpg_data attribute with new events. \"\"\" def __init__(self, jpg_data=False, resp_var=\"count\", thumb_dir=None): \"\"\" Parameters",
"events. \"\"\" def __init__(self, jpg_data=False, resp_var=\"count\", thumb_dir=None): \"\"\" Parameters ---------- jpg_data : list",
"difference. Prior to thresholding, the differenced image is blurred to reduce noise. After",
"g:h] image = CROPPER(image, crop) return cv2.equalizeHist(image) def crop_clone_preview(image): \"\"\"Interactive viewer to quickly",
"for the clone parameter in process_jpgs(). \"\"\" clone_to = np.array(clone_to) mults = np.array(DIRECTION_MULTS[fill_from[0].upper()])",
"to feed a Cam() object with its initial data. \"\"\" jpg_paths = find_imgs(dirpath)",
"dictionaries Requires that \"filepath\" and \"filename\" is in dictionary keys, which is easily",
"sensitivity. \"\"\" difference = cv2.absdiff(curr, prev) blurred = cv2.medianBlur(difference, ksize) _, mask =",
"For simplicity, use generate_clone_tuples() to generate this object. \"\"\" (a, b, c, d),",
"to Inf. z - Hold and release to DECREASE response value to 0.",
"str(raw) if x in string.digits) return dt.strptime(str_, \"%Y%m%d%H%M%S\") def SORT_BY_DT(row): \"\"\"Default sort for",
"differencing method. Takes two images, then finds their absolute difference. A simple threshold",
"(movement). Works decently, a little faster than COUNTOURS. Parameters ---------- curr : numpy.ndarray",
"i in lo_to_hi: self.user_edits.pop(i, None) self.press = [None, None] update() except TypeError: pass",
"choose = [] for (tups, direct) in trials: test = image.copy() (a, b,",
"ksize=None, min_area=None): \"\"\"Most basic frame differencing method. Takes two images, then finds their",
"a Cam() object with its initial data. \"\"\" jpg_paths = find_imgs(dirpath) print(f\"{len(jpg_paths)} images",
"foo = [{\"name\": \"Shane\", \"age\": 22}, {\"name\": \"Eve\", \"age\": 7}] >>> extract_var(data=foo, var=\"name\")",
"1 + ( self.plt_vals[\"night_mult\"] * row[\"is_night\"]) row[\"new_count\"] = new_count for i, shift in",
"def CROP_CLONE_EQUALIZE(image, crop, clone): \"\"\"Returns a cropped image, with specified cloning and equalization.",
"while True: filename = input(\"FILEPATH > \") if os.path.exists(filename): print(\"File already exists, would",
"scale), (H + H // scale) gs = gridspec.GridSpec(2, 2, height_ratios=[1, 1.25]) fig",
"import string import sys import time import cv2 import piexif import numpy as",
"return mem.crop_tuple, mem.clone_tuple, mem.clone_directs # FRAME DIFFERENCING METHODS # Bare-bones. Take difference, threshold,",
"or max_x < 0) return tuple(map( lambda x: int(round(x)), (min_y, max_y, min_x, max_x))),",
"int Minimum contour area to count as a response (movement). Default is an",
"(all have been checked for bounds, unlike generate_clone_tuples). \"\"\" mem = Mem() mem.crop_tuple",
"h) = clone image[a:b, c:d] = image[e:f, g:h] image = CROPPER(image, crop) return",
"IndexError: pass for i in master_set: self.jpg_data[i][\"selected\"] = True def plot(self): \"\"\"Interactive plot",
"+ [n] self.buffer[1] = self.buffer[1][1:] + [img] if self.toggle: gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)",
"RectangleSelector( ax_crop, RS_event, **RS_PARAMS) clone_RS = RectangleSelector( ax_clone, RS_event, **RS_PARAMS) ax_crop.set_title(\"Crop\") ax_clone.set_title(\"Clone\") ax_mod.set_title(\"Result\")",
"rint(n): return round(int(n)) def sort_cols(var_name): if var_name in COL_ORDER: return COL_ORDER.index(var_name) else: return",
"for export.\") def attach_diffs(self, var, new_var): \"\"\"Finds the difference between the current and",
"< 0: if func == operator.sub: master_set.add(ind) break else: master_set.add(ind) except IndexError: pass",
"save.\") cam.save(input_filename()) print(\"→ Use the interactive plot to select images for export.\") help(Cam.plot)",
"if row[\"new_count\"] < 0: if func == operator.sub: master_set.add(ind) break else: master_set.add(ind) except",
"= resp_var self.plt_vals = DEFAULT_PLOT_PARAMS self.lines = {} self.sliders = {} self.user_edits =",
"== 0: jpg = cv2.imread(row[\"filepath\"], 0) h, w = jpg.shape if not crop:",
"save(self, filename): \"\"\"Dumps a JSON object with jpg_data, plot_params, and user_edits. \"\"\" temp_data",
"filling the area. Returns ------- pair of tuples Matches the format for the",
"prior to this function. method : function, {SIMPLE, BLURRED, COUNTOURS} Determines the frame",
"output # THE MEAT AND POTATOES # Requires data from process_jpg(). Object essentially",
"np.array(extract_var(self.jpg_data, \"new_count\")) self.lines[\"edited\"] = ax.fill_between( np.arange(0, self.length) + 0.5, -BIG_NUM, BIG_NUM, where=[r[\"trans_edit\"] or",
"then finds their absolute difference. Prior to thresholding, the differenced image is blurred",
"if answer.lower() in (\"y\", \"yes\"): return filename elif filename: return filename def input_directory():",
"self.plt_vals[\"resp_thresh\"]) if i == self.length-1: curr[\"selected\"] = ( curr[\"new_count\"] > self.plt_vals[\"resp_thresh\"]) prev =",
"False def update(event): if crop_RS.active: crop_RS.update() if clone_RS.active: clone_RS.update() def safe_corners(geometry): min_y =",
"piexif.transplant(from_path, to_path) # SPECIFIC FUNCTIONS def find_imgs(dirpath, img_type=(\".jpg\", \".jpeg\")): \"\"\"Walks directory path, finding",
"0: if func == operator.sub: master_set.add(ind) break else: master_set.add(ind) except IndexError: pass for",
"for (key, tag), var, anon in parse_tags: row[var] = anon(tags[key][tag]) output.append(row) return output",
"Timedelta object to format. fmt : str Contains format calls to days, hours,",
"a variable for sequence. process_options : dictionary, optional Passes along paramters to the",
"= [] for n in array: if n in self.buffer[0]: ind = self.buffer[0].index(n)",
"JSON object as a .sav file. update_counts() Updates jpg_data attribute with new counts.",
"fill_from : {\"A\", \"B\", \"R\", \"L\"} Calls directional tuples from DIRECTION_MULTS to fill",
"to pass to attach_exif(), if more data is desired from EXIF tags. Returns",
"= crop return image[y1:y2, x1:x2] def CROP_EQUALIZE(image, crop, clone=None): \"\"\"Returns a cropped image",
"of the two images for the absolute difference to be taken. prev :",
"the process_jpgs() function. \"\"\" difference = cv2.absdiff(curr, prev) _, mask = cv2.threshold( difference,",
"select images for export.\") help(Cam.plot) cam.plot() print(\"→ Save once again, so changes are",
"11. Must be positive, odd number. min_area : int Minimum contour area to",
"img_type=(\".jpg\", \".jpeg\")): \"\"\"Walks directory path, finding all files ending in img_type. Parameters ----------",
"process_jpgs(jpg_data, **process_options) print(\"Done!\") return output # THE MEAT AND POTATOES # Requires data",
"self.jpg_data[0] for i, curr in enumerate(self.jpg_data): prev[\"selected\"] = ( prev[\"new_count\"] > self.plt_vals[\"resp_thresh\"] or",
"min(geometry[1, :])) max_x = min(W, max(geometry[1, :])) ignore = (min_y > H or",
"typically from cv2.imread(). Returns ------- tuple Format is (crop, clone_to, clone_directs). The crop_tuple",
"\"median\", \"med_diff\", \"count\", \"new_count\", \"selected\", \"user_edit\", \"trans_edit\" ] RS_PARAMS = { \"drawtype\": \"box\",",
"for export. QUICK GUIDE: c - Hold to VIEW IMAGES in gallery. x",
"in the BLURRED() and CONTOURS() functions, but retained here to shorten the process_jpgs()",
"and release to INCREASE response value to Inf. z - Hold and release",
"empty Cam() object is desired for a load() method call. resp_var : str,",
"stop_watch(i, timer) jpg = cv2.imread(row[\"filepath\"], 0) curr = preprocess(jpg, crop, clone) row[\"shape\"] =",
"QUICK GUIDE: c - Hold to VIEW IMAGES in gallery. x - Hold",
"Finds the difference between the current and previous items. export(directory) Exports selected images",
"more data is desired from EXIF tags. Returns ------- list of dictionaries Same",
"jpg_data : list of dictionaries Requires that \"filepath\" and \"filename\" is in dictionary",
"* image.shape[1] hist = cv2.calcHist([image], [0], None, [256], [0, 256]) tally = 0",
"image tone and a count variable, which respresents how many pixels have changed",
"= False if self.dt_present: self.attach_diffs(\"datetime\", \"timedelta\") for row in self.jpg_data: row[\"24hr\"] = to_24_hour(row[\"datetime\"])",
"Make sure that this parameter is mappable. Returns ------- list of dictionaries Each",
"( lapse <= self.plt_vals[\"smooth_time\"]) prev = curr else: nudge = int(self.plt_vals[\"smooth_time\"]) master_set =",
"self.lines[\"count\"] = ax.fill_between( range(self.length), 0, np_counts, facecolor=\"black\") self.lines[\"threshold\"] = ax.axhline( self.plt_vals[\"resp_thresh\"], color=\"#14B37D\") fig.canvas.draw_idle()",
"elif event.key == \"v\": self.toggle = not self.toggle image_pano(event.xdata) elif event.key == \".\":",
"tuple Format is (y1, y2, x1, x2), just like slicing images as np.arrays.",
"cv2.imread(jpg_data[len(jpg_data) // 2][\"filepath\"])) clone = generate_clone_tuples(clone_to, directs[0]) if clone_to else False print(\"→ Images",
"default, images will be resized to 1024 pixels on the long edge of",
"W) mem.crop_tuple = False else: mem.crop_tuple = cr_corn y1, y2, x1, x2 =",
"response value to 0. , - Hold and release to REMOVE EDITS. .",
"def generate_thumbnails(jpg_data, export_dir, long_edge=1024): \"\"\"Formats a timedelta object as a string. Parameters ----------",
"= 0 for cnt in contours: area = cv2.contourArea(cnt) if area > min_area:",
"this parameter is mappable. Returns ------- list of dictionaries Each row contains everything",
"a datetime, but do have a variable for sequence. process_options : dictionary, optional",
"an area of 100 pixels. Larger numbers decreases sensitivity. \"\"\" difference = cv2.absdiff(curr,",
"(W + W // scale) lo_H, hi_H = (0 - H // scale),",
"Methods ------- attach_diffs(var, new_var) Finds the difference between the current and previous items.",
"alternatives like \"median\" can be used to plot jpgs without processing them first.",
"\"R\", \"L\"} Calls directional tuples from DIRECTION_MULTS to fill pixels within the clone_to",
"desired from EXIF tags. Returns ------- list of dictionaries Same as jpg_data, but",
"w]) clone_from = clone_to + (h_or_w * mults) return (tuple(clone_to), tuple(clone_from)) # IMAGE",
"direct) in trials: test = image.copy() (a, b, c, d), (e, f, g,",
"(0, H, 0, W) mem.crop_tuple = False else: mem.crop_tuple = cr_corn y1, y2,",
"threshold=False, ksize=11, min_area=100 ): \"\"\"Generates a response (movement) metric between images. Works hierarchically",
"row[\"datetime\"], \"%Y-%m-%d %H:%M:%S\") if \"timedelta\" in row.keys(): row[\"timedelta\"] = row[\"timedelta\"].total_seconds() if \"selected\" in",
"print(\"→ Please input a directory path with camera-trapping images.\") jpg_paths = find_imgs(input_directory()) jpg_data",
"self.resp_var = resp_var self.plt_vals = DEFAULT_PLOT_PARAMS self.lines = {} self.sliders = {} self.user_edits",
"selected for export.\") def attach_diffs(self, var, new_var): \"\"\"Finds the difference between the current",
"(0 - H // scale), (H + H // scale) gs = gridspec.GridSpec(2,",
"print(\"FUNCTION ABORTED!\\n\" \"Not all images are of same size, \" \"consider using the",
"if event.key in \"zxc,\": image_pano(event.xdata) elif event.key == \"v\": self.toggle = not self.toggle",
"Bare-bones. Take difference, threshold, and sum the mask. def SIMPLE(curr, prev, threshold, ksize=None,",
"if not cl_ig: mem.clone_tuple = cl_corn trials = [] for direct in (\"A\",",
"a little faster than COUNTOURS. Parameters ---------- curr : numpy.ndarray Image array, typically",
"0, W) mem.crop_tuple = False else: mem.crop_tuple = cr_corn y1, y2, x1, x2",
"again, so changes are recorded.\") cam.save(input_filename()) print(\"→ Finally, choose a location for export.\")",
"and a .csv file to specified directory. \"\"\" if not os.path.exists(directory): os.makedirs(directory) write_data",
"im.shape if w > h: scale = size / w else: scale =",
"direct) a, b, c, d = tups[1] if not (a < 0 or",
"= erelease.xdata, erelease.ydata cr_corn, cr_ig = safe_corners(crop_RS.geometry) cl_corn, cl_ig = safe_corners(clone_RS.geometry) mod =",
"3600 def extract_var(data, var): \"\"\"Returns a list of values corresponding to a variable",
"\"\"\" if not threshold: thresh_init = False if not clone: preprocess = CROP_EQUALIZE",
"else False) process_options = {\"crop\": crop, \"clone\": clone} print(\"Started processing...\") output = process_jpgs(jpg_data,",
"the resulting white pixels. If the contours are above the min_area parameter, they",
"from sklearn.cluster import KMeans from datetime import datetime as dt, timedelta as td",
"mod = mod[y1:y2, x1:x2] mod = cv2.cvtColor(mod, cv2.COLOR_BGR2RGB) ax_mod.imshow(mod) fig.canvas.draw_idle() rgb = cv2.cvtColor(image,",
"valfmt=fmt, color=\"#003459\", alpha=0.5) self.sliders[name].on_changed(on_slide) fig.canvas.mpl_connect(\"key_press_event\", on_key) fig.canvas.mpl_connect(\"key_release_event\", off_key) fig.canvas.mpl_connect(\"button_press_event\", on_click) ax.fill_between( np.arange(0, self.length)",
"EDITS. v - Press for EQUALIZED image (for dark images). \"\"\" try: self.jpg_data",
"min_x > W or max_x < 0) return tuple(map( lambda x: int(round(x)), (min_y,",
"= [[None] * 64, [None] * 64] self.recent_folder = os.path.expanduser(\"~\") # Cam objects",
"direct in (\"A\", \"B\", \"R\", \"L\"): tups = generate_clone_tuples(cl_corn, direct) a, b, c,",
"\"\"\" y1, y2, x1, x2 = crop return image[y1:y2, x1:x2] def CROP_EQUALIZE(image, crop,",
"self.dt_present = \"datetime\" in self.jpg_data[0].keys() h, w = jpg_data[0][\"shape\"] self.plt_vals[\"ceiling\"] = h *",
"json.loads(next(f)) temp_dict = json.loads(next(f)) for row in temp_data: if \"datetime\" in row.keys(): row[\"datetime\"]",
"like \"median\" can be used to plot jpgs without processing them first. thumb_dir",
"the interactive plot() method. A simply initialization could be: Cam(construct_jpg_data()). After filtering images",
"\"datetime\" in row.keys(): row[\"datetime\"] = dt.strptime( row[\"datetime\"], \"%Y-%m-%d %H:%M:%S\" ) self.dt_present = True",
"write_data: with open(os.path.join(directory, \"_export.csv\"), \"w\") as f: variables = sorted(write_data[0].keys(), key=sort_cols) for i,",
"curr[\"td_minutes\"] else: lapse = prev[\"td_minutes\"] curr[\"selected\"] = ( lapse <= self.plt_vals[\"smooth_time\"]) prev =",
"and sum. def BLURRED(curr, prev, threshold, ksize=11, min_area=None): \"\"\"Useful, mid-grade frame differencing method.",
"= min(H, max(geometry[0, :])) min_x = max(0, min(geometry[1, :])) max_x = min(W, max(geometry[1,",
"a file path for an initial save.\") cam.save(input_filename()) print(\"→ Use the interactive plot",
"return dt.strptime(str_, \"%Y%m%d%H%M%S\") def SORT_BY_DT(row): \"\"\"Default sort for construct_jpg_data(). \"\"\" return row[\"datetime\"] DEFAULT_PARSE",
"\"useblit\": True, \"button\": [1, 3], \"minspanx\": 5, \"minspany\": 5, \"spancoords\": \"pixels\", \"interactive\": True",
"= 3.5 def PARSE_DT(raw): \"\"\"Default parser for EXIF \"Image DateTime\" tag. \"\"\" str_",
"cv2.threshold( blurred, threshold, 255, cv2.THRESH_BINARY) contours, _ = cv2.findContours( mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2:] count",
"3.5 def PARSE_DT(raw): \"\"\"Default parser for EXIF \"Image DateTime\" tag. \"\"\" str_ =",
"datetime.timedelta Timedelta object to format. fmt : str Contains format calls to days,",
"= self.jpg_data[0] for i, curr in enumerate(self.jpg_data): prev[\"selected\"] = ( prev[\"new_count\"] > self.plt_vals[\"resp_thresh\"]",
"ksize=11, min_area=100 ): \"\"\"Generates a response (movement) metric between images. Works hierarchically to",
"parameter to pass to attach_exif(), if more data is desired from EXIF tags.",
"multiplied based on slider. Manual user edits are applied. \"\"\" for i, row",
"row[\"med_diff\"] > self.plt_vals[\"trans_thresh\"]: new_count = 0 self.mark_edits(i, \"trans_edit\") if self.dt_present: new_count *= 1",
"> \") if answer.lower() in (\"y\", \"yes\"): return filename elif filename: return filename",
"(\"A\", \"B\", \"R\", \"L\"): tups = generate_clone_tuples(cl_corn, direct) a, b, c, d =",
"3600) d[\"minutes\"], d[\"seconds\"] = divmod(rem, 60) for k, v in d.items(): if k",
"- Hold to VIEW IMAGES in gallery. x - Hold and release to",
"else: scale = size / h new_w = rint(w * scale) new_h =",
"}) return output def attach_exif(jpg_data, parse_tags=DEFAULT_PARSE): \"\"\"Loops through jpg_data, reading filepaths and attaching",
"the jpg_data list can be fed into the Cam() class for response filtering.",
"= curr.shape[:2], prev.shape[:2] h, w = min(a, c), min(b, d) tup = (0,",
"directory path, finding all files ending in img_type. Parameters ---------- dirpath : str",
"0. , - Hold and release to REMOVE EDITS. . - Press to",
"on the long edge of the image. Smaller sizes speed up performance, but",
"used for exporting thumbnails. long_edge : int, optional By default, images will be",
"self.jpg_data] for row in temp_data: if \"datetime\" in row.keys(): row[\"datetime\"] = dt.strftime( row[\"datetime\"],",
"2 for i, count in enumerate(hist): tally += count if tally > threshold:",
"prev = curr else: nudge = int(self.plt_vals[\"smooth_time\"]) master_set = set() for i, row",
"CROP_EQUALIZE else: preprocess = CROP_CLONE_EQUALIZE output = [] timer = (len(jpg_data) // 10,",
"row in enumerate(write_data): if i != 0: f.write(\"\\n\") else: f.write(\",\".join(variables) + \"\\n\") f.write(\",\".join(csv_safe(row[v])",
"path for an initial save.\") cam.save(input_filename()) print(\"→ Use the interactive plot to select",
"image = CROPPER(image, crop) return cv2.equalizeHist(image) def crop_clone_preview(image): \"\"\"Interactive viewer to quickly get",
"the last step before the jpg_data list can be fed into the Cam()",
"= input(\"DIRPATH > \") if os.path.isdir(directory): return directory else: print(\"Directory does not exist,",
"VIEW IMAGES in gallery. x - Hold and release to INCREASE response value",
"in the CONTOURS() function, but retained here to shorten the process_jpgs() function. \"\"\"",
"plt.show() cv2.destroyAllWindows() if __name__ == \"__main__\": print(\"→ Please input a directory path with",
"based on time since last image (SMOOTH slider value). \"\"\" self.pano_i = 0",
"row in self.jpg_data] for row in temp_data: if \"datetime\" in row.keys(): row[\"datetime\"] =",
"directory here. These smaller images will be displayed in the Gallery tab. \"\"\"",
"= np.array(range(i - 2, i + 2)) while True: if any(n < 0",
"basic frame differencing method. Takes two images, then finds their absolute difference. A",
"\"%.2e\"), (\"TRANS\", 0.06, 0, 120, self.plt_vals[\"trans_thresh\"], \"%.1f\"), (\"SMOOTH\", 0.04, 0, 10, self.plt_vals[\"smooth_time\"], \"%.1f\"),",
"\"Image DateTime\" EXIF tag. This can be changed if images don\"t have a",
"= json.loads(next(f)) self.plt_vals[\"resp_thresh\"] = ( self.plt_vals[\"resp_thresh\"] ** (1 / RESP_NUM)) temp_data = json.loads(next(f))",
"data. Useful for cloning out timestamps, aids in histogram equalization. Parameters ---------- clone_to",
".sav file. mark_edits(i) Marks which photos have been edited. plot() Interactive plot used",
"input a file path for an initial save.\") cam.save(input_filename()) print(\"→ Use the interactive",
"array += 1 elif any(n >= self.length for n in array): array -=",
"> \") if os.path.exists(filename): print(\"File already exists, would you like to overwrite it?\")",
"return cv2.equalizeHist(image) def CROP_CLONE_EQUALIZE(image, crop, clone): \"\"\"Returns a cropped image, with specified cloning",
"for axe in (ax_crop, ax_clone): axe.set_xticklabels([]) axe.set_yticklabels([]) axe.set_xlim(lo_W, hi_W) axe.set_ylim(hi_H, lo_H) ax_crop.imshow(rgb) ax_clone.imshow(rgb)",
"timer): progress = (i * 10) // timer[0] elapsed = time.time() - timer[1]",
"Very noisy, but fast. Parameters ---------- curr : numpy.ndarray Image array, typically from",
"PARSE_DT) ] DEFAULT_PLOT_PARAMS = { \"ceiling\": 40000, \"resp_thresh\": 20000, \"trans_thresh\": 30, \"smooth_time\": 1,",
"{} self.sliders = {} self.user_edits = {} self.press = [None, None] self.toggle =",
"open(filename, \"w\") as f: f.write(json.dumps(self.plt_vals) + \"\\n\") f.write(json.dumps(temp_data) + \"\\n\") f.write(json.dumps(self.user_edits)) def load(self,",
"255, cv2.THRESH_BINARY) return cv2.countNonZero(mask) # Difference, blur (amount changes with ksize), mask and",
"- Hold and release to REMOVE EDITS. . - Press to RESET ALL",
"Used in the BLURRED() and CONTOURS() functions, but retained here to shorten the",
"for response filtering. Parameters ---------- jpg_data : list of dictionaries Requires that \"filepath\"",
"clone_to area. Neighboring pixels from \"[A]bove,\" \"[B]elow,\" \"[R]ight,\" and \"[L]eft\" are used for",
"\"is_night\", \"timedelta\", \"td_minutes\", \"median\", \"med_diff\", \"count\", \"new_count\", \"selected\", \"user_edit\", \"trans_edit\" ] RS_PARAMS =",
"return filename def input_directory(): while True: directory = input(\"DIRPATH > \") if os.path.isdir(directory):",
"= jpg.shape row[\"median\"] = hist_median(jpg) if not thresh_init: threshold = row[\"median\"]*1.05 try: row[\"count\"]",
"generate this object. \"\"\" image = CROPPER(image, crop) return cv2.equalizeHist(image) def CROP_CLONE_EQUALIZE(image, crop,",
"a JSON object as a .sav file. update_counts() Updates jpg_data attribute with new",
"[] for i, row in enumerate(self.jpg_data): write_row = row.copy() if row[\"selected\"]: if self.dt_present:",
"curr : numpy.ndarray Image array, typically from cv2.imread(). One of the two images",
"it?\") answer = input(\"Y / N > \") if answer.lower() in (\"y\", \"yes\"):",
"right based on increasing accuracy, decreasing speed. crop : tuple Format is (y1,",
"True def plot(self): \"\"\"Interactive plot used to select images for export. QUICK GUIDE:",
"ax_clone): axe.set_xticklabels([]) axe.set_yticklabels([]) axe.set_xlim(lo_W, hi_W) axe.set_ylim(hi_H, lo_H) ax_crop.imshow(rgb) ax_clone.imshow(rgb) ax_mod.imshow(rgb) plt.connect(\"draw_event\", update) plt.show()",
"key[:key.find(\"_\")].upper() if key == \"resp_thresh\": mod = self.sliders[slider_key].val ** RESP_NUM self.plt_vals[key] = mod",
"file, the Cam() object is now identical to the last. \"\"\" with open(filename,",
"cr_corn = (0, H, 0, W) mem.crop_tuple = False else: mem.crop_tuple = cr_corn",
"in array: if n in self.buffer[0]: ind = self.buffer[0].index(n) img = self.buffer[1][ind] self.buffer[0].append(self.buffer[0].pop(ind))",
"and attaching EXIF data. Useful for cloning out timestamps, aids in histogram equalization.",
"threshold: return i def generate_clone_tuples(clone_to, fill_from): \"\"\"Loops through jpg_data, reading filepaths and attaching",
"of same size, \" \"consider using the crop parameter.\\n\" f\"Try crop={tup}.\") return tup",
"= [] for deep_row in jpg_data: row = deep_row.copy() tags = piexif.load(row[\"filepath\"]) for",
"variable for sequence. process_options : dictionary, optional Passes along paramters to the process_jpgs()",
"Cam() object with its initial data. \"\"\" jpg_paths = find_imgs(dirpath) print(f\"{len(jpg_paths)} images found.\")",
"in dir_: found = ( f for f in files if f.lower().endswith(img_type) )",
"axe in (ax_crop, ax_clone): axe.set_xticklabels([]) axe.set_yticklabels([]) axe.set_xlim(lo_W, hi_W) axe.set_ylim(hi_H, lo_H) ax_crop.imshow(rgb) ax_clone.imshow(rgb) ax_mod.imshow(rgb)",
"import numpy as np from sklearn.cluster import KMeans from datetime import datetime as",
"difference. A simple threshold is called, the resulting white pixels are counted toward",
"unused Only used in the CONTOURS() function, but retained here to shorten the",
"DateTime\" tag. \"\"\" str_ = ''.join(x for x in str(raw) if x in",
"These smaller images will be displayed in the Gallery tab. \"\"\" self.resp_var =",
"= h * w * 0.02 self.plt_vals[\"resp_thresh\"] = self.plt_vals[\"ceiling\"] / 2 self.attach_diffs(\"median\", \"med_diff\")",
"in parse_tags: row[var] = anon(tags[key][tag]) output.append(row) return output def hist_median(image): \"\"\"Quickly finds the",
"to the cv2.threshold() function. ksize : int Parameter to be passed to the",
"{} self.press = [None, None] self.toggle = False self.buffer = [[None] * 64,",
"\"\"\" prev = self.jpg_data[0][var] for row in self.jpg_data: curr = row[var] row[new_var] =",
"= rint(h * scale) return cv2.resize(im, (new_w, new_h)) def generate_thumbnails(jpg_data, export_dir, long_edge=1024): \"\"\"Formats",
"= CROP_CLONE_EQUALIZE output = [] timer = (len(jpg_data) // 10, time.time()) for i,",
"image[a:b, c:d] = image[e:f, g:h] image = CROPPER(image, crop) return cv2.equalizeHist(image) def crop_clone_preview(image):",
"i, row in enumerate(write_data): if i != 0: f.write(\"\\n\") else: f.write(\",\".join(variables) + \"\\n\")",
"as jpg_data, but now with desired EXIF data attached. \"\"\" output = []",
"The crop_tuple variable can be fed directly into process_jpgs(). Then, use \"generate_clone_tuples(clone_to, directs[0])\"",
"DECREASE response value to 0. , - Hold and release to REMOVE EDITS.",
"Slider( slider_ax, name, minv, maxv, valinit=init, valfmt=fmt, color=\"#003459\", alpha=0.5) self.sliders[name].on_changed(on_slide) fig.canvas.mpl_connect(\"key_press_event\", on_key) fig.canvas.mpl_connect(\"key_release_event\",",
"row.keys(): row[\"selected\"] = int(row[\"selected\"]) with open(filename, \"w\") as f: f.write(json.dumps(self.plt_vals) + \"\\n\") f.write(json.dumps(temp_data)",
"time = datetime.time() return time.hour + time.minute / 60 + time.second / 3600",
"with commas in them. \"\"\" string = str(obj) return '\"' + string +",
"str, optional A key found in jpg_data, typically the \"count\" variable is used",
"*_ = image.shape scale = 10 lo_W, hi_W = (0 - W //",
"fig.add_axes([0.125, pos, 0.8, 0.02]) self.sliders[name] = Slider( slider_ax, name, minv, maxv, valinit=init, valfmt=fmt,",
"self.buffer[0].append(self.buffer[0].pop(ind)) self.buffer[1].append(self.buffer[1].pop(ind)) else: img = cv2.imread(self.jpg_data[n][\"thumbpath\"]) self.buffer[0] = self.buffer[0][1:] + [n] self.buffer[1] =",
"Directory path that is used for exporting thumbnails. long_edge : int, optional By",
"in (ax_crop, ax_clone): axe.set_xticklabels([]) axe.set_yticklabels([]) axe.set_xlim(lo_W, hi_W) axe.set_ylim(hi_H, lo_H) ax_crop.imshow(rgb) ax_clone.imshow(rgb) ax_mod.imshow(rgb) plt.connect(\"draw_event\",",
"c < 0 or d > W): trials.append((tups, direct)) choose = [] for",
"np.arange(0, self.length) + 0.5, -BIG_NUM, BIG_NUM, where=extract_var(self.jpg_data, \"is_night\"), facecolor=\"#003459\", alpha=0.5) except KeyError: pass",
"\"trans_edit\" ] RS_PARAMS = { \"drawtype\": \"box\", \"useblit\": True, \"button\": [1, 3], \"minspanx\":",
"def crop_clone_preview(image): \"\"\"Interactive viewer to quickly get crop and clone parameters. Parameters ----------",
"a empty Cam() object is desired for a load() method call. resp_var :",
"filepaths and attaching EXIF data. Useful for cloning out timestamps, aids in histogram",
"\"R\", \"L\"): tups = generate_clone_tuples(cl_corn, direct) a, b, c, d = tups[1] if",
"Can be omitted if a empty Cam() object is desired for a load()",
"finds their absolute difference. Prior to thresholding, the differenced image is blurred to",
"load() older, processed data. if jpg_data: self.jpg_data = list(jpg_data) self.length = len(self.jpg_data) self.dt_present",
"and previous variable. Requires a list of dictionaries. \"\"\" prev = self.jpg_data[0][var] for",
"= { \"drawtype\": \"box\", \"useblit\": True, \"button\": [1, 3], \"minspanx\": 5, \"minspany\": 5,",
"mod, \"%.2e\"), (\"TRANS\", 0.06, 0, 120, self.plt_vals[\"trans_thresh\"], \"%.1f\"), (\"SMOOTH\", 0.04, 0, 10, self.plt_vals[\"smooth_time\"],",
"tuples, optional Matches the format ((clone_to), (clone_from)). For simplicity, use generate_clone_tuples() to generate",
"jpg_data, but now with desired EXIF data attached. \"\"\" output = [] for",
"= False mem.clone_tuple = False mem.clone_directs = False def update(event): if crop_RS.active: crop_RS.update()",
"[0, i] if event.key in \"zxc,\": image_pano(event.xdata) elif event.key == \"v\": self.toggle =",
"**new_edits} elif event.key == \",\": for i in lo_to_hi: self.user_edits.pop(i, None) self.press =",
"last. \"\"\" with open(filename, \"r\") as f: self.plt_vals = json.loads(next(f)) self.plt_vals[\"resp_thresh\"] = (",
"initial save.\") cam.save(input_filename()) print(\"→ Use the interactive plot to select images for export.\")",
"crop, clone): \"\"\"Returns a cropped image, with specified cloning and equalization. Parameters ----------",
"shutil.copy2(row[\"filepath\"], new_path) write_data.append(write_row) if write_data: with open(os.path.join(directory, \"_export.csv\"), \"w\") as f: variables =",
"hierarchically to preform image cropping, cloning, and histogram equalization on images read from",
") for filename in found: filepath = os.path.join(dir_, filename) output.append({ \"filename\": filename, \"filepath\":",
"{int(k): v for k, v in temp_dict.items()} def export(self, directory): \"\"\"Exports selected images",
"None] self.toggle = False self.buffer = [[None] * 64, [None] * 64] self.recent_folder",
"= Mem() mem.crop_tuple = False mem.clone_tuple = False mem.clone_directs = False def update(event):",
"= np.array(extract_var(self.jpg_data, \"new_count\")) self.lines[\"edited\"] = ax.fill_between( np.arange(0, self.length) + 0.5, -BIG_NUM, BIG_NUM, where=[r[\"trans_edit\"]",
"np.arrays. fill_from : {\"A\", \"B\", \"R\", \"L\"} Calls directional tuples from DIRECTION_MULTS to",
"Requires that \"filepath\" is in dictionary keys, which is easily provided by find_imgs()",
"jpg[\"filename\"]) im = cv2.imread(from_path) resized = resize_long_edge(im, long_edge) cv2.imwrite(to_path, resized) piexif.transplant(from_path, to_path) #",
"since last image (SMOOTH slider value). \"\"\" self.pano_i = 0 prev = self.jpg_data[0]",
"preprocess(jpg, crop, clone) row[\"shape\"] = jpg.shape row[\"median\"] = hist_median(jpg) if not thresh_init: threshold",
": int, optional By default, images will be resized to 1024 pixels on",
"= round( row[\"timedelta\"].total_seconds() / 60, 2) day_hr = extract_var(self.jpg_data, \"24hr\") # meds =",
"= cv2.imread(from_path) resized = resize_long_edge(im, long_edge) cv2.imwrite(to_path, resized) piexif.transplant(from_path, to_path) # SPECIFIC FUNCTIONS",
"row[\"count\"] if row[\"med_diff\"] > self.plt_vals[\"trans_thresh\"]: new_count = 0 self.mark_edits(i, \"trans_edit\") if self.dt_present: new_count",
"move in (1, -1): is_neg = move < 0 prev = self.jpg_data[-is_neg] for",
"self.dt_present: dt_ISO = dt.strftime( row[\"datetime\"], \"%Y%m%dT%H%M%S\" ) else: dt_ISO = str(i) new_name =",
"\".jpeg\")): \"\"\"Walks directory path, finding all files ending in img_type. Parameters ---------- dirpath",
"a JSON object with jpg_data, plot_params, and user_edits. \"\"\" temp_data = [ {k:",
"var, anon in parse_tags: row[var] = anon(tags[key][tag]) output.append(row) return output def hist_median(image): \"\"\"Quickly",
"row[\"selected\"] = int(row[\"selected\"]) with open(filename, \"w\") as f: f.write(json.dumps(self.plt_vals) + \"\\n\") f.write(json.dumps(temp_data) +",
"to REMOVE EDITS. . - Press to RESET ALL EDITS. v - Press",
"keys, which is easily provided by find_imgs() prior to this function. method :",
"Same as jpg_data, but now with desired EXIF data attached. \"\"\" output =",
"range(self.length), 0, np_counts, facecolor=\"black\") self.lines[\"threshold\"] = ax.axhline( self.plt_vals[\"resp_thresh\"], color=\"#14B37D\") fig.canvas.draw_idle() def on_slide(val): for",
"from images.\") crop, clone_to, directs = crop_clone_preview( cv2.imread(jpg_data[len(jpg_data) // 2][\"filepath\"])) clone = generate_clone_tuples(clone_to,",
"= cv2.threshold( blurred, threshold, 255, cv2.THRESH_BINARY) return cv2.countNonZero(mask) # Like BLURRED, but only",
"their absolute difference. Prior to thresholding, the differenced image is blurred to reduce",
"= np.hstack([img[:min_y, :] for img in stack]) h, w, *_ = pano.shape cv2.namedWindow(\"Gallery\",",
"object as a string. Parameters ---------- tdelta : datetime.timedelta Timedelta object to format.",
"CONTOURS(curr, prev, threshold, ksize=11, min_area=100): \"\"\"Slower, but powerful frame differencing method. Takes two",
"toward response (movement). Works decently, a little faster than COUNTOURS. Parameters ---------- curr",
"with desired EXIF data attached. \"\"\" output = [] for deep_row in jpg_data:",
"ax.fill_between( np.arange(0, self.length) + 0.5, -BIG_NUM, 0, facecolor=\"white\", alpha=0.75, zorder=2) try: ax.fill_between( np.arange(0,",
"in data] def stop_watch(i, timer): progress = (i * 10) // timer[0] elapsed",
"slicing images as np.arrays. \"\"\" y1, y2, x1, x2 = crop return image[y1:y2,",
"to be taken. prev : numpy.ndarray Like curr. The second image to be",
"= KMeans(n_clusters=3).fit(X) night_indices = [np.argmin(kmeans.cluster_centers_), np.argmax(kmeans.cluster_centers_)] for n, index in enumerate(kmeans.labels_): self.jpg_data[n][\"is_night\"] =",
"= temp_data.copy() self.length = len(self.jpg_data) self.user_edits = {int(k): v for k, v in",
"If the contours are above the min_area parameter, they are counted as a",
"photo and its previous, after preprocessing / thresholding. \"\"\" if not threshold: thresh_init",
"file to specified directory. \"\"\" if not os.path.exists(directory): os.makedirs(directory) write_data = [] for",
"not i % timer[0] and i: stop_watch(i, timer) from_path = jpg[\"filepath\"] to_path =",
"DIRECTION_MULTS to fill pixels within the clone_to area. Neighboring pixels from \"[A]bove,\" \"[B]elow,\"",
"\"\"\" with open(filename, \"r\") as f: self.plt_vals = json.loads(next(f)) self.plt_vals[\"resp_thresh\"] = ( self.plt_vals[\"resp_thresh\"]",
"= ax.axhline( self.plt_vals[\"resp_thresh\"], color=\"#14B37D\") fig.canvas.draw_idle() def on_slide(val): for key in self.plt_vals.keys(): if key",
": list of dictionaries Requires that \"filepath\" and \"filename\" is in dictionary keys,",
"don\"t need to have data to initialize. # This way, someone can load()",
"initialize. # This way, someone can load() older, processed data. if jpg_data: self.jpg_data",
"= (min_y > H or max_y < 0 or min_x > W or",
"pixels are counted toward response (movement). Works decently, a little faster than COUNTOURS.",
"= cv2.absdiff(curr, prev) blurred = cv2.medianBlur(difference, ksize) _, mask = cv2.threshold( blurred, threshold,",
"False) process_options = {\"crop\": crop, \"clone\": clone} print(\"Started processing...\") output = process_jpgs(jpg_data, **process_options)",
"update(event): if crop_RS.active: crop_RS.update() if clone_RS.active: clone_RS.update() def safe_corners(geometry): min_y = max(0, min(geometry[0,",
"dt.strptime(str_, \"%Y%m%d%H%M%S\") def SORT_BY_DT(row): \"\"\"Default sort for construct_jpg_data(). \"\"\" return row[\"datetime\"] DEFAULT_PARSE =",
"does not exist, would you like to make it?\") answer = input(\"Y /",
"self.jpg_data = temp_data.copy() self.length = len(self.jpg_data) self.user_edits = {int(k): v for k, v",
"---------- jpg_data : list of dictionaries Requires that \"filepath\" is in dictionary keys,",
"type to 24 hour float type. \"\"\" time = datetime.time() return time.hour +",
"[img] if self.toggle: gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img = cv2.cv2.equalizeHist(gray) stack.append(img) min_y =",
"prev, threshold, ksize=11, min_area=None): \"\"\"Useful, mid-grade frame differencing method. Takes two images, then",
"\"timedelta\", \"td_minutes\", \"median\", \"med_diff\", \"count\", \"new_count\", \"selected\", \"user_edit\", \"trans_edit\" ] RS_PARAMS = {",
"( prev[\"new_count\"] > self.plt_vals[\"resp_thresh\"] or curr[\"new_count\"] > self.plt_vals[\"resp_thresh\"]) if i == self.length-1: curr[\"selected\"]",
"default, no options are specified. Make sure that this parameter is mappable. Returns",
"will be resized to 1024 pixels on the long edge of the image.",
"self.buffer[0] = self.buffer[0][1:] + [n] self.buffer[1] = self.buffer[1][1:] + [img] if self.toggle: gray",
"cv2.CHAIN_APPROX_SIMPLE)[-2:] count = 0 for cnt in contours: area = cv2.contourArea(cnt) if area",
"else: print(\"Directory does not exist, would you like to make it?\") answer =",
"i, row in enumerate(self.jpg_data): if row[\"selected\"]: for func in (operator.add, operator.sub): for j",
"jpg_data, typically the \"count\" variable is used as a response, but alternatives like",
"and clone out any timestamps from images.\") crop, clone_to, directs = crop_clone_preview( cv2.imread(jpg_data[len(jpg_data)",
"Hold to VIEW IMAGES in gallery. x - Hold and release to INCREASE",
"min_area=None): \"\"\"Most basic frame differencing method. Takes two images, then finds their absolute",
"they are counted as a response (movement). Works very well, little noise; slower",
"number. min_area : int Minimum contour area to count as a response (movement).",
"mem.crop_tuple = False else: mem.crop_tuple = cr_corn y1, y2, x1, x2 = cr_corn",
"no options are specified. Make sure that this parameter is mappable. Returns -------",
"self.jpg_data[i-1][kind] = True def update_counts(self): \"\"\"Updates jpg_data with new counts (response metric). Variable",
"out based on slider. Counts taken at with nighttime are multiplied based on",
"which respresents how many pixels have changed between a photo and its previous,",
"\"user_edit\") def update_events(self): \"\"\"Updates jpg_data with new events (runs of detection). An event",
"2)) while True: if any(n < 0 for n in array): array +=",
"\"\"\" image = CROPPER(image, crop) return cv2.equalizeHist(image) def CROP_CLONE_EQUALIZE(image, crop, clone): \"\"\"Returns a",
"white pixels are counted toward response (movement). Works decently, a little faster than",
"np.argmax(kmeans.cluster_centers_)] for n, index in enumerate(kmeans.labels_): self.jpg_data[n][\"is_night\"] = index in night_indices def save(self,",
"on_click) ax.fill_between( np.arange(0, self.length) + 0.5, -BIG_NUM, 0, facecolor=\"white\", alpha=0.75, zorder=2) try: ax.fill_between(",
"%H:%M:%S\" ) self.dt_present = True else: self.dt_present = False if \"timedelta\" in row.keys():",
"two and next two images from response spike. def image_pano(xdata): i = int(round(xdata))",
"crop return image[y1:y2, x1:x2] def CROP_EQUALIZE(image, crop, clone=None): \"\"\"Returns a cropped image with",
"pixels on the long edge of the image. Smaller sizes speed up performance,",
"decrease acuity. \"\"\" if not os.path.exists(export_dir): os.makedirs(export_dir) timer = (len(jpg_data) // 10, time.time())",
"30, \"smooth_time\": 1, \"night_mult\": 0 } DIRECTION_MULTS = { \"A\": (-1, -1, 0,",
"but can be changed if camera exports a different filetype. Returns ------- list",
"export. save(filename) Dumps a JSON object as a .sav file. update_counts() Updates jpg_data",
"function, optional By default, dictionaries within the jpg_data list are sorted by their",
"are above the min_area parameter, they are counted as a response (movement). Works",
"Returns ------- list of dictionaries Same as incoming jpg_data, but now with the",
"lo_to_hi: self.user_edits.pop(i, None) self.press = [None, None] update() except TypeError: pass plt.rc(\"font\", **{\"size\":",
"Only used in the CONTOURS() function, but retained here to shorten the process_jpgs()",
"be passed to the cv2.threshold() function. ksize : int Parameter to be passed",
"last two and next two images from response spike. def image_pano(xdata): i =",
"PARSE_DT(raw): \"\"\"Default parser for EXIF \"Image DateTime\" tag. \"\"\" str_ = ''.join(x for",
"for name, pos, minv, maxv, init, fmt in SLIDER_PARAMS: slider_ax = fig.add_axes([0.125, pos,",
"d[\"seconds\"] = divmod(rem, 60) for k, v in d.items(): if k != \"days\":",
"counted as a response (movement). Works very well, little noise; slower than others.",
"min_x = max(0, min(geometry[1, :])) max_x = min(W, max(geometry[1, :])) ignore = (min_y",
"10, time.time()) for i, jpg in enumerate(jpg_data): if not i % timer[0] and",
"contours, _ = cv2.findContours( mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2:] count = 0 for cnt in",
"= (0, h, 0, w) print(\"FUNCTION ABORTED!\\n\" \"Not all images are of same",
"self.jpg_data[0].keys() h, w = jpg_data[0][\"shape\"] self.plt_vals[\"ceiling\"] = h * w * 0.02 self.plt_vals[\"resp_thresh\"]",
"ax_clone.set_title(\"Clone\") ax_mod.set_title(\"Result\") for axe in (ax_crop, ax_clone): axe.set_xticklabels([]) axe.set_yticklabels([]) axe.set_xlim(lo_W, hi_W) axe.set_ylim(hi_H, lo_H)",
": int, unused Only used in the CONTOURS() function, but retained here to",
"elif filename: return filename def input_directory(): while True: directory = input(\"DIRPATH > \")",
"\"%.1f\"), (\"NIGHT\", 0.02, -1, 50, self.plt_vals[\"night_mult\"], \"%.1f\") ] def update(): self.update_counts() self.update_events() draw()",
"+ \"\\n\") f.write(\",\".join(csv_safe(row[v]) for v in variables)) else: raise ValueError(\"No images selected for",
"with its initial data. \"\"\" jpg_paths = find_imgs(dirpath) print(f\"{len(jpg_paths)} images found.\") jpg_data =",
"night_indices def save(self, filename): \"\"\"Dumps a JSON object with jpg_data, plot_params, and user_edits.",
"clone parameters. Parameters ---------- image : numpy.ndarray Image array, typically from cv2.imread(). Returns",
"A key found in jpg_data, typically the \"count\" variable is used as a",
"write_row[\"old_name\"] = row[\"filename\"] write_row[\"old_path\"] = row[\"filepath\"] shutil.copy2(row[\"filepath\"], new_path) write_data.append(write_row) if write_data: with open(os.path.join(directory,",
"of detection). An event is a contiguous sequence of images. First, images are",
"contains everything that is needed to feed a Cam() object with its initial",
"images). \"\"\" try: self.jpg_data except AttributeError as inst: raise inst mod = self.plt_vals[\"resp_thresh\"]",
"filename: return filename def input_directory(): while True: directory = input(\"DIRPATH > \") if",
"\"[R]ight,\" and \"[L]eft\" are used for filling the area. Returns ------- pair of",
"and release to REMOVE EDITS. . - Press to RESET ALL EDITS. v",
"in \"zxc,\": image_pano(event.xdata) elif event.key == \"v\": self.toggle = not self.toggle image_pano(event.xdata) elif",
"= int(self.plt_vals[\"smooth_time\"]) master_set = set() for i, row in enumerate(self.jpg_data): if row[\"selected\"]: for",
"filename def input_directory(): while True: directory = input(\"DIRPATH > \") if os.path.isdir(directory): return",
"range(0, 256) Parameter to be passed to the cv2.threshold() function. ksize : int",
"left.\") def strfdelta(tdelta, fmt): \"\"\"Formats a timedelta object as a string. Parameters ----------",
"256]) tally = 0 threshold = px_count / 2 for i, count in",
"min_area=100 ): \"\"\"Generates a response (movement) metric between images. Works hierarchically to preform",
"\"\\n\") f.write(json.dumps(temp_data) + \"\\n\") f.write(json.dumps(self.user_edits)) def load(self, filename): \"\"\"Loads a .sav file, the",
"break stack = [] for n in array: if n in self.buffer[0]: ind",
"N > \") if answer.lower() in (\"y\", \"yes\"): return filename elif filename: return",
"2 spaces, filled with zeros. \"\"\" d = {\"days\": tdelta.days} d[\"hours\"], rem =",
"max(geometry[0, :])) min_x = max(0, min(geometry[1, :])) max_x = min(W, max(geometry[1, :])) ignore",
"trials.append((tups, direct)) choose = [] for (tups, direct) in trials: test = image.copy()",
"resized to 1024 pixels on the long edge of the image. Smaller sizes",
"divmod(rem, 60) for k, v in d.items(): if k != \"days\": d[k] =",
"slicing images as np.arrays. fill_from : {\"A\", \"B\", \"R\", \"L\"} Calls directional tuples",
"threshold: thresh_init = False if not clone: preprocess = CROP_EQUALIZE else: preprocess =",
"h: scale = size / w else: scale = size / h new_w",
"\"old_path\", \"filename\", \"filepath\", \"shape\", \"datetime\", \"24hr\", \"is_night\", \"timedelta\", \"td_minutes\", \"median\", \"med_diff\", \"count\", \"new_count\",",
"provided by find_imgs() prior to this function. parse_tags : list of tuples, optional",
"with new events. \"\"\" def __init__(self, jpg_data=False, resp_var=\"count\", thumb_dir=None): \"\"\" Parameters ---------- jpg_data",
"MEAT AND POTATOES # Requires data from process_jpg(). Object essentially holds data #",
"axe.set_yticklabels([]) axe.set_xlim(lo_W, hi_W) axe.set_ylim(hi_H, lo_H) ax_crop.imshow(rgb) ax_clone.imshow(rgb) ax_mod.imshow(rgb) plt.connect(\"draw_event\", update) plt.show() return mem.crop_tuple,",
".csv file. load(filename) Loads a .sav file. mark_edits(i) Marks which photos have been",
"return fmt.format(**d) def resize_long_edge(im, size): h, w, *_ = im.shape if w >",
"passed to the cv2.threshold() function. ksize : int Parameter to be passed to",
"resize_long_edge(im, size): h, w, *_ = im.shape if w > h: scale =",
"Image array, typically from cv2.imread(). Returns ------- tuple Format is (crop, clone_to, clone_directs).",
"dictionary keys, which is easily provided by find_imgs() prior to this function. parse_tags",
"the \"count\" variable is used as a response, but alternatives like \"median\" can",
"*_ = pano.shape cv2.namedWindow(\"Gallery\", cv2.WINDOW_NORMAL) cv2.imshow(\"Gallery\", cv2.resize(pano, (w // 2, h // 2)))",
"None) self.press = [None, None] update() except TypeError: pass plt.rc(\"font\", **{\"size\": 8}) plt.rcParams[\"keymap.back\"]",
"0.8, 0.02]) self.sliders[name] = Slider( slider_ax, name, minv, maxv, valinit=init, valfmt=fmt, color=\"#003459\", alpha=0.5)",
"dictionary keys, which is easily provided by find_imgs() prior to this function. export_dir",
"self.jpg_data: curr = row[var] row[new_var] = curr - prev prev = curr def",
"same size, \" \"consider using the crop parameter.\\n\" f\"Try crop={tup}.\") return tup else:",
"counts (response metric). Variable new_count is attached to jpg_data. Day to night transitions",
"W, *_ = image.shape scale = 10 lo_W, hi_W = (0 - W",
"to VIEW IMAGES in gallery. x - Hold and release to INCREASE response",
"tups[1] if not (a < 0 or b > H or c <",
"images found.\") jpg_data = attach_exif(jpg_paths, parse_tags) jpg_data.sort(key=sort_key) if process_options == {}: print(\"Crop and",
"differencing methods that generate a response metric. This is the last step before",
"(generate_clone_tuples(clone_to, directs[0]) if clone_to else False) process_options = {\"crop\": crop, \"clone\": clone} print(\"Started",
"row[\"user_edit\"] = False row[\"trans_edit\"] = False if self.dt_present: self.attach_diffs(\"datetime\", \"timedelta\") for row in",
"else: self.plt_vals[key] = self.sliders[slider_key].val update() # Displays last two and next two images",
"0.02]) self.sliders[name] = Slider( slider_ax, name, minv, maxv, valinit=init, valfmt=fmt, color=\"#003459\", alpha=0.5) self.sliders[name].on_changed(on_slide)",
"{SIMPLE, BLURRED, COUNTOURS} Determines the frame differencing method to use. Ordered from left",
"axe.set_xlim(lo_W, hi_W) axe.set_ylim(hi_H, lo_H) ax_crop.imshow(rgb) ax_clone.imshow(rgb) ax_mod.imshow(rgb) plt.connect(\"draw_event\", update) plt.show() return mem.crop_tuple, mem.clone_tuple,",
"extract_var(data, var): \"\"\"Returns a list of values corresponding to a variable name. >>>",
"def resize_long_edge(im, size): h, w, *_ = im.shape if w > h: scale",
"d), (e, f, g, h) = tups test[a:b, c:d] = test[e:f, g:h] diff",
"initial data. \"\"\" jpg_paths = find_imgs(dirpath) print(f\"{len(jpg_paths)} images found.\") jpg_data = attach_exif(jpg_paths, parse_tags)",
"\"\"\" clone_to = np.array(clone_to) mults = np.array(DIRECTION_MULTS[fill_from[0].upper()]) a, b, c, d = clone_to",
"an area of 100 pixels. Larger numbers decreases sensitivity. Returns ------- list of",
"c, d), (e, f, g, h) = tups test[a:b, c:d] = test[e:f, g:h]",
"def input_filename(): while True: filename = input(\"FILEPATH > \") if os.path.exists(filename): print(\"File already",
"and not (prev[\"user_edit\"] and curr[\"user_edit\"])) if boo: if not is_neg: lapse = curr[\"td_minutes\"]",
"row[\"median\"] = hist_median(jpg) if not thresh_init: threshold = row[\"median\"]*1.05 try: row[\"count\"] = method(curr,",
"value to 0. , - Hold and release to REMOVE EDITS. . -",
"This way, someone can load() older, processed data. if jpg_data: self.jpg_data = list(jpg_data)",
"object as a .sav file. update_counts() Updates jpg_data attribute with new counts. update_events()",
"size, \" \"consider using the crop parameter.\\n\" f\"Try crop={tup}.\") return tup else: print(inst)",
"kind): \"\"\"Marks which photos to label as edited based on [i]ndex. \"\"\" if",
"if not i % timer[0] and i: stop_watch(i, timer) from_path = jpg[\"filepath\"] to_path",
"function. By default, no options are specified. Make sure that this parameter is",
"\"age\": 7}] >>> extract_var(data=foo, var=\"name\") [\"Shane\", \"Eve\"] \"\"\" return [x[var] for x in",
"= process_jpgs(jpg_data, **process_options) print(\"Done!\") return output # THE MEAT AND POTATOES # Requires",
"row.keys(): try: row[\"timedelta\"] = td(seconds=row[\"timedelta\"]) except AttributeError: pass if \"selected\" in row.keys(): row[\"selected\"]",
"response, but alternatives like \"median\" can be used to plot jpgs without processing",
"print(\"Crop and clone image as desired.\") crop, clone_to, directs = crop_clone_preview( cv2.imread(jpg_data[len(jpg_data) //",
"elif event.key == \".\": self.user_edits = {} def off_key(event): try: if event.xdata is",
"cv2.COLOR_BGR2GRAY) img = cv2.cv2.equalizeHist(gray) stack.append(img) min_y = min(img.shape[0] for img in stack) pano",
"row[\"datetime\"], \"%Y-%m-%d %H:%M:%S\" ) self.dt_present = True else: self.dt_present = False if \"timedelta\"",
"\"\"\"Dumps a JSON object with jpg_data, plot_params, and user_edits. \"\"\" temp_data = [",
"is desired from EXIF tags. Returns ------- list of dictionaries Same as jpg_data,",
"is needed to feed a Cam() object with its initial data. \"\"\" jpg_paths",
"simple threshold is called, the resulting white pixels are counted toward response (movement).",
"\"__main__\": print(\"→ Please input a directory path with camera-trapping images.\") jpg_paths = find_imgs(input_directory())",
"import os import shutil import string import sys import time import cv2 import",
"response (movement) metric between images. Works hierarchically to preform image cropping, cloning, and",
"A simply initialization could be: Cam(construct_jpg_data()). After filtering images with the plot, save()",
"---------- curr : numpy.ndarray Image array, typically from cv2.imread(). One of the two",
"row.keys(): row[\"selected\"] = bool(row[\"selected\"]) self.jpg_data = temp_data.copy() self.length = len(self.jpg_data) self.user_edits = {int(k):",
"files ending in img_type. Parameters ---------- dirpath : str Path to an image-containing",
"meds = extract_var(self.jpg_data, \"median\") X = np.array(day_hr).reshape(-1, 1) kmeans = KMeans(n_clusters=3).fit(X) night_indices =",
"attach_exif(jpg_paths) jpg_data.sort(key=lambda x: x[\"datetime\"]) print(\"→ Crop and clone out any timestamps from images.\")",
"prev, threshold, ksize=None, min_area=None): \"\"\"Most basic frame differencing method. Takes two images, then",
"= cv2.cvtColor(image, cv2.COLOR_BGR2RGB) H, W, *_ = image.shape scale = 10 lo_W, hi_W",
"count variable, which respresents how many pixels have changed between a photo and",
"area of 100 pixels. Larger numbers decreases sensitivity. Returns ------- list of dictionaries",
"min(b, d) tup = (0, h, 0, w) print(\"FUNCTION ABORTED!\\n\" \"Not all images",
"file. load(filename) Loads a .sav file. mark_edits(i) Marks which photos have been edited.",
"essentially holds data # used in exporting, parameters for graphing, and plot function.",
"(SMOOTH slider value). \"\"\" self.pano_i = 0 prev = self.jpg_data[0] for i, curr",
"mem.clone_directs = directs mod = imgs[0] del choose else: mem.clone_tuple = False mem.clone_directs",
"just like slicing images as np.arrays. clone : pair of tuples, optional Matches",
"shorten the process_jpgs() function. \"\"\" difference = cv2.absdiff(curr, prev) blurred = cv2.medianBlur(difference, ksize)",
"0) curr = preprocess(jpg, crop, clone) row[\"shape\"] = jpg.shape row[\"median\"] = hist_median(jpg) if",
"= {} self.press = [None, None] self.toggle = False self.buffer = [[None] *",
"clone_from = clone_to + (h_or_w * mults) return (tuple(clone_to), tuple(clone_from)) # IMAGE PREPROCESSING",
"find_imgs(input_directory()) jpg_data = attach_exif(jpg_paths) jpg_data.sort(key=lambda x: x[\"datetime\"]) print(\"→ Crop and clone out any",
"event.key in \"zx,\": i = int(round(event.xdata)) low, high = sorted((self.press[1], i)) lo_to_hi =",
"AttributeError as inst: raise inst mod = self.plt_vals[\"resp_thresh\"] ** (1 / RESP_NUM) SLIDER_PARAMS",
"choose: _, directs, imgs = list(zip(*choose)) mem.clone_directs = directs mod = imgs[0] del",
"0.02, -1, 50, self.plt_vals[\"night_mult\"], \"%.1f\") ] def update(): self.update_counts() self.update_events() draw() def draw():",
"> W): trials.append((tups, direct)) choose = [] for (tups, direct) in trials: test",
"**RS_PARAMS) ax_crop.set_title(\"Crop\") ax_clone.set_title(\"Clone\") ax_mod.set_title(\"Result\") for axe in (ax_crop, ax_clone): axe.set_xticklabels([]) axe.set_yticklabels([]) axe.set_xlim(lo_W, hi_W)",
"Parameter to be passed to the cv2.threshold() function. ksize : int, unused Used",
"self.buffer = [[None] * 64, [None] * 64] self.recent_folder = os.path.expanduser(\"~\") # Cam",
"prev : numpy.ndarray Like curr. The second image to be differenced. threshold :",
"preprocessing / thresholding. \"\"\" if not threshold: thresh_init = False if not clone:",
"second image to be differenced. threshold : int, in range(0, 256) Parameter to",
"dictionary keys, which is easily provided by find_imgs() prior to this function. method",
"to specified directory. \"\"\" if not os.path.exists(directory): os.makedirs(directory) write_data = [] for i,",
"i, count in enumerate(hist): tally += count if tally > threshold: return i",
"max(geometry[1, :])) ignore = (min_y > H or max_y < 0 or min_x",
"object is now identical to the last. \"\"\" with open(filename, \"r\") as f:",
"retained here to shorten the process_jpgs() function. \"\"\" difference = cv2.absdiff(curr, prev) _,",
"event is a contiguous sequence of images. First, images are identified as being",
"is a contiguous sequence of images. First, images are identified as being selected",
"matplotlib.widgets import Slider, RectangleSelector import matplotlib.gridspec as gridspec # CONSTANTS BIG_NUM = int(1e9)",
"cv2.destroyAllWindows() if __name__ == \"__main__\": print(\"→ Please input a directory path with camera-trapping",
"= strfdelta(td(seconds=total - elapsed), \"{days}:{hours}:{minutes}:{seconds}\") print(f\"{progress}% done. {remain} left.\") def strfdelta(tdelta, fmt): \"\"\"Formats",
"plt from matplotlib.widgets import Slider, RectangleSelector import matplotlib.gridspec as gridspec # CONSTANTS BIG_NUM",
"gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img = cv2.cv2.equalizeHist(gray) stack.append(img) min_y = min(img.shape[0] for img",
"crop=False, clone=False, threshold=False, ksize=11, min_area=100 ): \"\"\"Generates a response (movement) metric between images.",
"based on increasing accuracy, decreasing speed. crop : tuple Format is (y1, y2,",
"selection, edits, event, etc. plot_params : dictionary Parameters used in the plot() method.",
"\"resp_thresh\": mod = self.sliders[slider_key].val ** RESP_NUM self.plt_vals[key] = mod self.sliders[slider_key].valtext.set_text(\"%.2e\" % mod) else:",
"\"\"\"Interactive plot used to select images for export. QUICK GUIDE: c - Hold",
"for i in lo_to_hi} self.user_edits = {**self.user_edits, **new_edits} elif event.key == \",\": for",
"fig.add_subplot(111) fig.canvas.set_window_title(\"Response Filtering\") fig.subplots_adjust(0.07, 0.18, 0.97, 0.97) ax.grid(alpha=0.4) ax.set_axisbelow(True) ax.set_ylim([0, self.plt_vals[\"ceiling\"]]) ax.set_xlim([0, min(500,",
"import shutil import string import sys import time import cv2 import piexif import",
"cnt in contours: area = cv2.contourArea(cnt) if area > min_area: count += area",
"images.\") jpg_paths = find_imgs(input_directory()) jpg_data = attach_exif(jpg_paths) jpg_data.sort(key=lambda x: x[\"datetime\"]) print(\"→ Crop and",
"any timestamps from images.\") crop, clone_to, directs = crop_clone_preview( cv2.imread(jpg_data[len(jpg_data) // 2][\"filepath\"])) clone",
"0, w) prev = preprocess(jpg, crop, clone) elif i % timer[0] == 0:",
"/ 100) remain = strfdelta(td(seconds=total - elapsed), \"{days}:{hours}:{minutes}:{seconds}\") print(f\"{progress}% done. {remain} left.\") def",
"_, directs, imgs = list(zip(*choose)) mem.clone_directs = directs mod = imgs[0] del choose",
"displayed in the Gallery tab. \"\"\" self.resp_var = resp_var self.plt_vals = DEFAULT_PLOT_PARAMS self.lines",
"from EXIF tags. Returns ------- list of dictionaries Same as jpg_data, but now",
"Format is (y1, y2, x1, x2), just like slicing images as np.arrays. fill_from",
"np.array(clone_to) mults = np.array(DIRECTION_MULTS[fill_from[0].upper()]) a, b, c, d = clone_to h, w =",
"self.press = [0, i] if event.key in \"zxc,\": image_pano(event.xdata) elif event.key == \"v\":",
"facecolor=\"#D8BFAA\", alpha=0.5) self.lines[\"selected\"] = ax.fill_between( np.arange(0, self.length) + 0.5, -BIG_NUM, BIG_NUM, where=extract_var(self.jpg_data, \"selected\"),",
"to use. Ordered from left to right based on increasing accuracy, decreasing speed.",
"if i != self.pano_i: self.pano_i = i array = np.array(range(i - 2, i",
"((\"0th\", 306), \"datetime\", PARSE_DT) ] DEFAULT_PLOT_PARAMS = { \"ceiling\": 40000, \"resp_thresh\": 20000, \"trans_thresh\":",
"y1, y2, x1, x2 = cr_corn mod = mod[y1:y2, x1:x2] mod = cv2.cvtColor(mod,",
"any(n < 0 for n in array): array += 1 elif any(n >=",
"simplicity, use generate_clone_tuples() to generate this object. \"\"\" (a, b, c, d), (e,",
"this function. method : function, {SIMPLE, BLURRED, COUNTOURS} Determines the frame differencing method",
"on_key) fig.canvas.mpl_connect(\"key_release_event\", off_key) fig.canvas.mpl_connect(\"button_press_event\", on_click) ax.fill_between( np.arange(0, self.length) + 0.5, -BIG_NUM, 0, facecolor=\"white\",",
"have a datetime, but do have a variable for sequence. process_options : dictionary,",
"\"timedelta\") for row in self.jpg_data: row[\"24hr\"] = to_24_hour(row[\"datetime\"]) row[\"td_minutes\"] = round( row[\"timedelta\"].total_seconds() /",
"d = tups[1] if not (a < 0 or b > H or",
"the last. \"\"\" with open(filename, \"r\") as f: self.plt_vals = json.loads(next(f)) self.plt_vals[\"resp_thresh\"] =",
"Hold and release to REMOVE EDITS. . - Press to RESET ALL EDITS.",
"with an equalized histogram. Parameters ---------- image : numpy.ndarray Image array, typically from",
"RESP_NUM = 3.5 def PARSE_DT(raw): \"\"\"Default parser for EXIF \"Image DateTime\" tag. \"\"\"",
"to thresholding, the differenced image is blurred to reduce noise. After thresholding, contours",
"in temp_data: if \"datetime\" in row.keys(): row[\"datetime\"] = dt.strftime( row[\"datetime\"], \"%Y-%m-%d %H:%M:%S\") if",
"if f.lower().endswith(img_type) ) for filename in found: filepath = os.path.join(dir_, filename) output.append({ \"filename\":",
"and export() should be called so as not to lose any prior work.",
"+= count if tally > threshold: return i def generate_clone_tuples(clone_to, fill_from): \"\"\"Loops through",
"crop): \"\"\"Returns a cropped image. Parameters ---------- image : numpy.ndarray Image array, typically",
"f for f in files if f.lower().endswith(img_type) ) for filename in found: filepath",
"\"L\": (0, 0, -1, -1) } COL_ORDER = [ \"old_name\", \"old_path\", \"filename\", \"filepath\",",
"= int(1e9) NEG_NUM = -0.1 RESP_NUM = 3.5 def PARSE_DT(raw): \"\"\"Default parser for",
"array): array += 1 elif any(n >= self.length for n in array): array",
"object as a string. Parameters ---------- jpg_data : list of dictionaries Requires that",
"try: if event.xdata is not None and event.key in \"zx,\": i = int(round(event.xdata))",
"== 0: self.jpg_data[i][kind] = True else: self.jpg_data[i][kind] = True self.jpg_data[i-1][kind] = True def",
"path with camera-trapping images.\") jpg_paths = find_imgs(input_directory()) jpg_data = attach_exif(jpg_paths) jpg_data.sort(key=lambda x: x[\"datetime\"])",
"a list of dictionaries. \"\"\" prev = self.jpg_data[0][var] for row in self.jpg_data: curr",
"> h: scale = size / w else: scale = size / h",
"else: break stack = [] for n in array: if n in self.buffer[0]:",
"print(\"Done!\") return output # THE MEAT AND POTATOES # Requires data from process_jpg().",
"* scale) new_h = rint(h * scale) return cv2.resize(im, (new_w, new_h)) def generate_thumbnails(jpg_data,",
"odd number. min_area : int Minimum contour area to count as a response",
"self.pano_i = i array = np.array(range(i - 2, i + 2)) while True:",
"jpg[\"filepath\"] to_path = os.path.join(export_dir, jpg[\"filename\"]) im = cv2.imread(from_path) resized = resize_long_edge(im, long_edge) cv2.imwrite(to_path,",
"\"[B]elow,\" \"[R]ight,\" and \"[L]eft\" are used for filling the area. Returns ------- pair",
"call. resp_var : str, optional A key found in jpg_data, typically the \"count\"",
"row[\"datetime\"] DEFAULT_PARSE = [ ((\"0th\", 306), \"datetime\", PARSE_DT) ] DEFAULT_PLOT_PARAMS = { \"ceiling\":",
"def PARSE_DT(raw): \"\"\"Default parser for EXIF \"Image DateTime\" tag. \"\"\" str_ = ''.join(x",
"object to format. fmt : str Contains format calls to days, hours, minutes,",
"tuple(map( lambda x: int(round(x)), (min_y, max_y, min_x, max_x))), ignore def RS_event(eclick, erelease): x1,",
"in the Gallery tab. \"\"\" self.resp_var = resp_var self.plt_vals = DEFAULT_PLOT_PARAMS self.lines =",
"pair of tuples Matches the format ((clone_to), (clone_from)). For simplicity, use generate_clone_tuples() to",
"if i != 0: f.write(\"\\n\") else: f.write(\",\".join(variables) + \"\\n\") f.write(\",\".join(csv_safe(row[v]) for v in",
"= cv2.medianBlur(difference, ksize) _, mask = cv2.threshold( blurred, threshold, 255, cv2.THRESH_BINARY) return cv2.countNonZero(mask)",
"new events (runs of detection). An event is a contiguous sequence of images.",
"Clone Preview\") ax_crop = fig.add_subplot(gs[0, 0]) ax_clone = fig.add_subplot(gs[0, 1]) ax_mod = fig.add_subplot(gs[1,",
"array = np.array(range(i - 2, i + 2)) while True: if any(n <",
"white pixels are counted toward response (movement). Very noisy, but fast. Parameters ----------",
"resp_var=\"count\", thumb_dir=None): \"\"\" Parameters ---------- jpg_data : list of dictionaries, optional Typically requires",
"based on slider. Counts taken at with nighttime are multiplied based on slider.",
"data from process_jpg(). Object essentially holds data # used in exporting, parameters for",
"tags. Returns ------- list of dictionaries Same as jpg_data, but now with desired",
"fill_from): \"\"\"Loops through jpg_data, reading filepaths and attaching EXIF data. Useful for cloning",
"update) plt.show() return mem.crop_tuple, mem.clone_tuple, mem.clone_directs # FRAME DIFFERENCING METHODS # Bare-bones. Take",
"array, typically from cv2.imread(). One of the two images for the absolute difference",
"test[a:b, c:d] = test[e:f, g:h] diff = cv2.absdiff(test, image) choose.append((sum(cv2.sumElems(diff)), direct, test)) choose.sort()",
": function, {SIMPLE, BLURRED, COUNTOURS} Determines the frame differencing method to use. Ordered",
"!= 0: f.write(\"\\n\") else: f.write(\",\".join(variables) + \"\\n\") f.write(\",\".join(csv_safe(row[v]) for v in variables)) else:",
"for row in self.jpg_data: curr = row[var] row[new_var] = curr - prev prev",
"Requires data from process_jpg(). Object essentially holds data # used in exporting, parameters",
"for (tups, direct) in trials: test = image.copy() (a, b, c, d), (e,",
"RS_PARAMS = { \"drawtype\": \"box\", \"useblit\": True, \"button\": [1, 3], \"minspanx\": 5, \"minspany\":",
"= DEFAULT_PLOT_PARAMS self.lines = {} self.sliders = {} self.user_edits = {} self.press =",
"= cv2.threshold( blurred, threshold, 255, cv2.THRESH_BINARY) contours, _ = cv2.findContours( mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2:]",
"json.loads(next(f)) self.plt_vals[\"resp_thresh\"] = ( self.plt_vals[\"resp_thresh\"] ** (1 / RESP_NUM)) temp_data = json.loads(next(f)) temp_dict",
"cv2.absdiff(test, image) choose.append((sum(cv2.sumElems(diff)), direct, test)) choose.sort() if choose: _, directs, imgs = list(zip(*choose))",
"= prev[\"td_minutes\"] curr[\"selected\"] = ( lapse <= self.plt_vals[\"smooth_time\"]) prev = curr else: nudge",
"in (\"count\", \"threshold\", \"selected\", \"edited\"): self.lines[name] = ax.axhline() for name, pos, minv, maxv,",
"else string def to_24_hour(datetime): \"\"\"Converts datetime.datetime type to 24 hour float type. \"\"\"",
"with open(os.path.join(directory, \"_export.csv\"), \"w\") as f: variables = sorted(write_data[0].keys(), key=sort_cols) for i, row",
"---------- image : numpy.ndarray Image array, typically from cv2.imread(). crop : tuple Format",
"frame differencing method. Takes two images, then finds their absolute difference. A simple",
"min_area: count += area return count # JPG PROCESSING def process_jpgs( jpg_data, method=CONTOURS,",
"row in self.jpg_data: curr = row[var] row[new_var] = curr - prev prev =",
"inst: raise inst mod = self.plt_vals[\"resp_thresh\"] ** (1 / RESP_NUM) SLIDER_PARAMS = [",
"Like BLURRED, but only sums drawn contours over given limit. def CONTOURS(curr, prev,",
"False mem.clone_directs = False if cr_ig: cr_corn = (0, H, 0, W) mem.crop_tuple",
"and user_edits. \"\"\" temp_data = [ {k: v for k, v in row.items()}",
"update_counts() Updates jpg_data attribute with new counts. update_events() Updates jpg_data attribute with new",
"method to use. Ordered from left to right based on increasing accuracy, decreasing",
"row[var] = anon(tags[key][tag]) output.append(row) return output def hist_median(image): \"\"\"Quickly finds the median tone",
"image.shape[0] * image.shape[1] hist = cv2.calcHist([image], [0], None, [256], [0, 256]) tally =",
"the heart of this module, the interactive plot() method. A simply initialization could",
"crop=crop, clone=clone) if type(processed_data) is not tuple: cam = Cam(processed_data) print(\"→ Please input",
"= Cam(processed_data) print(\"→ Please input a file path for an initial save.\") cam.save(input_filename())",
"that is used for exporting thumbnails. long_edge : int, optional By default, images",
"directs list (all have been checked for bounds, unlike generate_clone_tuples). \"\"\" mem =",
"(\"y\", \"yes\"): os.makedirs(directory) return directory print(\"Please input a new directory path.\") def csv_safe(obj):",
"self.sliders[slider_key].val ** RESP_NUM self.plt_vals[key] = mod self.sliders[slider_key].valtext.set_text(\"%.2e\" % mod) else: self.plt_vals[key] = self.sliders[slider_key].val",
"\"%Y-%m-%d %H:%M:%S\") if \"timedelta\" in row.keys(): row[\"timedelta\"] = row[\"timedelta\"].total_seconds() if \"selected\" in row.keys():",
"\"w\") as f: variables = sorted(write_data[0].keys(), key=sort_cols) for i, row in enumerate(write_data): if",
"mem.crop_tuple, mem.clone_tuple, mem.clone_directs # FRAME DIFFERENCING METHODS # Bare-bones. Take difference, threshold, and",
"clone=None): \"\"\"Returns a cropped image with an equalized histogram. Parameters ---------- image :",
"or curr[\"new_count\"] > self.plt_vals[\"resp_thresh\"]) if i == self.length-1: curr[\"selected\"] = ( curr[\"new_count\"] >",
"of this module, the interactive plot() method. A simply initialization could be: Cam(construct_jpg_data()).",
"JPG PROCESSING def process_jpgs( jpg_data, method=CONTOURS, crop=False, clone=False, threshold=False, ksize=11, min_area=100 ): \"\"\"Generates",
"RectangleSelector( ax_clone, RS_event, **RS_PARAMS) ax_crop.set_title(\"Crop\") ax_clone.set_title(\"Clone\") ax_mod.set_title(\"Result\") for axe in (ax_crop, ax_clone): axe.set_xticklabels([])",
"mod = self.plt_vals[\"resp_thresh\"] ** (1 / RESP_NUM) SLIDER_PARAMS = [ (\"RESP\", 0.08, 0,",
"= fig.add_subplot(gs[1, :]) crop_RS = RectangleSelector( ax_crop, RS_event, **RS_PARAMS) clone_RS = RectangleSelector( ax_clone,",
"this object. threshold : int, in range(0, 256) Parameter to be passed to",
"in enumerate(jpg_data): if not i % timer[0] and i: stop_watch(i, timer) from_path =",
"lumped based on time since last image (SMOOTH slider value). \"\"\" self.pano_i =",
"write_row = row.copy() if row[\"selected\"]: if self.dt_present: dt_ISO = dt.strftime( row[\"datetime\"], \"%Y%m%dT%H%M%S\" )",
"\"filepath\" and \"filename\" is in dictionary keys, which is easily provided by find_imgs()",
"an image-containing directory. img_type : tuple, optional By default, finds JPG image types,",
"def update_events(self): \"\"\"Updates jpg_data with new events (runs of detection). An event is",
"RESP_NUM) SLIDER_PARAMS = [ (\"RESP\", 0.08, 0, 100, mod, \"%.2e\"), (\"TRANS\", 0.06, 0,",
"this object. \"\"\" image = CROPPER(image, crop) return cv2.equalizeHist(image) def CROP_CLONE_EQUALIZE(image, crop, clone):",
"to attach_exif(), if more data is desired from EXIF tags. sort_key : function,",
"any prior work. Attributes ---------- jpg_data : list of dictionaries Similar to what",
"of a grayscale image. \"\"\" px_count = image.shape[0] * image.shape[1] hist = cv2.calcHist([image],",
"+ \"\\n\") f.write(json.dumps(self.user_edits)) def load(self, filename): \"\"\"Loads a .sav file, the Cam() object",
"as a .sav file. update_counts() Updates jpg_data attribute with new counts. update_events() Updates"
] |
[
"= js['answers'] return predictions def calculate_scores(answers, predictions): scores = [] for key in",
"predictions): scores = [] for key in answers: # import ipdb # ipdb.set_trace()",
"Copyright (c) Microsoft Corporation. # Licensed under the MIT license. # Adapted from",
"sys.exit() flag = False for rank, idx in enumerate(predictions[key]): if idx == answers[key]:",
"= read_answers(args.answers) print(\"reading predcited answers\") predictions = read_predictions(args.predictions) print(\"computing scores\") scores = calculate_scores(answers,",
"answers def read_predictions(filename): predictions = {} with open(filename) as f: for idx, line",
"as f: for idx, line in enumerate(f): line = line.strip() js = json.loads(line)",
"break if flag is False: scores.append(0) result = {} result['MRR'] = round(np.mean(scores), 4)",
"return answers def read_predictions(filename): predictions = {} with open(filename) as f: for idx,",
"for POJ-104 dataset.') parser.add_argument('--answers', '-a', help=\"filename of the labels, in txt format.\") parser.add_argument('--predictions',",
"line.strip() js = json.loads(line) predictions[str(idx)] = js['answers'] return predictions def calculate_scores(answers, predictions): scores",
"license. # Adapted from https://github.com/microsoft/CodeXGLUE/blob/main/Text-Code/NL-code-search-Adv/evaluator/evaluator.py import logging import sys, json import numpy as",
"answers[str(idx)] = str(idx) return answers def read_predictions(filename): predictions = {} with open(filename) as",
"scores = [] for key in answers: # import ipdb # ipdb.set_trace() if",
"== answers[key]: scores.append(1 / (rank + 1)) flag = True break if flag",
"= parser.parse_args() print(\"reading gold answers\") answers = read_answers(args.answers) print(\"reading predcited answers\") predictions =",
"= round(np.mean(scores), 4) return result def main(): import argparse parser = argparse.ArgumentParser(description='Evaluate leaderboard",
"main(): import argparse parser = argparse.ArgumentParser(description='Evaluate leaderboard predictions for POJ-104 dataset.') parser.add_argument('--answers', '-a',",
"format.\") parser.add_argument('--predictions', '-p', help=\"filename of the leaderboard predictions, in txt format.\") args =",
"predictions = {} with open(filename) as f: for idx, line in enumerate(f): line",
"(rank + 1)) flag = True break if flag is False: scores.append(0) result",
"sys, json import numpy as np def read_answers(filename): answers = {} with open(filename)",
"txt format.\") args = parser.parse_args() print(\"reading gold answers\") answers = read_answers(args.answers) print(\"reading predcited",
"for url {}.\".format(key)) sys.exit() flag = False for rank, idx in enumerate(predictions[key]): if",
"f: for idx, line in enumerate(f): line = line.strip() js = json.loads(line) predictions[str(idx)]",
"scores = calculate_scores(answers, predictions) print(scores) if __name__ == '__main__': main() # python mrr.py",
"Microsoft Corporation. # Licensed under the MIT license. # Adapted from https://github.com/microsoft/CodeXGLUE/blob/main/Text-Code/NL-code-search-Adv/evaluator/evaluator.py import",
"if key not in predictions: logging.error(\"Missing prediction for url {}.\".format(key)) sys.exit() flag =",
"read_answers(filename): answers = {} with open(filename) as f: for idx, line in enumerate(f):",
"from https://github.com/microsoft/CodeXGLUE/blob/main/Text-Code/NL-code-search-Adv/evaluator/evaluator.py import logging import sys, json import numpy as np def read_answers(filename):",
"def calculate_scores(answers, predictions): scores = [] for key in answers: # import ipdb",
"# Adapted from https://github.com/microsoft/CodeXGLUE/blob/main/Text-Code/NL-code-search-Adv/evaluator/evaluator.py import logging import sys, json import numpy as np",
"enumerate(f): line = line.strip() js = json.loads(line) predictions[str(idx)] = js['answers'] return predictions def",
"the leaderboard predictions, in txt format.\") args = parser.parse_args() print(\"reading gold answers\") answers",
"enumerate(predictions[key]): if idx == answers[key]: scores.append(1 / (rank + 1)) flag = True",
"= argparse.ArgumentParser(description='Evaluate leaderboard predictions for POJ-104 dataset.') parser.add_argument('--answers', '-a', help=\"filename of the labels,",
"4) return result def main(): import argparse parser = argparse.ArgumentParser(description='Evaluate leaderboard predictions for",
"labels, in txt format.\") parser.add_argument('--predictions', '-p', help=\"filename of the leaderboard predictions, in txt",
"in txt format.\") args = parser.parse_args() print(\"reading gold answers\") answers = read_answers(args.answers) print(\"reading",
"'-p', help=\"filename of the leaderboard predictions, in txt format.\") args = parser.parse_args() print(\"reading",
"json import numpy as np def read_answers(filename): answers = {} with open(filename) as",
"argparse parser = argparse.ArgumentParser(description='Evaluate leaderboard predictions for POJ-104 dataset.') parser.add_argument('--answers', '-a', help=\"filename of",
"txt format.\") parser.add_argument('--predictions', '-p', help=\"filename of the leaderboard predictions, in txt format.\") args",
"key not in predictions: logging.error(\"Missing prediction for url {}.\".format(key)) sys.exit() flag = False",
"idx, line in enumerate(f): line = line.strip() js = json.loads(line) answers[str(idx)] = str(idx)",
"= read_predictions(args.predictions) print(\"computing scores\") scores = calculate_scores(answers, predictions) print(scores) if __name__ == '__main__':",
"False for rank, idx in enumerate(predictions[key]): if idx == answers[key]: scores.append(1 / (rank",
"help=\"filename of the leaderboard predictions, in txt format.\") args = parser.parse_args() print(\"reading gold",
"return result def main(): import argparse parser = argparse.ArgumentParser(description='Evaluate leaderboard predictions for POJ-104",
"flag = True break if flag is False: scores.append(0) result = {} result['MRR']",
"import logging import sys, json import numpy as np def read_answers(filename): answers =",
"f: for idx, line in enumerate(f): line = line.strip() js = json.loads(line) answers[str(idx)]",
"return predictions def calculate_scores(answers, predictions): scores = [] for key in answers: #",
"enumerate(f): line = line.strip() js = json.loads(line) answers[str(idx)] = str(idx) return answers def",
"# ipdb.set_trace() if key not in predictions: logging.error(\"Missing prediction for url {}.\".format(key)) sys.exit()",
"read_predictions(args.predictions) print(\"computing scores\") scores = calculate_scores(answers, predictions) print(scores) if __name__ == '__main__': main()",
"in predictions: logging.error(\"Missing prediction for url {}.\".format(key)) sys.exit() flag = False for rank,",
"in txt format.\") parser.add_argument('--predictions', '-p', help=\"filename of the leaderboard predictions, in txt format.\")",
"format.\") args = parser.parse_args() print(\"reading gold answers\") answers = read_answers(args.answers) print(\"reading predcited answers\")",
"= json.loads(line) predictions[str(idx)] = js['answers'] return predictions def calculate_scores(answers, predictions): scores = []",
"import ipdb # ipdb.set_trace() if key not in predictions: logging.error(\"Missing prediction for url",
"parser.add_argument('--predictions', '-p', help=\"filename of the leaderboard predictions, in txt format.\") args = parser.parse_args()",
"is False: scores.append(0) result = {} result['MRR'] = round(np.mean(scores), 4) return result def",
"answers: # import ipdb # ipdb.set_trace() if key not in predictions: logging.error(\"Missing prediction",
"https://github.com/microsoft/CodeXGLUE/blob/main/Text-Code/NL-code-search-Adv/evaluator/evaluator.py import logging import sys, json import numpy as np def read_answers(filename): answers",
"dataset.') parser.add_argument('--answers', '-a', help=\"filename of the labels, in txt format.\") parser.add_argument('--predictions', '-p', help=\"filename",
"[] for key in answers: # import ipdb # ipdb.set_trace() if key not",
"= {} with open(filename) as f: for idx, line in enumerate(f): line =",
"flag = False for rank, idx in enumerate(predictions[key]): if idx == answers[key]: scores.append(1",
"of the labels, in txt format.\") parser.add_argument('--predictions', '-p', help=\"filename of the leaderboard predictions,",
"result def main(): import argparse parser = argparse.ArgumentParser(description='Evaluate leaderboard predictions for POJ-104 dataset.')",
"def main(): import argparse parser = argparse.ArgumentParser(description='Evaluate leaderboard predictions for POJ-104 dataset.') parser.add_argument('--answers',",
"if flag is False: scores.append(0) result = {} result['MRR'] = round(np.mean(scores), 4) return",
"= line.strip() js = json.loads(line) predictions[str(idx)] = js['answers'] return predictions def calculate_scores(answers, predictions):",
"help=\"filename of the labels, in txt format.\") parser.add_argument('--predictions', '-p', help=\"filename of the leaderboard",
"answers\") predictions = read_predictions(args.predictions) print(\"computing scores\") scores = calculate_scores(answers, predictions) print(scores) if __name__",
"= True break if flag is False: scores.append(0) result = {} result['MRR'] =",
"the MIT license. # Adapted from https://github.com/microsoft/CodeXGLUE/blob/main/Text-Code/NL-code-search-Adv/evaluator/evaluator.py import logging import sys, json import",
"= [] for key in answers: # import ipdb # ipdb.set_trace() if key",
"result['MRR'] = round(np.mean(scores), 4) return result def main(): import argparse parser = argparse.ArgumentParser(description='Evaluate",
"str(idx) return answers def read_predictions(filename): predictions = {} with open(filename) as f: for",
"POJ-104 dataset.') parser.add_argument('--answers', '-a', help=\"filename of the labels, in txt format.\") parser.add_argument('--predictions', '-p',",
"rank, idx in enumerate(predictions[key]): if idx == answers[key]: scores.append(1 / (rank + 1))",
"/ (rank + 1)) flag = True break if flag is False: scores.append(0)",
"ipdb # ipdb.set_trace() if key not in predictions: logging.error(\"Missing prediction for url {}.\".format(key))",
"print(\"reading predcited answers\") predictions = read_predictions(args.predictions) print(\"computing scores\") scores = calculate_scores(answers, predictions) print(scores)",
"+ 1)) flag = True break if flag is False: scores.append(0) result =",
"in answers: # import ipdb # ipdb.set_trace() if key not in predictions: logging.error(\"Missing",
"import argparse parser = argparse.ArgumentParser(description='Evaluate leaderboard predictions for POJ-104 dataset.') parser.add_argument('--answers', '-a', help=\"filename",
"for rank, idx in enumerate(predictions[key]): if idx == answers[key]: scores.append(1 / (rank +",
"ipdb.set_trace() if key not in predictions: logging.error(\"Missing prediction for url {}.\".format(key)) sys.exit() flag",
"np def read_answers(filename): answers = {} with open(filename) as f: for idx, line",
"idx, line in enumerate(f): line = line.strip() js = json.loads(line) predictions[str(idx)] = js['answers']",
"with open(filename) as f: for idx, line in enumerate(f): line = line.strip() js",
"gold answers\") answers = read_answers(args.answers) print(\"reading predcited answers\") predictions = read_predictions(args.predictions) print(\"computing scores\")",
"= False for rank, idx in enumerate(predictions[key]): if idx == answers[key]: scores.append(1 /",
"args = parser.parse_args() print(\"reading gold answers\") answers = read_answers(args.answers) print(\"reading predcited answers\") predictions",
"line.strip() js = json.loads(line) answers[str(idx)] = str(idx) return answers def read_predictions(filename): predictions =",
"Licensed under the MIT license. # Adapted from https://github.com/microsoft/CodeXGLUE/blob/main/Text-Code/NL-code-search-Adv/evaluator/evaluator.py import logging import sys,",
"def read_answers(filename): answers = {} with open(filename) as f: for idx, line in",
"logging.error(\"Missing prediction for url {}.\".format(key)) sys.exit() flag = False for rank, idx in",
"calculate_scores(answers, predictions): scores = [] for key in answers: # import ipdb #",
"(c) Microsoft Corporation. # Licensed under the MIT license. # Adapted from https://github.com/microsoft/CodeXGLUE/blob/main/Text-Code/NL-code-search-Adv/evaluator/evaluator.py",
"numpy as np def read_answers(filename): answers = {} with open(filename) as f: for",
"round(np.mean(scores), 4) return result def main(): import argparse parser = argparse.ArgumentParser(description='Evaluate leaderboard predictions",
"predictions[str(idx)] = js['answers'] return predictions def calculate_scores(answers, predictions): scores = [] for key",
"as np def read_answers(filename): answers = {} with open(filename) as f: for idx,",
"import sys, json import numpy as np def read_answers(filename): answers = {} with",
"= json.loads(line) answers[str(idx)] = str(idx) return answers def read_predictions(filename): predictions = {} with",
"{} result['MRR'] = round(np.mean(scores), 4) return result def main(): import argparse parser =",
"print(\"computing scores\") scores = calculate_scores(answers, predictions) print(scores) if __name__ == '__main__': main() #",
"in enumerate(f): line = line.strip() js = json.loads(line) predictions[str(idx)] = js['answers'] return predictions",
"scores.append(0) result = {} result['MRR'] = round(np.mean(scores), 4) return result def main(): import",
"json.loads(line) answers[str(idx)] = str(idx) return answers def read_predictions(filename): predictions = {} with open(filename)",
"if idx == answers[key]: scores.append(1 / (rank + 1)) flag = True break",
"json.loads(line) predictions[str(idx)] = js['answers'] return predictions def calculate_scores(answers, predictions): scores = [] for",
"Corporation. # Licensed under the MIT license. # Adapted from https://github.com/microsoft/CodeXGLUE/blob/main/Text-Code/NL-code-search-Adv/evaluator/evaluator.py import logging",
"import numpy as np def read_answers(filename): answers = {} with open(filename) as f:",
"for key in answers: # import ipdb # ipdb.set_trace() if key not in",
"answers = {} with open(filename) as f: for idx, line in enumerate(f): line",
"js = json.loads(line) predictions[str(idx)] = js['answers'] return predictions def calculate_scores(answers, predictions): scores =",
"key in answers: # import ipdb # ipdb.set_trace() if key not in predictions:",
"predictions: logging.error(\"Missing prediction for url {}.\".format(key)) sys.exit() flag = False for rank, idx",
"False: scores.append(0) result = {} result['MRR'] = round(np.mean(scores), 4) return result def main():",
"predictions for POJ-104 dataset.') parser.add_argument('--answers', '-a', help=\"filename of the labels, in txt format.\")",
"= str(idx) return answers def read_predictions(filename): predictions = {} with open(filename) as f:",
"True break if flag is False: scores.append(0) result = {} result['MRR'] = round(np.mean(scores),",
"for idx, line in enumerate(f): line = line.strip() js = json.loads(line) predictions[str(idx)] =",
"{}.\".format(key)) sys.exit() flag = False for rank, idx in enumerate(predictions[key]): if idx ==",
"prediction for url {}.\".format(key)) sys.exit() flag = False for rank, idx in enumerate(predictions[key]):",
"for idx, line in enumerate(f): line = line.strip() js = json.loads(line) answers[str(idx)] =",
"# Licensed under the MIT license. # Adapted from https://github.com/microsoft/CodeXGLUE/blob/main/Text-Code/NL-code-search-Adv/evaluator/evaluator.py import logging import",
"Adapted from https://github.com/microsoft/CodeXGLUE/blob/main/Text-Code/NL-code-search-Adv/evaluator/evaluator.py import logging import sys, json import numpy as np def",
"of the leaderboard predictions, in txt format.\") args = parser.parse_args() print(\"reading gold answers\")",
"line = line.strip() js = json.loads(line) predictions[str(idx)] = js['answers'] return predictions def calculate_scores(answers,",
"= {} result['MRR'] = round(np.mean(scores), 4) return result def main(): import argparse parser",
"read_predictions(filename): predictions = {} with open(filename) as f: for idx, line in enumerate(f):",
"predictions, in txt format.\") args = parser.parse_args() print(\"reading gold answers\") answers = read_answers(args.answers)",
"js['answers'] return predictions def calculate_scores(answers, predictions): scores = [] for key in answers:",
"1)) flag = True break if flag is False: scores.append(0) result = {}",
"predictions) print(scores) if __name__ == '__main__': main() # python mrr.py -a /home/wasiahmad/workspace/projects/NeuralKpGen/data/scikp/kp20k_separated/KP20k.test.jsonl -p",
"under the MIT license. # Adapted from https://github.com/microsoft/CodeXGLUE/blob/main/Text-Code/NL-code-search-Adv/evaluator/evaluator.py import logging import sys, json",
"= line.strip() js = json.loads(line) answers[str(idx)] = str(idx) return answers def read_predictions(filename): predictions",
"parser = argparse.ArgumentParser(description='Evaluate leaderboard predictions for POJ-104 dataset.') parser.add_argument('--answers', '-a', help=\"filename of the",
"# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. # Adapted",
"flag is False: scores.append(0) result = {} result['MRR'] = round(np.mean(scores), 4) return result",
"logging import sys, json import numpy as np def read_answers(filename): answers = {}",
"answers\") answers = read_answers(args.answers) print(\"reading predcited answers\") predictions = read_predictions(args.predictions) print(\"computing scores\") scores",
"idx == answers[key]: scores.append(1 / (rank + 1)) flag = True break if",
"in enumerate(f): line = line.strip() js = json.loads(line) answers[str(idx)] = str(idx) return answers",
"answers = read_answers(args.answers) print(\"reading predcited answers\") predictions = read_predictions(args.predictions) print(\"computing scores\") scores =",
"predictions = read_predictions(args.predictions) print(\"computing scores\") scores = calculate_scores(answers, predictions) print(scores) if __name__ ==",
"idx in enumerate(predictions[key]): if idx == answers[key]: scores.append(1 / (rank + 1)) flag",
"in enumerate(predictions[key]): if idx == answers[key]: scores.append(1 / (rank + 1)) flag =",
"line in enumerate(f): line = line.strip() js = json.loads(line) predictions[str(idx)] = js['answers'] return",
"parser.add_argument('--answers', '-a', help=\"filename of the labels, in txt format.\") parser.add_argument('--predictions', '-p', help=\"filename of",
"scores\") scores = calculate_scores(answers, predictions) print(scores) if __name__ == '__main__': main() # python",
"def read_predictions(filename): predictions = {} with open(filename) as f: for idx, line in",
"predcited answers\") predictions = read_predictions(args.predictions) print(\"computing scores\") scores = calculate_scores(answers, predictions) print(scores) if",
"the labels, in txt format.\") parser.add_argument('--predictions', '-p', help=\"filename of the leaderboard predictions, in",
"open(filename) as f: for idx, line in enumerate(f): line = line.strip() js =",
"'-a', help=\"filename of the labels, in txt format.\") parser.add_argument('--predictions', '-p', help=\"filename of the",
"result = {} result['MRR'] = round(np.mean(scores), 4) return result def main(): import argparse",
"leaderboard predictions for POJ-104 dataset.') parser.add_argument('--answers', '-a', help=\"filename of the labels, in txt",
"js = json.loads(line) answers[str(idx)] = str(idx) return answers def read_predictions(filename): predictions = {}",
"MIT license. # Adapted from https://github.com/microsoft/CodeXGLUE/blob/main/Text-Code/NL-code-search-Adv/evaluator/evaluator.py import logging import sys, json import numpy",
"not in predictions: logging.error(\"Missing prediction for url {}.\".format(key)) sys.exit() flag = False for",
"read_answers(args.answers) print(\"reading predcited answers\") predictions = read_predictions(args.predictions) print(\"computing scores\") scores = calculate_scores(answers, predictions)",
"answers[key]: scores.append(1 / (rank + 1)) flag = True break if flag is",
"calculate_scores(answers, predictions) print(scores) if __name__ == '__main__': main() # python mrr.py -a /home/wasiahmad/workspace/projects/NeuralKpGen/data/scikp/kp20k_separated/KP20k.test.jsonl",
"print(\"reading gold answers\") answers = read_answers(args.answers) print(\"reading predcited answers\") predictions = read_predictions(args.predictions) print(\"computing",
"line in enumerate(f): line = line.strip() js = json.loads(line) answers[str(idx)] = str(idx) return",
"leaderboard predictions, in txt format.\") args = parser.parse_args() print(\"reading gold answers\") answers =",
"url {}.\".format(key)) sys.exit() flag = False for rank, idx in enumerate(predictions[key]): if idx",
"scores.append(1 / (rank + 1)) flag = True break if flag is False:",
"= calculate_scores(answers, predictions) print(scores) if __name__ == '__main__': main() # python mrr.py -a",
"line = line.strip() js = json.loads(line) answers[str(idx)] = str(idx) return answers def read_predictions(filename):",
"parser.parse_args() print(\"reading gold answers\") answers = read_answers(args.answers) print(\"reading predcited answers\") predictions = read_predictions(args.predictions)",
"print(scores) if __name__ == '__main__': main() # python mrr.py -a /home/wasiahmad/workspace/projects/NeuralKpGen/data/scikp/kp20k_separated/KP20k.test.jsonl -p /home/rizwan/DPR/predictions_KP20k.jsonl",
"argparse.ArgumentParser(description='Evaluate leaderboard predictions for POJ-104 dataset.') parser.add_argument('--answers', '-a', help=\"filename of the labels, in",
"{} with open(filename) as f: for idx, line in enumerate(f): line = line.strip()",
"# import ipdb # ipdb.set_trace() if key not in predictions: logging.error(\"Missing prediction for",
"predictions def calculate_scores(answers, predictions): scores = [] for key in answers: # import"
] |
[
"self._value -= 1 def set(self, amount: int): with self._lock: self._value += amount def",
"return self._value def increment(self): with self._lock: self._value += 1 def decrement(self): with self._lock:",
"def increment(self): with self._lock: self._value += 1 def decrement(self): with self._lock: self._value -=",
"# class LongAdder: def __init__(self): self._lock = threading.Lock() self._value = 0 def get_value(self):",
"import threading # # @author andy # class LongAdder: def __init__(self): self._lock =",
"def __init__(self): self._lock = threading.Lock() self._value = 0 def get_value(self): return self._value def",
"self._lock = threading.Lock() self._value = 0 def get_value(self): return self._value def increment(self): with",
"1 def set(self, amount: int): with self._lock: self._value += amount def reset(self): with",
"decrement(self): with self._lock: self._value -= 1 def set(self, amount: int): with self._lock: self._value",
"increment(self): with self._lock: self._value += 1 def decrement(self): with self._lock: self._value -= 1",
"1 def decrement(self): with self._lock: self._value -= 1 def set(self, amount: int): with",
"amount: int): with self._lock: self._value += amount def reset(self): with self._lock: self._value =",
"self._value def increment(self): with self._lock: self._value += 1 def decrement(self): with self._lock: self._value",
"+= 1 def decrement(self): with self._lock: self._value -= 1 def set(self, amount: int):",
"andy # class LongAdder: def __init__(self): self._lock = threading.Lock() self._value = 0 def",
"get_value(self): return self._value def increment(self): with self._lock: self._value += 1 def decrement(self): with",
"int): with self._lock: self._value += amount def reset(self): with self._lock: self._value = 0",
"LongAdder: def __init__(self): self._lock = threading.Lock() self._value = 0 def get_value(self): return self._value",
"class LongAdder: def __init__(self): self._lock = threading.Lock() self._value = 0 def get_value(self): return",
"threading.Lock() self._value = 0 def get_value(self): return self._value def increment(self): with self._lock: self._value",
"# @author andy # class LongAdder: def __init__(self): self._lock = threading.Lock() self._value =",
"def get_value(self): return self._value def increment(self): with self._lock: self._value += 1 def decrement(self):",
"self._value = 0 def get_value(self): return self._value def increment(self): with self._lock: self._value +=",
"threading # # @author andy # class LongAdder: def __init__(self): self._lock = threading.Lock()",
"def decrement(self): with self._lock: self._value -= 1 def set(self, amount: int): with self._lock:",
"= threading.Lock() self._value = 0 def get_value(self): return self._value def increment(self): with self._lock:",
"with self._lock: self._value += 1 def decrement(self): with self._lock: self._value -= 1 def",
"self._value += 1 def decrement(self): with self._lock: self._value -= 1 def set(self, amount:",
"# # @author andy # class LongAdder: def __init__(self): self._lock = threading.Lock() self._value",
"set(self, amount: int): with self._lock: self._value += amount def reset(self): with self._lock: self._value",
"def set(self, amount: int): with self._lock: self._value += amount def reset(self): with self._lock:",
"= 0 def get_value(self): return self._value def increment(self): with self._lock: self._value += 1",
"@author andy # class LongAdder: def __init__(self): self._lock = threading.Lock() self._value = 0",
"__init__(self): self._lock = threading.Lock() self._value = 0 def get_value(self): return self._value def increment(self):",
"self._lock: self._value -= 1 def set(self, amount: int): with self._lock: self._value += amount",
"self._lock: self._value += 1 def decrement(self): with self._lock: self._value -= 1 def set(self,",
"-= 1 def set(self, amount: int): with self._lock: self._value += amount def reset(self):",
"with self._lock: self._value -= 1 def set(self, amount: int): with self._lock: self._value +=",
"0 def get_value(self): return self._value def increment(self): with self._lock: self._value += 1 def"
] |
[
"CorpusRegistry() # this has to be at the bottom to avoid circular references",
"from randompoetry import PoemFormRegistry, CorpusRegistry app = Flask(__name__) app.config.from_object(Config) pfr = PoemFormRegistry.from_json('poemforms.json') cr",
"PoemFormRegistry, CorpusRegistry app = Flask(__name__) app.config.from_object(Config) pfr = PoemFormRegistry.from_json('poemforms.json') cr = CorpusRegistry() #",
"Config from randompoetry import PoemFormRegistry, CorpusRegistry app = Flask(__name__) app.config.from_object(Config) pfr = PoemFormRegistry.from_json('poemforms.json')",
"app = Flask(__name__) app.config.from_object(Config) pfr = PoemFormRegistry.from_json('poemforms.json') cr = CorpusRegistry() # this has",
"= PoemFormRegistry.from_json('poemforms.json') cr = CorpusRegistry() # this has to be at the bottom",
"flask import Flask from config import Config from randompoetry import PoemFormRegistry, CorpusRegistry app",
"<filename>app/__init__.py from flask import Flask from config import Config from randompoetry import PoemFormRegistry,",
"PoemFormRegistry.from_json('poemforms.json') cr = CorpusRegistry() # this has to be at the bottom to",
"randompoetry import PoemFormRegistry, CorpusRegistry app = Flask(__name__) app.config.from_object(Config) pfr = PoemFormRegistry.from_json('poemforms.json') cr =",
"# this has to be at the bottom to avoid circular references from",
"from config import Config from randompoetry import PoemFormRegistry, CorpusRegistry app = Flask(__name__) app.config.from_object(Config)",
"CorpusRegistry app = Flask(__name__) app.config.from_object(Config) pfr = PoemFormRegistry.from_json('poemforms.json') cr = CorpusRegistry() # this",
"config import Config from randompoetry import PoemFormRegistry, CorpusRegistry app = Flask(__name__) app.config.from_object(Config) pfr",
"= CorpusRegistry() # this has to be at the bottom to avoid circular",
"app.config.from_object(Config) pfr = PoemFormRegistry.from_json('poemforms.json') cr = CorpusRegistry() # this has to be at",
"has to be at the bottom to avoid circular references from app import",
"this has to be at the bottom to avoid circular references from app",
"= Flask(__name__) app.config.from_object(Config) pfr = PoemFormRegistry.from_json('poemforms.json') cr = CorpusRegistry() # this has to",
"import PoemFormRegistry, CorpusRegistry app = Flask(__name__) app.config.from_object(Config) pfr = PoemFormRegistry.from_json('poemforms.json') cr = CorpusRegistry()",
"from flask import Flask from config import Config from randompoetry import PoemFormRegistry, CorpusRegistry",
"import Flask from config import Config from randompoetry import PoemFormRegistry, CorpusRegistry app =",
"Flask from config import Config from randompoetry import PoemFormRegistry, CorpusRegistry app = Flask(__name__)",
"to be at the bottom to avoid circular references from app import routes",
"pfr = PoemFormRegistry.from_json('poemforms.json') cr = CorpusRegistry() # this has to be at the",
"Flask(__name__) app.config.from_object(Config) pfr = PoemFormRegistry.from_json('poemforms.json') cr = CorpusRegistry() # this has to be",
"import Config from randompoetry import PoemFormRegistry, CorpusRegistry app = Flask(__name__) app.config.from_object(Config) pfr =",
"cr = CorpusRegistry() # this has to be at the bottom to avoid"
] |
[
"= rospy.Time.now() + rospy.Duration(0.2) traj_msg.trajectory.joint_names = ['JOINT0', 'JOINT1', 'JOINT2', 'JOINT3', 'JOINT4', 'JOINT5', 'JOINT6',",
"%f -(%f)-> max %f'%(msg.angle_min, msg.angle_increment, msg.angle_max)) # トピック名,メッセージ型を使って ActionLib client を定義 client =",
"'JOINT13', 'JOINT14', 'JOINT15', 'JOINT16', 'JOINT17', 'JOINT18', 'JOINT19', 'JOINT20', 'JOINT21', 'JOINT22', 'JOINT23', 'JOINT24', 'JOINT25',",
"#!/usr/bin/env python # -*- coding: utf-8 -*- import rospy import actionlib import math",
"client.wait_for_result() #ロボットの動作が終わるまで待つ rospy.loginfo(\"done\") if __name__ == '__main__': rospy.init_node('range_listener', anonymous=True) rospy.Subscriber(\"/range_sensor\", LaserScan, callback) rospy.spin()",
"= JointTrajectory() traj_msg.trajectory.header.stamp = rospy.Time.now() + rospy.Duration(0.2) traj_msg.trajectory.joint_names = ['JOINT0', 'JOINT1', 'JOINT2', 'JOINT3',",
"'JOINT29'] global i val = int(-msg.angle_min / msg.angle_increment) if (msg.ranges[val] < 100): i",
"rospy.Duration(1.0 + i))) #目標姿勢をゴールとして送信 client.send_goal(traj_msg) rospy.loginfo(\"wait for goal ...\") client.wait_for_result() #ロボットの動作が終わるまで待つ rospy.loginfo(\"done\") if",
"coding: utf-8 -*- import rospy import actionlib import math from trajectory_msgs.msg import JointTrajectry",
"%f'%(msg.angle_min, msg.angle_increment, msg.angle_max)) # トピック名,メッセージ型を使って ActionLib client を定義 client = actionlib.SimpleActionClient('/fullbody_controller/follow_joint_trajectory', FollowJointTrajectoryAction) client.wait_for_server()",
"i, 0, 0, 0, 0, i, 0, i], time_from_start = rospy.Duration(1.0 + i)))",
"import JointTrajectry from trajectry_msgs.msg import JointTrajectoryPoint from control_msgs.msg import JointTrajectory from sensor_msgs.msg import",
"'JOINT21', 'JOINT22', 'JOINT23', 'JOINT24', 'JOINT25', 'JOINT26', 'JOINT27', 'JOINT28', 'JOINT29'] global i val =",
"import rospy import actionlib import math from trajectory_msgs.msg import JointTrajectry from trajectry_msgs.msg import",
"= int(-msg.angle_min / msg.angle_increment) if (msg.ranges[val] < 100): i += 1 traj_msg.trajectory.points.append(JointTrajectoryPoint(positions=[0, 0,",
"from control_msgs.msg import JointTrajectory from sensor_msgs.msg import LaserScan i=0 def callback(msg): rospy.loginfo('min %f",
"FollowJointTrajectoryGoal() traj_msg.trajectory = JointTrajectory() traj_msg.trajectory.header.stamp = rospy.Time.now() + rospy.Duration(0.2) traj_msg.trajectory.joint_names = ['JOINT0', 'JOINT1',",
"0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,",
"/ msg.angle_increment) if (msg.ranges[val] < 100): i += 1 traj_msg.trajectory.points.append(JointTrajectoryPoint(positions=[0, 0, 0, 0,",
"JointTrajectory from sensor_msgs.msg import LaserScan i=0 def callback(msg): rospy.loginfo('min %f -(%f)-> max %f'%(msg.angle_min,",
"msg traj_msg = FollowJointTrajectoryGoal() traj_msg.trajectory = JointTrajectory() traj_msg.trajectory.header.stamp = rospy.Time.now() + rospy.Duration(0.2) traj_msg.trajectory.joint_names",
"0, 0, 0, i, 0, i], time_from_start = rospy.Duration(1.0 + i))) #目標姿勢をゴールとして送信 client.send_goal(traj_msg)",
"from trajectory_msgs.msg import JointTrajectry from trajectry_msgs.msg import JointTrajectoryPoint from control_msgs.msg import JointTrajectory from",
"int(-msg.angle_min / msg.angle_increment) if (msg.ranges[val] < 100): i += 1 traj_msg.trajectory.points.append(JointTrajectoryPoint(positions=[0, 0, 0,",
"'JOINT3', 'JOINT4', 'JOINT5', 'JOINT6', 'JOINT7', 'JOINT8', 'JOINT9', 'JOINT10', 'JOINT11', 'JOINT12', 'JOINT13', 'JOINT14', 'JOINT15',",
"# -*- coding: utf-8 -*- import rospy import actionlib import math from trajectory_msgs.msg",
"'JOINT18', 'JOINT19', 'JOINT20', 'JOINT21', 'JOINT22', 'JOINT23', 'JOINT24', 'JOINT25', 'JOINT26', 'JOINT27', 'JOINT28', 'JOINT29'] global",
"import math from trajectory_msgs.msg import JointTrajectry from trajectry_msgs.msg import JointTrajectoryPoint from control_msgs.msg import",
"control_msgs.msg import JointTrajectory from sensor_msgs.msg import LaserScan i=0 def callback(msg): rospy.loginfo('min %f -(%f)->",
"# gen msg traj_msg = FollowJointTrajectoryGoal() traj_msg.trajectory = JointTrajectory() traj_msg.trajectory.header.stamp = rospy.Time.now() +",
"+ i))) #目標姿勢をゴールとして送信 client.send_goal(traj_msg) rospy.loginfo(\"wait for goal ...\") client.wait_for_result() #ロボットの動作が終わるまで待つ rospy.loginfo(\"done\") if __name__",
"client.wait_for_server() # ActionLib のサーバと通信が接続されることを確認 # gen msg traj_msg = FollowJointTrajectoryGoal() traj_msg.trajectory = JointTrajectory()",
"client.send_goal(traj_msg) rospy.loginfo(\"wait for goal ...\") client.wait_for_result() #ロボットの動作が終わるまで待つ rospy.loginfo(\"done\") if __name__ == '__main__': rospy.init_node('range_listener',",
"= rospy.Duration(1.0 + i))) #目標姿勢をゴールとして送信 client.send_goal(traj_msg) rospy.loginfo(\"wait for goal ...\") client.wait_for_result() #ロボットの動作が終わるまで待つ rospy.loginfo(\"done\")",
"gen msg traj_msg = FollowJointTrajectoryGoal() traj_msg.trajectory = JointTrajectory() traj_msg.trajectory.header.stamp = rospy.Time.now() + rospy.Duration(0.2)",
"ActionLib のサーバと通信が接続されることを確認 # gen msg traj_msg = FollowJointTrajectoryGoal() traj_msg.trajectory = JointTrajectory() traj_msg.trajectory.header.stamp =",
"'JOINT20', 'JOINT21', 'JOINT22', 'JOINT23', 'JOINT24', 'JOINT25', 'JOINT26', 'JOINT27', 'JOINT28', 'JOINT29'] global i val",
"0, i, 0, i], time_from_start = rospy.Duration(1.0 + i))) #目標姿勢をゴールとして送信 client.send_goal(traj_msg) rospy.loginfo(\"wait for",
"+= 1 traj_msg.trajectory.points.append(JointTrajectoryPoint(positions=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,",
"0, 0, 0, i, 0, i, 0, 0, 0, 0, i, 0, i],",
"0, 0, 0, 0, 0, 0, 0, 0, i, 0, i, 0, 0,",
"if (msg.ranges[val] < 100): i += 1 traj_msg.trajectory.points.append(JointTrajectoryPoint(positions=[0, 0, 0, 0, 0, 0,",
"global i val = int(-msg.angle_min / msg.angle_increment) if (msg.ranges[val] < 100): i +=",
"i, 0, i, 0, 0, 0, 0, i, 0, i], time_from_start = rospy.Duration(1.0",
"'JOINT11', 'JOINT12', 'JOINT13', 'JOINT14', 'JOINT15', 'JOINT16', 'JOINT17', 'JOINT18', 'JOINT19', 'JOINT20', 'JOINT21', 'JOINT22', 'JOINT23',",
"i, 0, i], time_from_start = rospy.Duration(1.0 + i))) #目標姿勢をゴールとして送信 client.send_goal(traj_msg) rospy.loginfo(\"wait for goal",
"'JOINT5', 'JOINT6', 'JOINT7', 'JOINT8', 'JOINT9', 'JOINT10', 'JOINT11', 'JOINT12', 'JOINT13', 'JOINT14', 'JOINT15', 'JOINT16', 'JOINT17',",
"JointTrajectoryPoint from control_msgs.msg import JointTrajectory from sensor_msgs.msg import LaserScan i=0 def callback(msg): rospy.loginfo('min",
"0, i, 0, i, 0, 0, 0, 0, i, 0, i], time_from_start =",
"msg.angle_max)) # トピック名,メッセージ型を使って ActionLib client を定義 client = actionlib.SimpleActionClient('/fullbody_controller/follow_joint_trajectory', FollowJointTrajectoryAction) client.wait_for_server() # ActionLib",
"for goal ...\") client.wait_for_result() #ロボットの動作が終わるまで待つ rospy.loginfo(\"done\") if __name__ == '__main__': rospy.init_node('range_listener', anonymous=True) rospy.Subscriber(\"/range_sensor\",",
"'JOINT4', 'JOINT5', 'JOINT6', 'JOINT7', 'JOINT8', 'JOINT9', 'JOINT10', 'JOINT11', 'JOINT12', 'JOINT13', 'JOINT14', 'JOINT15', 'JOINT16',",
"callback(msg): rospy.loginfo('min %f -(%f)-> max %f'%(msg.angle_min, msg.angle_increment, msg.angle_max)) # トピック名,メッセージ型を使って ActionLib client を定義",
"import JointTrajectory from sensor_msgs.msg import LaserScan i=0 def callback(msg): rospy.loginfo('min %f -(%f)-> max",
"i))) #目標姿勢をゴールとして送信 client.send_goal(traj_msg) rospy.loginfo(\"wait for goal ...\") client.wait_for_result() #ロボットの動作が終わるまで待つ rospy.loginfo(\"done\") if __name__ ==",
"0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, i, 0,",
"を定義 client = actionlib.SimpleActionClient('/fullbody_controller/follow_joint_trajectory', FollowJointTrajectoryAction) client.wait_for_server() # ActionLib のサーバと通信が接続されることを確認 # gen msg traj_msg",
"msg.angle_increment, msg.angle_max)) # トピック名,メッセージ型を使って ActionLib client を定義 client = actionlib.SimpleActionClient('/fullbody_controller/follow_joint_trajectory', FollowJointTrajectoryAction) client.wait_for_server() #",
"'JOINT28', 'JOINT29'] global i val = int(-msg.angle_min / msg.angle_increment) if (msg.ranges[val] < 100):",
"trajectry_msgs.msg import JointTrajectoryPoint from control_msgs.msg import JointTrajectory from sensor_msgs.msg import LaserScan i=0 def",
"0, 0, 0, 0, 0, 0, 0, i, 0, i, 0, 0, 0,",
"'JOINT19', 'JOINT20', 'JOINT21', 'JOINT22', 'JOINT23', 'JOINT24', 'JOINT25', 'JOINT26', 'JOINT27', 'JOINT28', 'JOINT29'] global i",
"traj_msg.trajectory.joint_names = ['JOINT0', 'JOINT1', 'JOINT2', 'JOINT3', 'JOINT4', 'JOINT5', 'JOINT6', 'JOINT7', 'JOINT8', 'JOINT9', 'JOINT10',",
"utf-8 -*- import rospy import actionlib import math from trajectory_msgs.msg import JointTrajectry from",
"sensor_msgs.msg import LaserScan i=0 def callback(msg): rospy.loginfo('min %f -(%f)-> max %f'%(msg.angle_min, msg.angle_increment, msg.angle_max))",
"'JOINT25', 'JOINT26', 'JOINT27', 'JOINT28', 'JOINT29'] global i val = int(-msg.angle_min / msg.angle_increment) if",
"FollowJointTrajectoryAction) client.wait_for_server() # ActionLib のサーバと通信が接続されることを確認 # gen msg traj_msg = FollowJointTrajectoryGoal() traj_msg.trajectory =",
"ActionLib client を定義 client = actionlib.SimpleActionClient('/fullbody_controller/follow_joint_trajectory', FollowJointTrajectoryAction) client.wait_for_server() # ActionLib のサーバと通信が接続されることを確認 # gen",
"from trajectry_msgs.msg import JointTrajectoryPoint from control_msgs.msg import JointTrajectory from sensor_msgs.msg import LaserScan i=0",
"< 100): i += 1 traj_msg.trajectory.points.append(JointTrajectoryPoint(positions=[0, 0, 0, 0, 0, 0, 0, 0,",
"0, 0, 0, 0, 0, i, 0, i, 0, 0, 0, 0, i,",
"'JOINT24', 'JOINT25', 'JOINT26', 'JOINT27', 'JOINT28', 'JOINT29'] global i val = int(-msg.angle_min / msg.angle_increment)",
"i += 1 traj_msg.trajectory.points.append(JointTrajectoryPoint(positions=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0,",
"0, 0, 0, 0, 0, 0, 0, 0, 0, i, 0, i, 0,",
"0, 0, 0, 0, 0, 0, 0, 0, 0, 0, i, 0, i,",
"'JOINT1', 'JOINT2', 'JOINT3', 'JOINT4', 'JOINT5', 'JOINT6', 'JOINT7', 'JOINT8', 'JOINT9', 'JOINT10', 'JOINT11', 'JOINT12', 'JOINT13',",
"'JOINT17', 'JOINT18', 'JOINT19', 'JOINT20', 'JOINT21', 'JOINT22', 'JOINT23', 'JOINT24', 'JOINT25', 'JOINT26', 'JOINT27', 'JOINT28', 'JOINT29']",
"rospy.loginfo(\"wait for goal ...\") client.wait_for_result() #ロボットの動作が終わるまで待つ rospy.loginfo(\"done\") if __name__ == '__main__': rospy.init_node('range_listener', anonymous=True)",
"i], time_from_start = rospy.Duration(1.0 + i))) #目標姿勢をゴールとして送信 client.send_goal(traj_msg) rospy.loginfo(\"wait for goal ...\") client.wait_for_result()",
"'JOINT10', 'JOINT11', 'JOINT12', 'JOINT13', 'JOINT14', 'JOINT15', 'JOINT16', 'JOINT17', 'JOINT18', 'JOINT19', 'JOINT20', 'JOINT21', 'JOINT22',",
"0, i, 0, 0, 0, 0, i, 0, i], time_from_start = rospy.Duration(1.0 +",
"'JOINT2', 'JOINT3', 'JOINT4', 'JOINT5', 'JOINT6', 'JOINT7', 'JOINT8', 'JOINT9', 'JOINT10', 'JOINT11', 'JOINT12', 'JOINT13', 'JOINT14',",
"# トピック名,メッセージ型を使って ActionLib client を定義 client = actionlib.SimpleActionClient('/fullbody_controller/follow_joint_trajectory', FollowJointTrajectoryAction) client.wait_for_server() # ActionLib のサーバと通信が接続されることを確認",
"client を定義 client = actionlib.SimpleActionClient('/fullbody_controller/follow_joint_trajectory', FollowJointTrajectoryAction) client.wait_for_server() # ActionLib のサーバと通信が接続されることを確認 # gen msg",
"#目標姿勢をゴールとして送信 client.send_goal(traj_msg) rospy.loginfo(\"wait for goal ...\") client.wait_for_result() #ロボットの動作が終わるまで待つ rospy.loginfo(\"done\") if __name__ == '__main__':",
"(msg.ranges[val] < 100): i += 1 traj_msg.trajectory.points.append(JointTrajectoryPoint(positions=[0, 0, 0, 0, 0, 0, 0,",
"LaserScan i=0 def callback(msg): rospy.loginfo('min %f -(%f)-> max %f'%(msg.angle_min, msg.angle_increment, msg.angle_max)) # トピック名,メッセージ型を使って",
"0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, i,",
"0, 0, 0, 0, i, 0, i], time_from_start = rospy.Duration(1.0 + i))) #目標姿勢をゴールとして送信",
"トピック名,メッセージ型を使って ActionLib client を定義 client = actionlib.SimpleActionClient('/fullbody_controller/follow_joint_trajectory', FollowJointTrajectoryAction) client.wait_for_server() # ActionLib のサーバと通信が接続されることを確認 #",
"rospy import actionlib import math from trajectory_msgs.msg import JointTrajectry from trajectry_msgs.msg import JointTrajectoryPoint",
"import actionlib import math from trajectory_msgs.msg import JointTrajectry from trajectry_msgs.msg import JointTrajectoryPoint from",
"のサーバと通信が接続されることを確認 # gen msg traj_msg = FollowJointTrajectoryGoal() traj_msg.trajectory = JointTrajectory() traj_msg.trajectory.header.stamp = rospy.Time.now()",
"= FollowJointTrajectoryGoal() traj_msg.trajectory = JointTrajectory() traj_msg.trajectory.header.stamp = rospy.Time.now() + rospy.Duration(0.2) traj_msg.trajectory.joint_names = ['JOINT0',",
"100): i += 1 traj_msg.trajectory.points.append(JointTrajectoryPoint(positions=[0, 0, 0, 0, 0, 0, 0, 0, 0,",
"= actionlib.SimpleActionClient('/fullbody_controller/follow_joint_trajectory', FollowJointTrajectoryAction) client.wait_for_server() # ActionLib のサーバと通信が接続されることを確認 # gen msg traj_msg = FollowJointTrajectoryGoal()",
"time_from_start = rospy.Duration(1.0 + i))) #目標姿勢をゴールとして送信 client.send_goal(traj_msg) rospy.loginfo(\"wait for goal ...\") client.wait_for_result() #ロボットの動作が終わるまで待つ",
"goal ...\") client.wait_for_result() #ロボットの動作が終わるまで待つ rospy.loginfo(\"done\") if __name__ == '__main__': rospy.init_node('range_listener', anonymous=True) rospy.Subscriber(\"/range_sensor\", LaserScan,",
"-*- import rospy import actionlib import math from trajectory_msgs.msg import JointTrajectry from trajectry_msgs.msg",
"'JOINT8', 'JOINT9', 'JOINT10', 'JOINT11', 'JOINT12', 'JOINT13', 'JOINT14', 'JOINT15', 'JOINT16', 'JOINT17', 'JOINT18', 'JOINT19', 'JOINT20',",
"trajectory_msgs.msg import JointTrajectry from trajectry_msgs.msg import JointTrajectoryPoint from control_msgs.msg import JointTrajectory from sensor_msgs.msg",
"traj_msg.trajectory.header.stamp = rospy.Time.now() + rospy.Duration(0.2) traj_msg.trajectory.joint_names = ['JOINT0', 'JOINT1', 'JOINT2', 'JOINT3', 'JOINT4', 'JOINT5',",
"+ rospy.Duration(0.2) traj_msg.trajectory.joint_names = ['JOINT0', 'JOINT1', 'JOINT2', 'JOINT3', 'JOINT4', 'JOINT5', 'JOINT6', 'JOINT7', 'JOINT8',",
"from sensor_msgs.msg import LaserScan i=0 def callback(msg): rospy.loginfo('min %f -(%f)-> max %f'%(msg.angle_min, msg.angle_increment,",
"'JOINT22', 'JOINT23', 'JOINT24', 'JOINT25', 'JOINT26', 'JOINT27', 'JOINT28', 'JOINT29'] global i val = int(-msg.angle_min",
"traj_msg.trajectory.points.append(JointTrajectoryPoint(positions=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,",
"0, 0, i, 0, i, 0, 0, 0, 0, i, 0, i], time_from_start",
"'JOINT9', 'JOINT10', 'JOINT11', 'JOINT12', 'JOINT13', 'JOINT14', 'JOINT15', 'JOINT16', 'JOINT17', 'JOINT18', 'JOINT19', 'JOINT20', 'JOINT21',",
"1 traj_msg.trajectory.points.append(JointTrajectoryPoint(positions=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,",
"i=0 def callback(msg): rospy.loginfo('min %f -(%f)-> max %f'%(msg.angle_min, msg.angle_increment, msg.angle_max)) # トピック名,メッセージ型を使って ActionLib",
"'JOINT7', 'JOINT8', 'JOINT9', 'JOINT10', 'JOINT11', 'JOINT12', 'JOINT13', 'JOINT14', 'JOINT15', 'JOINT16', 'JOINT17', 'JOINT18', 'JOINT19',",
"python # -*- coding: utf-8 -*- import rospy import actionlib import math from",
"max %f'%(msg.angle_min, msg.angle_increment, msg.angle_max)) # トピック名,メッセージ型を使って ActionLib client を定義 client = actionlib.SimpleActionClient('/fullbody_controller/follow_joint_trajectory', FollowJointTrajectoryAction)",
"= ['JOINT0', 'JOINT1', 'JOINT2', 'JOINT3', 'JOINT4', 'JOINT5', 'JOINT6', 'JOINT7', 'JOINT8', 'JOINT9', 'JOINT10', 'JOINT11',",
"# ActionLib のサーバと通信が接続されることを確認 # gen msg traj_msg = FollowJointTrajectoryGoal() traj_msg.trajectory = JointTrajectory() traj_msg.trajectory.header.stamp",
"'JOINT15', 'JOINT16', 'JOINT17', 'JOINT18', 'JOINT19', 'JOINT20', 'JOINT21', 'JOINT22', 'JOINT23', 'JOINT24', 'JOINT25', 'JOINT26', 'JOINT27',",
"'JOINT16', 'JOINT17', 'JOINT18', 'JOINT19', 'JOINT20', 'JOINT21', 'JOINT22', 'JOINT23', 'JOINT24', 'JOINT25', 'JOINT26', 'JOINT27', 'JOINT28',",
"'JOINT23', 'JOINT24', 'JOINT25', 'JOINT26', 'JOINT27', 'JOINT28', 'JOINT29'] global i val = int(-msg.angle_min /",
"0, 0, i, 0, i], time_from_start = rospy.Duration(1.0 + i))) #目標姿勢をゴールとして送信 client.send_goal(traj_msg) rospy.loginfo(\"wait",
"import JointTrajectoryPoint from control_msgs.msg import JointTrajectory from sensor_msgs.msg import LaserScan i=0 def callback(msg):",
"traj_msg.trajectory = JointTrajectory() traj_msg.trajectory.header.stamp = rospy.Time.now() + rospy.Duration(0.2) traj_msg.trajectory.joint_names = ['JOINT0', 'JOINT1', 'JOINT2',",
"math from trajectory_msgs.msg import JointTrajectry from trajectry_msgs.msg import JointTrajectoryPoint from control_msgs.msg import JointTrajectory",
"rospy.Duration(0.2) traj_msg.trajectory.joint_names = ['JOINT0', 'JOINT1', 'JOINT2', 'JOINT3', 'JOINT4', 'JOINT5', 'JOINT6', 'JOINT7', 'JOINT8', 'JOINT9',",
"i val = int(-msg.angle_min / msg.angle_increment) if (msg.ranges[val] < 100): i += 1",
"'JOINT14', 'JOINT15', 'JOINT16', 'JOINT17', 'JOINT18', 'JOINT19', 'JOINT20', 'JOINT21', 'JOINT22', 'JOINT23', 'JOINT24', 'JOINT25', 'JOINT26',",
"...\") client.wait_for_result() #ロボットの動作が終わるまで待つ rospy.loginfo(\"done\") if __name__ == '__main__': rospy.init_node('range_listener', anonymous=True) rospy.Subscriber(\"/range_sensor\", LaserScan, callback)",
"JointTrajectory() traj_msg.trajectory.header.stamp = rospy.Time.now() + rospy.Duration(0.2) traj_msg.trajectory.joint_names = ['JOINT0', 'JOINT1', 'JOINT2', 'JOINT3', 'JOINT4',",
"def callback(msg): rospy.loginfo('min %f -(%f)-> max %f'%(msg.angle_min, msg.angle_increment, msg.angle_max)) # トピック名,メッセージ型を使って ActionLib client",
"client = actionlib.SimpleActionClient('/fullbody_controller/follow_joint_trajectory', FollowJointTrajectoryAction) client.wait_for_server() # ActionLib のサーバと通信が接続されることを確認 # gen msg traj_msg =",
"0, 0, 0, 0, i, 0, i, 0, 0, 0, 0, i, 0,",
"'JOINT6', 'JOINT7', 'JOINT8', 'JOINT9', 'JOINT10', 'JOINT11', 'JOINT12', 'JOINT13', 'JOINT14', 'JOINT15', 'JOINT16', 'JOINT17', 'JOINT18',",
"actionlib.SimpleActionClient('/fullbody_controller/follow_joint_trajectory', FollowJointTrajectoryAction) client.wait_for_server() # ActionLib のサーバと通信が接続されることを確認 # gen msg traj_msg = FollowJointTrajectoryGoal() traj_msg.trajectory",
"import LaserScan i=0 def callback(msg): rospy.loginfo('min %f -(%f)-> max %f'%(msg.angle_min, msg.angle_increment, msg.angle_max)) #",
"rospy.Time.now() + rospy.Duration(0.2) traj_msg.trajectory.joint_names = ['JOINT0', 'JOINT1', 'JOINT2', 'JOINT3', 'JOINT4', 'JOINT5', 'JOINT6', 'JOINT7',",
"'JOINT26', 'JOINT27', 'JOINT28', 'JOINT29'] global i val = int(-msg.angle_min / msg.angle_increment) if (msg.ranges[val]",
"0, 0, 0, 0, 0, 0, i, 0, i, 0, 0, 0, 0,",
"-(%f)-> max %f'%(msg.angle_min, msg.angle_increment, msg.angle_max)) # トピック名,メッセージ型を使って ActionLib client を定義 client = actionlib.SimpleActionClient('/fullbody_controller/follow_joint_trajectory',",
"-*- coding: utf-8 -*- import rospy import actionlib import math from trajectory_msgs.msg import",
"['JOINT0', 'JOINT1', 'JOINT2', 'JOINT3', 'JOINT4', 'JOINT5', 'JOINT6', 'JOINT7', 'JOINT8', 'JOINT9', 'JOINT10', 'JOINT11', 'JOINT12',",
"msg.angle_increment) if (msg.ranges[val] < 100): i += 1 traj_msg.trajectory.points.append(JointTrajectoryPoint(positions=[0, 0, 0, 0, 0,",
"rospy.loginfo('min %f -(%f)-> max %f'%(msg.angle_min, msg.angle_increment, msg.angle_max)) # トピック名,メッセージ型を使って ActionLib client を定義 client",
"actionlib import math from trajectory_msgs.msg import JointTrajectry from trajectry_msgs.msg import JointTrajectoryPoint from control_msgs.msg",
"val = int(-msg.angle_min / msg.angle_increment) if (msg.ranges[val] < 100): i += 1 traj_msg.trajectory.points.append(JointTrajectoryPoint(positions=[0,",
"traj_msg = FollowJointTrajectoryGoal() traj_msg.trajectory = JointTrajectory() traj_msg.trajectory.header.stamp = rospy.Time.now() + rospy.Duration(0.2) traj_msg.trajectory.joint_names =",
"'JOINT27', 'JOINT28', 'JOINT29'] global i val = int(-msg.angle_min / msg.angle_increment) if (msg.ranges[val] <",
"JointTrajectry from trajectry_msgs.msg import JointTrajectoryPoint from control_msgs.msg import JointTrajectory from sensor_msgs.msg import LaserScan",
"0, i], time_from_start = rospy.Duration(1.0 + i))) #目標姿勢をゴールとして送信 client.send_goal(traj_msg) rospy.loginfo(\"wait for goal ...\")",
"'JOINT12', 'JOINT13', 'JOINT14', 'JOINT15', 'JOINT16', 'JOINT17', 'JOINT18', 'JOINT19', 'JOINT20', 'JOINT21', 'JOINT22', 'JOINT23', 'JOINT24',"
] |
[
"right def verifyPostorder1(self, postorder: List[int]) -> bool: \"\"\"递归分治:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof/solution/mian-shi-ti-33-er-cha-sou-suo-shu-de-hou-xu-bian-6/\"\"\" def recur(i, j): #终止条件: 当",
"def recur(i, j): #终止条件: 当 i >= j ,说明此子树节点数量 <=1,无需判别正确性,因此直接返回 true if i",
"1) def main(): param = [1,6,3,2,5] param = [1,3,2,6,5] solution = Solution() ret",
"1 left = True if lIndex: left = self.verifyPostorder(postorder[:lIndex]) right = True if",
"+= 1 #判断右区间,是否都大于 # 左子树区间 [i, m - 1]、右子树区间 [m, j - 1]、根节点索引",
"#判断右区间,是否都大于 # 左子树区间 [i, m - 1]、右子树区间 [m, j - 1]、根节点索引 j return",
"postorder[i] < root: return False rIndex += 1 left = True if lIndex:",
"参考以下这颗二叉搜索树: 5 / \\ 2 6 / \\ 1 3 示例 1: 输入:",
"1) and recur(m, j - 1) return recur(0, len(postorder) - 1) def main():",
"- 1): if postorder[i] > root: break lIndex += 1 #右子树大于跟节点,待求证 rIndex =",
"i while postorder[p] < postorder[j]: p += 1 #先定左区间,小于root m = p while",
"class Solution: def verifyPostorder(self, postorder: List[int]) -> bool: \"\"\"剑指Offer:判断有点繁琐\"\"\" length = len(postorder) if",
"len(postorder) if length <= 0: return True root = postorder[length - 1] #左子树小于跟节点,已经保证",
"-*- coding: utf-8 -*- from typing import List class Solution: def verifyPostorder(self, postorder:",
"[1,3,2,6,5] solution = Solution() ret = solution.verifyPostorder(param) print(ret) ret = solution.verifyPostorder1(param) print(ret) '''剑指",
"return recur(0, len(postorder) - 1) def main(): param = [1,6,3,2,5] param = [1,3,2,6,5]",
"return True root = postorder[length - 1] #左子树小于跟节点,已经保证 lIndex = 0 for i",
"Solution() ret = solution.verifyPostorder(param) print(ret) ret = solution.verifyPostorder1(param) print(ret) '''剑指 Offer 33. 二叉搜索树的后序遍历序列",
">= j ,说明此子树节点数量 <=1,无需判别正确性,因此直接返回 true if i >= j: return True #计数判断 p",
"ret = solution.verifyPostorder(param) print(ret) ret = solution.verifyPostorder1(param) print(ret) '''剑指 Offer 33. 二叉搜索树的后序遍历序列 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回",
"- 1): if postorder[i] < root: return False rIndex += 1 left =",
"-> bool: \"\"\"递归分治:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof/solution/mian-shi-ti-33-er-cha-sou-suo-shu-de-hou-xu-bian-6/\"\"\" def recur(i, j): #终止条件: 当 i >= j ,说明此子树节点数量 <=1,无需判别正确性,因此直接返回",
"#左子树小于跟节点,已经保证 lIndex = 0 for i in range(length - 1): if postorder[i] >",
"\"\"\"递归分治:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof/solution/mian-shi-ti-33-er-cha-sou-suo-shu-de-hou-xu-bian-6/\"\"\" def recur(i, j): #终止条件: 当 i >= j ,说明此子树节点数量 <=1,无需判别正确性,因此直接返回 true if",
"main(): param = [1,6,3,2,5] param = [1,3,2,6,5] solution = Solution() ret = solution.verifyPostorder(param)",
"2: 输入: [1,3,2,6,5] 输出: true 提示: 数组长度 <= 1000 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 '''",
"recur(0, len(postorder) - 1) def main(): param = [1,6,3,2,5] param = [1,3,2,6,5] solution",
"= 0 for i in range(length - 1): if postorder[i] > root: break",
"True #计数判断 p = i while postorder[p] < postorder[j]: p += 1 #先定左区间,小于root",
"param = [1,3,2,6,5] solution = Solution() ret = solution.verifyPostorder(param) print(ret) ret = solution.verifyPostorder1(param)",
"\\ 2 6 / \\ 1 3 示例 1: 输入: [1,6,3,2,5] 输出: false",
"from typing import List class Solution: def verifyPostorder(self, postorder: List[int]) -> bool: \"\"\"剑指Offer:判断有点繁琐\"\"\"",
"rIndex: right = self.verifyPostorder(postorder[lIndex:lIndex+rIndex]) return left and right def verifyPostorder1(self, postorder: List[int]) ->",
"while postorder[p] < postorder[j]: p += 1 #先定左区间,小于root m = p while postorder[p]",
"right = self.verifyPostorder(postorder[lIndex:lIndex+rIndex]) return left and right def verifyPostorder1(self, postorder: List[int]) -> bool:",
"0: return True root = postorder[length - 1] #左子树小于跟节点,已经保证 lIndex = 0 for",
"postorder[i] > root: break lIndex += 1 #右子树大于跟节点,待求证 rIndex = 0 for i",
"p += 1 #判断右区间,是否都大于 # 左子树区间 [i, m - 1]、右子树区间 [m, j -",
"solution.verifyPostorder(param) print(ret) ret = solution.verifyPostorder1(param) print(ret) '''剑指 Offer 33. 二叉搜索树的后序遍历序列 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。",
"Solution: def verifyPostorder(self, postorder: List[int]) -> bool: \"\"\"剑指Offer:判断有点繁琐\"\"\" length = len(postorder) if length",
"\"\"\"剑指Offer:判断有点繁琐\"\"\" length = len(postorder) if length <= 0: return True root = postorder[length",
"1] #左子树小于跟节点,已经保证 lIndex = 0 for i in range(length - 1): if postorder[i]",
"def verifyPostorder1(self, postorder: List[int]) -> bool: \"\"\"递归分治:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof/solution/mian-shi-ti-33-er-cha-sou-suo-shu-de-hou-xu-bian-6/\"\"\" def recur(i, j): #终止条件: 当 i",
"solution.verifyPostorder1(param) print(ret) '''剑指 Offer 33. 二叉搜索树的后序遍历序列 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。 参考以下这颗二叉搜索树: 5 / \\",
"recur(m, j - 1) return recur(0, len(postorder) - 1) def main(): param =",
"1 3 示例 1: 输入: [1,6,3,2,5] 输出: false 示例 2: 输入: [1,3,2,6,5] 输出:",
"verifyPostorder1(self, postorder: List[int]) -> bool: \"\"\"递归分治:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof/solution/mian-shi-ti-33-er-cha-sou-suo-shu-de-hou-xu-bian-6/\"\"\" def recur(i, j): #终止条件: 当 i >=",
"- 1) and recur(m, j - 1) return recur(0, len(postorder) - 1) def",
"m - 1]、右子树区间 [m, j - 1]、根节点索引 j return p == j and",
"-> bool: \"\"\"剑指Offer:判断有点繁琐\"\"\" length = len(postorder) if length <= 0: return True root",
"= i while postorder[p] < postorder[j]: p += 1 #先定左区间,小于root m = p",
"bool: \"\"\"递归分治:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof/solution/mian-shi-ti-33-er-cha-sou-suo-shu-de-hou-xu-bian-6/\"\"\" def recur(i, j): #终止条件: 当 i >= j ,说明此子树节点数量 <=1,无需判别正确性,因此直接返回 true",
"range(length - 1): if postorder[i] > root: break lIndex += 1 #右子树大于跟节点,待求证 rIndex",
"self.verifyPostorder(postorder[lIndex:lIndex+rIndex]) return left and right def verifyPostorder1(self, postorder: List[int]) -> bool: \"\"\"递归分治:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof/solution/mian-shi-ti-33-er-cha-sou-suo-shu-de-hou-xu-bian-6/\"\"\" def",
"for i in range(length - 1): if postorder[i] > root: break lIndex +=",
"p += 1 #先定左区间,小于root m = p while postorder[p] > postorder[j]: p +=",
"> root: break lIndex += 1 #右子树大于跟节点,待求证 rIndex = 0 for i in",
"= Solution() ret = solution.verifyPostorder(param) print(ret) ret = solution.verifyPostorder1(param) print(ret) '''剑指 Offer 33.",
"二叉搜索树的后序遍历序列 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。 参考以下这颗二叉搜索树: 5 / \\ 2 6 / \\ 1",
"< postorder[j]: p += 1 #先定左区间,小于root m = p while postorder[p] > postorder[j]:",
"- 1]、根节点索引 j return p == j and recur(i, m - 1) and",
"0 for i in range(lIndex, length - 1): if postorder[i] < root: return",
"lIndex: left = self.verifyPostorder(postorder[:lIndex]) right = True if rIndex: right = self.verifyPostorder(postorder[lIndex:lIndex+rIndex]) return",
"j - 1]、根节点索引 j return p == j and recur(i, m - 1)",
"#!/usr/local/bin/python3.7 # -*- coding: utf-8 -*- from typing import List class Solution: def",
"if length <= 0: return True root = postorder[length - 1] #左子树小于跟节点,已经保证 lIndex",
"[i, m - 1]、右子树区间 [m, j - 1]、根节点索引 j return p == j",
"[m, j - 1]、根节点索引 j return p == j and recur(i, m -",
"break lIndex += 1 #右子树大于跟节点,待求证 rIndex = 0 for i in range(lIndex, length",
"length - 1): if postorder[i] < root: return False rIndex += 1 left",
"return False rIndex += 1 left = True if lIndex: left = self.verifyPostorder(postorder[:lIndex])",
"return True #计数判断 p = i while postorder[p] < postorder[j]: p += 1",
"recur(i, m - 1) and recur(m, j - 1) return recur(0, len(postorder) -",
"verifyPostorder(self, postorder: List[int]) -> bool: \"\"\"剑指Offer:判断有点繁琐\"\"\" length = len(postorder) if length <= 0:",
"= postorder[length - 1] #左子树小于跟节点,已经保证 lIndex = 0 for i in range(length -",
"root = postorder[length - 1] #左子树小于跟节点,已经保证 lIndex = 0 for i in range(length",
"postorder[p] < postorder[j]: p += 1 #先定左区间,小于root m = p while postorder[p] >",
"def verifyPostorder(self, postorder: List[int]) -> bool: \"\"\"剑指Offer:判断有点繁琐\"\"\" length = len(postorder) if length <=",
"/ \\ 2 6 / \\ 1 3 示例 1: 输入: [1,6,3,2,5] 输出:",
"提示: 数组长度 <= 1000 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ''' if __name__ == '__main__': main()",
"if postorder[i] < root: return False rIndex += 1 left = True if",
"utf-8 -*- from typing import List class Solution: def verifyPostorder(self, postorder: List[int]) ->",
"1: 输入: [1,6,3,2,5] 输出: false 示例 2: 输入: [1,3,2,6,5] 输出: true 提示: 数组长度",
"range(lIndex, length - 1): if postorder[i] < root: return False rIndex += 1",
"#计数判断 p = i while postorder[p] < postorder[j]: p += 1 #先定左区间,小于root m",
"+= 1 #右子树大于跟节点,待求证 rIndex = 0 for i in range(lIndex, length - 1):",
"True if rIndex: right = self.verifyPostorder(postorder[lIndex:lIndex+rIndex]) return left and right def verifyPostorder1(self, postorder:",
"length <= 0: return True root = postorder[length - 1] #左子树小于跟节点,已经保证 lIndex =",
"输入: [1,6,3,2,5] 输出: false 示例 2: 输入: [1,3,2,6,5] 输出: true 提示: 数组长度 <=",
"param = [1,6,3,2,5] param = [1,3,2,6,5] solution = Solution() ret = solution.verifyPostorder(param) print(ret)",
"j return p == j and recur(i, m - 1) and recur(m, j",
"True root = postorder[length - 1] #左子树小于跟节点,已经保证 lIndex = 0 for i in",
"= 0 for i in range(lIndex, length - 1): if postorder[i] < root:",
"for i in range(lIndex, length - 1): if postorder[i] < root: return False",
"root: return False rIndex += 1 left = True if lIndex: left =",
"left = self.verifyPostorder(postorder[:lIndex]) right = True if rIndex: right = self.verifyPostorder(postorder[lIndex:lIndex+rIndex]) return left",
"j ,说明此子树节点数量 <=1,无需判别正确性,因此直接返回 true if i >= j: return True #计数判断 p =",
"j: return True #计数判断 p = i while postorder[p] < postorder[j]: p +=",
"j and recur(i, m - 1) and recur(m, j - 1) return recur(0,",
"1) return recur(0, len(postorder) - 1) def main(): param = [1,6,3,2,5] param =",
"List[int]) -> bool: \"\"\"递归分治:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof/solution/mian-shi-ti-33-er-cha-sou-suo-shu-de-hou-xu-bian-6/\"\"\" def recur(i, j): #终止条件: 当 i >= j ,说明此子树节点数量",
"<=1,无需判别正确性,因此直接返回 true if i >= j: return True #计数判断 p = i while",
"import List class Solution: def verifyPostorder(self, postorder: List[int]) -> bool: \"\"\"剑指Offer:判断有点繁琐\"\"\" length =",
"False rIndex += 1 left = True if lIndex: left = self.verifyPostorder(postorder[:lIndex]) right",
"1]、右子树区间 [m, j - 1]、根节点索引 j return p == j and recur(i, m",
"示例 1: 输入: [1,6,3,2,5] 输出: false 示例 2: 输入: [1,3,2,6,5] 输出: true 提示:",
"- 1) return recur(0, len(postorder) - 1) def main(): param = [1,6,3,2,5] param",
"postorder[j]: p += 1 #判断右区间,是否都大于 # 左子树区间 [i, m - 1]、右子树区间 [m, j",
"self.verifyPostorder(postorder[:lIndex]) right = True if rIndex: right = self.verifyPostorder(postorder[lIndex:lIndex+rIndex]) return left and right",
"coding: utf-8 -*- from typing import List class Solution: def verifyPostorder(self, postorder: List[int])",
"+= 1 #先定左区间,小于root m = p while postorder[p] > postorder[j]: p += 1",
"= solution.verifyPostorder(param) print(ret) ret = solution.verifyPostorder1(param) print(ret) '''剑指 Offer 33. 二叉搜索树的后序遍历序列 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回",
"lIndex += 1 #右子树大于跟节点,待求证 rIndex = 0 for i in range(lIndex, length -",
"solution = Solution() ret = solution.verifyPostorder(param) print(ret) ret = solution.verifyPostorder1(param) print(ret) '''剑指 Offer",
"1): if postorder[i] > root: break lIndex += 1 #右子树大于跟节点,待求证 rIndex = 0",
">= j: return True #计数判断 p = i while postorder[p] < postorder[j]: p",
"左子树区间 [i, m - 1]、右子树区间 [m, j - 1]、根节点索引 j return p ==",
"m - 1) and recur(m, j - 1) return recur(0, len(postorder) - 1)",
"输出: false 示例 2: 输入: [1,3,2,6,5] 输出: true 提示: 数组长度 <= 1000 来源:力扣(LeetCode)",
"1 #先定左区间,小于root m = p while postorder[p] > postorder[j]: p += 1 #判断右区间,是否都大于",
"postorder[p] > postorder[j]: p += 1 #判断右区间,是否都大于 # 左子树区间 [i, m - 1]、右子树区间",
"right = True if rIndex: right = self.verifyPostorder(postorder[lIndex:lIndex+rIndex]) return left and right def",
"Offer 33. 二叉搜索树的后序遍历序列 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。 参考以下这颗二叉搜索树: 5 / \\ 2 6 /",
"1): if postorder[i] < root: return False rIndex += 1 left = True",
"输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。 参考以下这颗二叉搜索树: 5 / \\ 2 6 / \\ 1 3",
"j): #终止条件: 当 i >= j ,说明此子树节点数量 <=1,无需判别正确性,因此直接返回 true if i >= j:",
"postorder: List[int]) -> bool: \"\"\"递归分治:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof/solution/mian-shi-ti-33-er-cha-sou-suo-shu-de-hou-xu-bian-6/\"\"\" def recur(i, j): #终止条件: 当 i >= j",
"len(postorder) - 1) def main(): param = [1,6,3,2,5] param = [1,3,2,6,5] solution =",
"typing import List class Solution: def verifyPostorder(self, postorder: List[int]) -> bool: \"\"\"剑指Offer:判断有点繁琐\"\"\" length",
"#右子树大于跟节点,待求证 rIndex = 0 for i in range(lIndex, length - 1): if postorder[i]",
"5 / \\ 2 6 / \\ 1 3 示例 1: 输入: [1,6,3,2,5]",
"> postorder[j]: p += 1 #判断右区间,是否都大于 # 左子树区间 [i, m - 1]、右子树区间 [m,",
"and recur(m, j - 1) return recur(0, len(postorder) - 1) def main(): param",
"p == j and recur(i, m - 1) and recur(m, j - 1)",
"当 i >= j ,说明此子树节点数量 <=1,无需判别正确性,因此直接返回 true if i >= j: return True",
"= True if rIndex: right = self.verifyPostorder(postorder[lIndex:lIndex+rIndex]) return left and right def verifyPostorder1(self,",
"i >= j ,说明此子树节点数量 <=1,无需判别正确性,因此直接返回 true if i >= j: return True #计数判断",
"left = True if lIndex: left = self.verifyPostorder(postorder[:lIndex]) right = True if rIndex:",
"#终止条件: 当 i >= j ,说明此子树节点数量 <=1,无需判别正确性,因此直接返回 true if i >= j: return",
"#先定左区间,小于root m = p while postorder[p] > postorder[j]: p += 1 #判断右区间,是否都大于 #",
"m = p while postorder[p] > postorder[j]: p += 1 #判断右区间,是否都大于 # 左子树区间",
"true 提示: 数组长度 <= 1000 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ''' if __name__ == '__main__':",
"if lIndex: left = self.verifyPostorder(postorder[:lIndex]) right = True if rIndex: right = self.verifyPostorder(postorder[lIndex:lIndex+rIndex])",
"= True if lIndex: left = self.verifyPostorder(postorder[:lIndex]) right = True if rIndex: right",
"List class Solution: def verifyPostorder(self, postorder: List[int]) -> bool: \"\"\"剑指Offer:判断有点繁琐\"\"\" length = len(postorder)",
"2 6 / \\ 1 3 示例 1: 输入: [1,6,3,2,5] 输出: false 示例",
"length = len(postorder) if length <= 0: return True root = postorder[length -",
"= self.verifyPostorder(postorder[lIndex:lIndex+rIndex]) return left and right def verifyPostorder1(self, postorder: List[int]) -> bool: \"\"\"递归分治:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof/solution/mian-shi-ti-33-er-cha-sou-suo-shu-de-hou-xu-bian-6/\"\"\"",
"1]、根节点索引 j return p == j and recur(i, m - 1) and recur(m,",
"bool: \"\"\"剑指Offer:判断有点繁琐\"\"\" length = len(postorder) if length <= 0: return True root =",
"false 示例 2: 输入: [1,3,2,6,5] 输出: true 提示: 数组长度 <= 1000 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof",
"in range(lIndex, length - 1): if postorder[i] < root: return False rIndex +=",
"< root: return False rIndex += 1 left = True if lIndex: left",
"[1,6,3,2,5] 输出: false 示例 2: 输入: [1,3,2,6,5] 输出: true 提示: 数组长度 <= 1000",
"0 for i in range(length - 1): if postorder[i] > root: break lIndex",
"\\ 1 3 示例 1: 输入: [1,6,3,2,5] 输出: false 示例 2: 输入: [1,3,2,6,5]",
"'''剑指 Offer 33. 二叉搜索树的后序遍历序列 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。 参考以下这颗二叉搜索树: 5 / \\ 2 6",
"# -*- coding: utf-8 -*- from typing import List class Solution: def verifyPostorder(self,",
"- 1]、右子树区间 [m, j - 1]、根节点索引 j return p == j and recur(i,",
"postorder: List[int]) -> bool: \"\"\"剑指Offer:判断有点繁琐\"\"\" length = len(postorder) if length <= 0: return",
"# 左子树区间 [i, m - 1]、右子树区间 [m, j - 1]、根节点索引 j return p",
"if postorder[i] > root: break lIndex += 1 #右子树大于跟节点,待求证 rIndex = 0 for",
"输入: [1,3,2,6,5] 输出: true 提示: 数组长度 <= 1000 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ''' if",
"= self.verifyPostorder(postorder[:lIndex]) right = True if rIndex: right = self.verifyPostorder(postorder[lIndex:lIndex+rIndex]) return left and",
"True if lIndex: left = self.verifyPostorder(postorder[:lIndex]) right = True if rIndex: right =",
"1 #判断右区间,是否都大于 # 左子树区间 [i, m - 1]、右子树区间 [m, j - 1]、根节点索引 j",
"ret = solution.verifyPostorder1(param) print(ret) '''剑指 Offer 33. 二叉搜索树的后序遍历序列 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。 参考以下这颗二叉搜索树: 5",
"true,否则返回 false。假设输入的数组的任意两个数字都互不相同。 参考以下这颗二叉搜索树: 5 / \\ 2 6 / \\ 1 3 示例",
"/ \\ 1 3 示例 1: 输入: [1,6,3,2,5] 输出: false 示例 2: 输入:",
"i >= j: return True #计数判断 p = i while postorder[p] < postorder[j]:",
"and recur(i, m - 1) and recur(m, j - 1) return recur(0, len(postorder)",
"33. 二叉搜索树的后序遍历序列 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。 参考以下这颗二叉搜索树: 5 / \\ 2 6 / \\",
"- 1) def main(): param = [1,6,3,2,5] param = [1,3,2,6,5] solution = Solution()",
"= p while postorder[p] > postorder[j]: p += 1 #判断右区间,是否都大于 # 左子树区间 [i,",
"false。假设输入的数组的任意两个数字都互不相同。 参考以下这颗二叉搜索树: 5 / \\ 2 6 / \\ 1 3 示例 1:",
"输出: true 提示: 数组长度 <= 1000 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ''' if __name__ ==",
"[1,3,2,6,5] 输出: true 提示: 数组长度 <= 1000 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ''' if __name__",
"-*- from typing import List class Solution: def verifyPostorder(self, postorder: List[int]) -> bool:",
"<= 0: return True root = postorder[length - 1] #左子树小于跟节点,已经保证 lIndex = 0",
"示例 2: 输入: [1,3,2,6,5] 输出: true 提示: 数组长度 <= 1000 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。",
"left and right def verifyPostorder1(self, postorder: List[int]) -> bool: \"\"\"递归分治:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof/solution/mian-shi-ti-33-er-cha-sou-suo-shu-de-hou-xu-bian-6/\"\"\" def recur(i, j):",
"lIndex = 0 for i in range(length - 1): if postorder[i] > root:",
"1 #右子树大于跟节点,待求证 rIndex = 0 for i in range(lIndex, length - 1): if",
"rIndex += 1 left = True if lIndex: left = self.verifyPostorder(postorder[:lIndex]) right =",
"p while postorder[p] > postorder[j]: p += 1 #判断右区间,是否都大于 # 左子树区间 [i, m",
"p = i while postorder[p] < postorder[j]: p += 1 #先定左区间,小于root m =",
"[1,6,3,2,5] param = [1,3,2,6,5] solution = Solution() ret = solution.verifyPostorder(param) print(ret) ret =",
"i in range(lIndex, length - 1): if postorder[i] < root: return False rIndex",
"and right def verifyPostorder1(self, postorder: List[int]) -> bool: \"\"\"递归分治:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof/solution/mian-shi-ti-33-er-cha-sou-suo-shu-de-hou-xu-bian-6/\"\"\" def recur(i, j): #终止条件:",
"in range(length - 1): if postorder[i] > root: break lIndex += 1 #右子树大于跟节点,待求证",
"print(ret) ret = solution.verifyPostorder1(param) print(ret) '''剑指 Offer 33. 二叉搜索树的后序遍历序列 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。 参考以下这颗二叉搜索树:",
"postorder[j]: p += 1 #先定左区间,小于root m = p while postorder[p] > postorder[j]: p",
"true if i >= j: return True #计数判断 p = i while postorder[p]",
"- 1] #左子树小于跟节点,已经保证 lIndex = 0 for i in range(length - 1): if",
"6 / \\ 1 3 示例 1: 输入: [1,6,3,2,5] 输出: false 示例 2:",
"if rIndex: right = self.verifyPostorder(postorder[lIndex:lIndex+rIndex]) return left and right def verifyPostorder1(self, postorder: List[int])",
"= len(postorder) if length <= 0: return True root = postorder[length - 1]",
"return left and right def verifyPostorder1(self, postorder: List[int]) -> bool: \"\"\"递归分治:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof/solution/mian-shi-ti-33-er-cha-sou-suo-shu-de-hou-xu-bian-6/\"\"\" def recur(i,",
"root: break lIndex += 1 #右子树大于跟节点,待求证 rIndex = 0 for i in range(lIndex,",
"+= 1 left = True if lIndex: left = self.verifyPostorder(postorder[:lIndex]) right = True",
"rIndex = 0 for i in range(lIndex, length - 1): if postorder[i] <",
"return p == j and recur(i, m - 1) and recur(m, j -",
"while postorder[p] > postorder[j]: p += 1 #判断右区间,是否都大于 # 左子树区间 [i, m -",
",说明此子树节点数量 <=1,无需判别正确性,因此直接返回 true if i >= j: return True #计数判断 p = i",
"if i >= j: return True #计数判断 p = i while postorder[p] <",
"j - 1) return recur(0, len(postorder) - 1) def main(): param = [1,6,3,2,5]",
"= solution.verifyPostorder1(param) print(ret) '''剑指 Offer 33. 二叉搜索树的后序遍历序列 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。 参考以下这颗二叉搜索树: 5 /",
"recur(i, j): #终止条件: 当 i >= j ,说明此子树节点数量 <=1,无需判别正确性,因此直接返回 true if i >=",
"def main(): param = [1,6,3,2,5] param = [1,3,2,6,5] solution = Solution() ret =",
"= [1,6,3,2,5] param = [1,3,2,6,5] solution = Solution() ret = solution.verifyPostorder(param) print(ret) ret",
"List[int]) -> bool: \"\"\"剑指Offer:判断有点繁琐\"\"\" length = len(postorder) if length <= 0: return True",
"3 示例 1: 输入: [1,6,3,2,5] 输出: false 示例 2: 输入: [1,3,2,6,5] 输出: true",
"print(ret) '''剑指 Offer 33. 二叉搜索树的后序遍历序列 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。 参考以下这颗二叉搜索树: 5 / \\ 2",
"i in range(length - 1): if postorder[i] > root: break lIndex += 1",
"== j and recur(i, m - 1) and recur(m, j - 1) return",
"postorder[length - 1] #左子树小于跟节点,已经保证 lIndex = 0 for i in range(length - 1):",
"= [1,3,2,6,5] solution = Solution() ret = solution.verifyPostorder(param) print(ret) ret = solution.verifyPostorder1(param) print(ret)"
] |
[
"= http_response.json() assert response[\"content\"] == resource_data[\"content\"] def resource_json_is(resource_data): response = http_response.json() assert response",
"import Http # noqa: F401 from safetydance_test.step_extension import step_extension from scrud_django.models import Resource,",
"isinstance(resource_data['content'], dict) response = http_response.json() assert response[\"content\"] == resource_data[\"content\"] def resource_json_is(resource_data): response =",
"@step_extension def is_valid_resource(name: str): instance = named_instances[name] assert isinstance(instance, Resource) assert isinstance(instance.content, dict)",
"= register_resource_type(**expected) resource_type_name = list(expected.keys())[0] expected = expected[resource_type_name] assert result.type_uri == expected['rdf_type_uri'] assert",
"in resource_data assert isinstance(resource_data['etag'], str) assert 'content' in resource_data assert isinstance(resource_data['content'], dict) response",
"def resource_json_is(resource_data): response = http_response.json() assert response == resource_data, response def response_json_matches(expected): observed",
"initializer=dict) json_path_match = step_data(object) sub_class_of = URIRef(\"http://www.w3.org/2000/01/rdf-schema#subClassOf\") @step_extension def an_instance_named(name: str, instance: Model):",
"initializer=dict) @step_extension def an_registration_data(name: str, registration_data: dict): named_registration_data[name] = registration_data @step_extension def check_registration_results(name:",
"json_path_match = step_data(object) sub_class_of = URIRef(\"http://www.w3.org/2000/01/rdf-schema#subClassOf\") @step_extension def an_instance_named(name: str, instance: Model): named_instances[name]",
"\\ncondition: {condition}, \\n match: {match}\" def resource_envelope_json_is(resource_data: dict): assert 'href' in resource_data assert",
"response = http_response.json() assert response[\"content\"] == resource_data[\"content\"] def resource_json_is(resource_data): response = http_response.json() assert",
"assert isinstance(resource_data['href'], str) assert 'last_modified' in resource_data assert isinstance(resource_data['last_modified'], str) assert 'etag' in",
"data match = json_path_match[0].value assert condition( json_path_match ), f\"expr: {expr} \\ncondition: {condition}, \\n",
"registration_data @step_extension def check_registration_results(name: str, result): expected = named_registration_data[name] # result = register_resource_type(**expected)",
"ResourceType) assert isinstance(instance.type_uri, str) assert len(instance.type_uri) > 0 @step_extension def ld_context_states_sub_class_of(subclass_uri, superclass_uri): data",
"def response_json_matches(expected): observed = http_response.json() assert json_values_match(expected, observed), http_response resource_envelope_json_is = step_extension( f=resource_envelope_json_is,",
"{condition}, \\n match: {match}\" def resource_envelope_json_is(resource_data: dict): assert 'href' in resource_data assert isinstance(resource_data['href'],",
"result.schema_uri == expected['json_schema_url'] def get_compiled_expression(expr, compiled_expressions): compiled_expr = compiled_expressions.get(expr, None) if compiled_expr is",
"= named_instances[name] assert isinstance(instance, ResourceType) assert isinstance(instance.type_uri, str) assert len(instance.type_uri) > 0 @step_extension",
") from safetydance_django.test import Http # noqa: F401 from safetydance_test.step_extension import step_extension from",
"= step_extension( f=resource_envelope_json_is, target_type=Http ) resource_json_is = step_extension(f=resource_json_is, target_type=Http) response_json_matches = step_extension(f=response_json_matches, target_type=Http)",
"json_path_match = compiled_expr.find(data) assert len(json_path_match) > 0, data match = json_path_match[0].value assert condition(",
"= parse(expr) compiled_expressions[expr] = compiled_expr return compiled_expr @step_extension def json_path_matches(expr, condition): data =",
"isinstance(resource_data['etag'], str) assert 'content' in resource_data assert isinstance(resource_data['content'], dict) response = http_response.json() assert",
"__all__ = [ 'an_instance_named', 'is_valid_resource', 'is_valid_resource_type', 'an_registration_data', 'check_registration_results', 'json_path_expressions', 'json_path_match', 'json_path_matches', 'ld_context_states_sub_class_of', 'named_instances',",
"http_response.json() g = Graph().parse(data=json.dumps(data), format='json-ld') superclasses = list(g.transitive_objects(subclass_uri, sub_class_of)) assert len(superclasses) > 0,",
"scrud_django.models import Resource, ResourceType __all__ = [ 'an_instance_named', 'is_valid_resource', 'is_valid_resource_type', 'an_registration_data', 'check_registration_results', 'json_path_expressions',",
"from datetime import datetime from django.db.models import Model from jsonpath_ng import parse from",
"json from datetime import datetime from django.db.models import Model from jsonpath_ng import parse",
"named_registration_data = step_data(dict, initializer=dict) @step_extension def an_registration_data(name: str, registration_data: dict): named_registration_data[name] = registration_data",
"> 0, data match = json_path_match[0].value assert condition( json_path_match ), f\"expr: {expr} \\ncondition:",
"expected['rdf_type_uri'] assert result.slug == resource_type_name assert result.context_uri == expected['json_ld_context_url'] assert result.schema_uri == expected['json_schema_url']",
"Graph, URIRef from safetydance import step_data from safetydance_django.steps import ( # noqa: F401",
"noqa: F401 from safetydance_test.step_extension import step_extension from scrud_django.models import Resource, ResourceType __all__ =",
"> 0, superclasses assert superclass_uri in superclasses, superclasses # register named_registration_data = step_data(dict,",
"dict): assert 'href' in resource_data assert isinstance(resource_data['href'], str) assert 'last_modified' in resource_data assert",
"'response_json_matches', ] named_instances = step_data(dict, initializer=dict) json_path_expressions = step_data(dict, initializer=dict) json_path_match = step_data(object)",
"assert 'href' in resource_data assert isinstance(resource_data['href'], str) assert 'last_modified' in resource_data assert isinstance(resource_data['last_modified'],",
"str, result): expected = named_registration_data[name] # result = register_resource_type(**expected) resource_type_name = list(expected.keys())[0] expected",
"@step_extension def an_registration_data(name: str, registration_data: dict): named_registration_data[name] = registration_data @step_extension def check_registration_results(name: str,",
"resource_data, response def response_json_matches(expected): observed = http_response.json() assert json_values_match(expected, observed), http_response resource_envelope_json_is =",
"compiled_expressions.get(expr, None) if compiled_expr is None: compiled_expr = parse(expr) compiled_expressions[expr] = compiled_expr return",
"compiled_expr.find(data) assert len(json_path_match) > 0, data match = json_path_match[0].value assert condition( json_path_match ),",
"safetydance_django.steps import ( # noqa: F401 http_client, http_response, json_values_match, ) from safetydance_django.test import",
"@step_extension def check_registration_results(name: str, result): expected = named_registration_data[name] # result = register_resource_type(**expected) resource_type_name",
"step_extension from scrud_django.models import Resource, ResourceType __all__ = [ 'an_instance_named', 'is_valid_resource', 'is_valid_resource_type', 'an_registration_data',",
"initializer=dict) json_path_expressions = step_data(dict, initializer=dict) json_path_match = step_data(object) sub_class_of = URIRef(\"http://www.w3.org/2000/01/rdf-schema#subClassOf\") @step_extension def",
"step_data(object) sub_class_of = URIRef(\"http://www.w3.org/2000/01/rdf-schema#subClassOf\") @step_extension def an_instance_named(name: str, instance: Model): named_instances[name] = instance",
"is_valid_resource_type(name: str): instance = named_instances[name] assert isinstance(instance, ResourceType) assert isinstance(instance.type_uri, str) assert len(instance.type_uri)",
"Graph().parse(data=json.dumps(data), format='json-ld') superclasses = list(g.transitive_objects(subclass_uri, sub_class_of)) assert len(superclasses) > 0, superclasses assert superclass_uri",
"g = Graph().parse(data=json.dumps(data), format='json-ld') superclasses = list(g.transitive_objects(subclass_uri, sub_class_of)) assert len(superclasses) > 0, superclasses",
"'an_registration_data', 'check_registration_results', 'json_path_expressions', 'json_path_match', 'json_path_matches', 'ld_context_states_sub_class_of', 'named_instances', 'resource_json_is', 'response_json_matches', ] named_instances = step_data(dict,",
"assert 'content' in resource_data assert isinstance(resource_data['content'], dict) response = http_response.json() assert response[\"content\"] ==",
"resource_type_name assert result.context_uri == expected['json_ld_context_url'] assert result.schema_uri == expected['json_schema_url'] def get_compiled_expression(expr, compiled_expressions): compiled_expr",
"import Resource, ResourceType __all__ = [ 'an_instance_named', 'is_valid_resource', 'is_valid_resource_type', 'an_registration_data', 'check_registration_results', 'json_path_expressions', 'json_path_match',",
"json_path_expressions = step_data(dict, initializer=dict) json_path_match = step_data(object) sub_class_of = URIRef(\"http://www.w3.org/2000/01/rdf-schema#subClassOf\") @step_extension def an_instance_named(name:",
"superclasses, superclasses # register named_registration_data = step_data(dict, initializer=dict) @step_extension def an_registration_data(name: str, registration_data:",
"check_registration_results(name: str, result): expected = named_registration_data[name] # result = register_resource_type(**expected) resource_type_name = list(expected.keys())[0]",
"def an_registration_data(name: str, registration_data: dict): named_registration_data[name] = registration_data @step_extension def check_registration_results(name: str, result):",
"compiled_expressions[expr] = compiled_expr return compiled_expr @step_extension def json_path_matches(expr, condition): data = http_response.json() compiled_expr",
"observed), http_response resource_envelope_json_is = step_extension( f=resource_envelope_json_is, target_type=Http ) resource_json_is = step_extension(f=resource_json_is, target_type=Http) response_json_matches",
"0, superclasses assert superclass_uri in superclasses, superclasses # register named_registration_data = step_data(dict, initializer=dict)",
"import step_data from safetydance_django.steps import ( # noqa: F401 http_client, http_response, json_values_match, )",
"instance = named_instances[name] assert isinstance(instance, Resource) assert isinstance(instance.content, dict) assert isinstance(instance.modified_at, datetime) assert",
"== resource_data[\"content\"] def resource_json_is(resource_data): response = http_response.json() assert response == resource_data, response def",
"32 @step_extension def is_valid_resource_type(name: str): instance = named_instances[name] assert isinstance(instance, ResourceType) assert isinstance(instance.type_uri,",
"'json_path_match', 'json_path_matches', 'ld_context_states_sub_class_of', 'named_instances', 'resource_json_is', 'response_json_matches', ] named_instances = step_data(dict, initializer=dict) json_path_expressions =",
"assert result.context_uri == expected['json_ld_context_url'] assert result.schema_uri == expected['json_schema_url'] def get_compiled_expression(expr, compiled_expressions): compiled_expr =",
"compiled_expr is None: compiled_expr = parse(expr) compiled_expressions[expr] = compiled_expr return compiled_expr @step_extension def",
"from jsonpath_ng import parse from rdflib import Graph, URIRef from safetydance import step_data",
"in resource_data assert isinstance(resource_data['content'], dict) response = http_response.json() assert response[\"content\"] == resource_data[\"content\"] def",
"response = http_response.json() assert response == resource_data, response def response_json_matches(expected): observed = http_response.json()",
"datetime from django.db.models import Model from jsonpath_ng import parse from rdflib import Graph,",
"json_path_match ), f\"expr: {expr} \\ncondition: {condition}, \\n match: {match}\" def resource_envelope_json_is(resource_data: dict): assert",
"rdflib import Graph, URIRef from safetydance import step_data from safetydance_django.steps import ( #",
"named_instances[name] assert isinstance(instance, Resource) assert isinstance(instance.content, dict) assert isinstance(instance.modified_at, datetime) assert isinstance(instance.etag, str)",
"= get_compiled_expression(expr, json_path_expressions) json_path_match = compiled_expr.find(data) assert len(json_path_match) > 0, data match =",
"resource_envelope_json_is(resource_data: dict): assert 'href' in resource_data assert isinstance(resource_data['href'], str) assert 'last_modified' in resource_data",
"in resource_data assert isinstance(resource_data['last_modified'], str) assert 'etag' in resource_data assert isinstance(resource_data['etag'], str) assert",
"{match}\" def resource_envelope_json_is(resource_data: dict): assert 'href' in resource_data assert isinstance(resource_data['href'], str) assert 'last_modified'",
"f\"expr: {expr} \\ncondition: {condition}, \\n match: {match}\" def resource_envelope_json_is(resource_data: dict): assert 'href' in",
"parse from rdflib import Graph, URIRef from safetydance import step_data from safetydance_django.steps import",
"'content' in resource_data assert isinstance(resource_data['content'], dict) response = http_response.json() assert response[\"content\"] == resource_data[\"content\"]",
"noqa: F401 http_client, http_response, json_values_match, ) from safetydance_django.test import Http # noqa: F401",
"in resource_data assert isinstance(resource_data['href'], str) assert 'last_modified' in resource_data assert isinstance(resource_data['last_modified'], str) assert",
"'json_path_matches', 'ld_context_states_sub_class_of', 'named_instances', 'resource_json_is', 'response_json_matches', ] named_instances = step_data(dict, initializer=dict) json_path_expressions = step_data(dict,",
"= Graph().parse(data=json.dumps(data), format='json-ld') superclasses = list(g.transitive_objects(subclass_uri, sub_class_of)) assert len(superclasses) > 0, superclasses assert",
"# result = register_resource_type(**expected) resource_type_name = list(expected.keys())[0] expected = expected[resource_type_name] assert result.type_uri ==",
"= compiled_expressions.get(expr, None) if compiled_expr is None: compiled_expr = parse(expr) compiled_expressions[expr] = compiled_expr",
"> 0 @step_extension def ld_context_states_sub_class_of(subclass_uri, superclass_uri): data = http_response.json() g = Graph().parse(data=json.dumps(data), format='json-ld')",
"URIRef(\"http://www.w3.org/2000/01/rdf-schema#subClassOf\") @step_extension def an_instance_named(name: str, instance: Model): named_instances[name] = instance @step_extension def is_valid_resource(name:",
"F401 from safetydance_test.step_extension import step_extension from scrud_django.models import Resource, ResourceType __all__ = [",
"str): instance = named_instances[name] assert isinstance(instance, ResourceType) assert isinstance(instance.type_uri, str) assert len(instance.type_uri) >",
"import step_extension from scrud_django.models import Resource, ResourceType __all__ = [ 'an_instance_named', 'is_valid_resource', 'is_valid_resource_type',",
"isinstance(instance, Resource) assert isinstance(instance.content, dict) assert isinstance(instance.modified_at, datetime) assert isinstance(instance.etag, str) assert len(instance.etag)",
"instance = named_instances[name] assert isinstance(instance, ResourceType) assert isinstance(instance.type_uri, str) assert len(instance.type_uri) > 0",
"import ( # noqa: F401 http_client, http_response, json_values_match, ) from safetydance_django.test import Http",
"import datetime from django.db.models import Model from jsonpath_ng import parse from rdflib import",
"superclasses # register named_registration_data = step_data(dict, initializer=dict) @step_extension def an_registration_data(name: str, registration_data: dict):",
"result.context_uri == expected['json_ld_context_url'] assert result.schema_uri == expected['json_schema_url'] def get_compiled_expression(expr, compiled_expressions): compiled_expr = compiled_expressions.get(expr,",
"response def response_json_matches(expected): observed = http_response.json() assert json_values_match(expected, observed), http_response resource_envelope_json_is = step_extension(",
"0 @step_extension def ld_context_states_sub_class_of(subclass_uri, superclass_uri): data = http_response.json() g = Graph().parse(data=json.dumps(data), format='json-ld') superclasses",
"condition): data = http_response.json() compiled_expr = get_compiled_expression(expr, json_path_expressions) json_path_match = compiled_expr.find(data) assert len(json_path_match)",
"= named_instances[name] assert isinstance(instance, Resource) assert isinstance(instance.content, dict) assert isinstance(instance.modified_at, datetime) assert isinstance(instance.etag,",
"http_response.json() assert json_values_match(expected, observed), http_response resource_envelope_json_is = step_extension( f=resource_envelope_json_is, target_type=Http ) resource_json_is =",
"sub_class_of = URIRef(\"http://www.w3.org/2000/01/rdf-schema#subClassOf\") @step_extension def an_instance_named(name: str, instance: Model): named_instances[name] = instance @step_extension",
"ld_context_states_sub_class_of(subclass_uri, superclass_uri): data = http_response.json() g = Graph().parse(data=json.dumps(data), format='json-ld') superclasses = list(g.transitive_objects(subclass_uri, sub_class_of))",
"is None: compiled_expr = parse(expr) compiled_expressions[expr] = compiled_expr return compiled_expr @step_extension def json_path_matches(expr,",
"None: compiled_expr = parse(expr) compiled_expressions[expr] = compiled_expr return compiled_expr @step_extension def json_path_matches(expr, condition):",
"dict) response = http_response.json() assert response[\"content\"] == resource_data[\"content\"] def resource_json_is(resource_data): response = http_response.json()",
"from rdflib import Graph, URIRef from safetydance import step_data from safetydance_django.steps import (",
"len(superclasses) > 0, superclasses assert superclass_uri in superclasses, superclasses # register named_registration_data =",
"resource_type_name = list(expected.keys())[0] expected = expected[resource_type_name] assert result.type_uri == expected['rdf_type_uri'] assert result.slug ==",
"superclasses assert superclass_uri in superclasses, superclasses # register named_registration_data = step_data(dict, initializer=dict) @step_extension",
"# noqa: F401 http_client, http_response, json_values_match, ) from safetydance_django.test import Http # noqa:",
"expected['json_schema_url'] def get_compiled_expression(expr, compiled_expressions): compiled_expr = compiled_expressions.get(expr, None) if compiled_expr is None: compiled_expr",
"== resource_type_name assert result.context_uri == expected['json_ld_context_url'] assert result.schema_uri == expected['json_schema_url'] def get_compiled_expression(expr, compiled_expressions):",
"str) assert len(instance.etag) == 32 @step_extension def is_valid_resource_type(name: str): instance = named_instances[name] assert",
"( # noqa: F401 http_client, http_response, json_values_match, ) from safetydance_django.test import Http #",
"result = register_resource_type(**expected) resource_type_name = list(expected.keys())[0] expected = expected[resource_type_name] assert result.type_uri == expected['rdf_type_uri']",
"get_compiled_expression(expr, compiled_expressions): compiled_expr = compiled_expressions.get(expr, None) if compiled_expr is None: compiled_expr = parse(expr)",
"assert 'last_modified' in resource_data assert isinstance(resource_data['last_modified'], str) assert 'etag' in resource_data assert isinstance(resource_data['etag'],",
"from django.db.models import Model from jsonpath_ng import parse from rdflib import Graph, URIRef",
"[ 'an_instance_named', 'is_valid_resource', 'is_valid_resource_type', 'an_registration_data', 'check_registration_results', 'json_path_expressions', 'json_path_match', 'json_path_matches', 'ld_context_states_sub_class_of', 'named_instances', 'resource_json_is', 'response_json_matches',",
"import Graph, URIRef from safetydance import step_data from safetydance_django.steps import ( # noqa:",
"named_registration_data[name] = registration_data @step_extension def check_registration_results(name: str, result): expected = named_registration_data[name] # result",
"sub_class_of)) assert len(superclasses) > 0, superclasses assert superclass_uri in superclasses, superclasses # register",
"response_json_matches(expected): observed = http_response.json() assert json_values_match(expected, observed), http_response resource_envelope_json_is = step_extension( f=resource_envelope_json_is, target_type=Http",
"safetydance_django.test import Http # noqa: F401 from safetydance_test.step_extension import step_extension from scrud_django.models import",
"isinstance(resource_data['last_modified'], str) assert 'etag' in resource_data assert isinstance(resource_data['etag'], str) assert 'content' in resource_data",
"F401 http_client, http_response, json_values_match, ) from safetydance_django.test import Http # noqa: F401 from",
"def json_path_matches(expr, condition): data = http_response.json() compiled_expr = get_compiled_expression(expr, json_path_expressions) json_path_match = compiled_expr.find(data)",
"response == resource_data, response def response_json_matches(expected): observed = http_response.json() assert json_values_match(expected, observed), http_response",
"json_path_matches(expr, condition): data = http_response.json() compiled_expr = get_compiled_expression(expr, json_path_expressions) json_path_match = compiled_expr.find(data) assert",
"compiled_expr = parse(expr) compiled_expressions[expr] = compiled_expr return compiled_expr @step_extension def json_path_matches(expr, condition): data",
"from safetydance import step_data from safetydance_django.steps import ( # noqa: F401 http_client, http_response,",
"result): expected = named_registration_data[name] # result = register_resource_type(**expected) resource_type_name = list(expected.keys())[0] expected =",
"superclass_uri in superclasses, superclasses # register named_registration_data = step_data(dict, initializer=dict) @step_extension def an_registration_data(name:",
"match: {match}\" def resource_envelope_json_is(resource_data: dict): assert 'href' in resource_data assert isinstance(resource_data['href'], str) assert",
"= http_response.json() assert json_values_match(expected, observed), http_response resource_envelope_json_is = step_extension( f=resource_envelope_json_is, target_type=Http ) resource_json_is",
"assert isinstance(resource_data['last_modified'], str) assert 'etag' in resource_data assert isinstance(resource_data['etag'], str) assert 'content' in",
"http_client, http_response, json_values_match, ) from safetydance_django.test import Http # noqa: F401 from safetydance_test.step_extension",
"str, registration_data: dict): named_registration_data[name] = registration_data @step_extension def check_registration_results(name: str, result): expected =",
"), f\"expr: {expr} \\ncondition: {condition}, \\n match: {match}\" def resource_envelope_json_is(resource_data: dict): assert 'href'",
"assert isinstance(instance.content, dict) assert isinstance(instance.modified_at, datetime) assert isinstance(instance.etag, str) assert len(instance.etag) == 32",
"str, instance: Model): named_instances[name] = instance @step_extension def is_valid_resource(name: str): instance = named_instances[name]",
"= URIRef(\"http://www.w3.org/2000/01/rdf-schema#subClassOf\") @step_extension def an_instance_named(name: str, instance: Model): named_instances[name] = instance @step_extension def",
"safetydance import step_data from safetydance_django.steps import ( # noqa: F401 http_client, http_response, json_values_match,",
"assert isinstance(instance, ResourceType) assert isinstance(instance.type_uri, str) assert len(instance.type_uri) > 0 @step_extension def ld_context_states_sub_class_of(subclass_uri,",
"json_values_match, ) from safetydance_django.test import Http # noqa: F401 from safetydance_test.step_extension import step_extension",
"isinstance(instance, ResourceType) assert isinstance(instance.type_uri, str) assert len(instance.type_uri) > 0 @step_extension def ld_context_states_sub_class_of(subclass_uri, superclass_uri):",
"http_response.json() compiled_expr = get_compiled_expression(expr, json_path_expressions) json_path_match = compiled_expr.find(data) assert len(json_path_match) > 0, data",
"if compiled_expr is None: compiled_expr = parse(expr) compiled_expressions[expr] = compiled_expr return compiled_expr @step_extension",
"resource_data assert isinstance(resource_data['href'], str) assert 'last_modified' in resource_data assert isinstance(resource_data['last_modified'], str) assert 'etag'",
"is_valid_resource(name: str): instance = named_instances[name] assert isinstance(instance, Resource) assert isinstance(instance.content, dict) assert isinstance(instance.modified_at,",
"None) if compiled_expr is None: compiled_expr = parse(expr) compiled_expressions[expr] = compiled_expr return compiled_expr",
"dict) assert isinstance(instance.modified_at, datetime) assert isinstance(instance.etag, str) assert len(instance.etag) == 32 @step_extension def",
"result.type_uri == expected['rdf_type_uri'] assert result.slug == resource_type_name assert result.context_uri == expected['json_ld_context_url'] assert result.schema_uri",
"= named_registration_data[name] # result = register_resource_type(**expected) resource_type_name = list(expected.keys())[0] expected = expected[resource_type_name] assert",
"ResourceType __all__ = [ 'an_instance_named', 'is_valid_resource', 'is_valid_resource_type', 'an_registration_data', 'check_registration_results', 'json_path_expressions', 'json_path_match', 'json_path_matches', 'ld_context_states_sub_class_of',",
"dict): named_registration_data[name] = registration_data @step_extension def check_registration_results(name: str, result): expected = named_registration_data[name] #",
"= step_data(dict, initializer=dict) json_path_expressions = step_data(dict, initializer=dict) json_path_match = step_data(object) sub_class_of = URIRef(\"http://www.w3.org/2000/01/rdf-schema#subClassOf\")",
"assert len(superclasses) > 0, superclasses assert superclass_uri in superclasses, superclasses # register named_registration_data",
"@step_extension def json_path_matches(expr, condition): data = http_response.json() compiled_expr = get_compiled_expression(expr, json_path_expressions) json_path_match =",
"data = http_response.json() g = Graph().parse(data=json.dumps(data), format='json-ld') superclasses = list(g.transitive_objects(subclass_uri, sub_class_of)) assert len(superclasses)",
"assert isinstance(instance.modified_at, datetime) assert isinstance(instance.etag, str) assert len(instance.etag) == 32 @step_extension def is_valid_resource_type(name:",
"def is_valid_resource(name: str): instance = named_instances[name] assert isinstance(instance, Resource) assert isinstance(instance.content, dict) assert",
"named_instances[name] assert isinstance(instance, ResourceType) assert isinstance(instance.type_uri, str) assert len(instance.type_uri) > 0 @step_extension def",
"def ld_context_states_sub_class_of(subclass_uri, superclass_uri): data = http_response.json() g = Graph().parse(data=json.dumps(data), format='json-ld') superclasses = list(g.transitive_objects(subclass_uri,",
"assert isinstance(instance.etag, str) assert len(instance.etag) == 32 @step_extension def is_valid_resource_type(name: str): instance =",
"in superclasses, superclasses # register named_registration_data = step_data(dict, initializer=dict) @step_extension def an_registration_data(name: str,",
"expected['json_ld_context_url'] assert result.schema_uri == expected['json_schema_url'] def get_compiled_expression(expr, compiled_expressions): compiled_expr = compiled_expressions.get(expr, None) if",
"Http # noqa: F401 from safetydance_test.step_extension import step_extension from scrud_django.models import Resource, ResourceType",
"http_response.json() assert response == resource_data, response def response_json_matches(expected): observed = http_response.json() assert json_values_match(expected,",
"resource_json_is(resource_data): response = http_response.json() assert response == resource_data, response def response_json_matches(expected): observed =",
"len(json_path_match) > 0, data match = json_path_match[0].value assert condition( json_path_match ), f\"expr: {expr}",
"assert result.slug == resource_type_name assert result.context_uri == expected['json_ld_context_url'] assert result.schema_uri == expected['json_schema_url'] def",
"list(expected.keys())[0] expected = expected[resource_type_name] assert result.type_uri == expected['rdf_type_uri'] assert result.slug == resource_type_name assert",
"assert json_values_match(expected, observed), http_response resource_envelope_json_is = step_extension( f=resource_envelope_json_is, target_type=Http ) resource_json_is = step_extension(f=resource_json_is,",
"assert superclass_uri in superclasses, superclasses # register named_registration_data = step_data(dict, initializer=dict) @step_extension def",
"def check_registration_results(name: str, result): expected = named_registration_data[name] # result = register_resource_type(**expected) resource_type_name =",
"= [ 'an_instance_named', 'is_valid_resource', 'is_valid_resource_type', 'an_registration_data', 'check_registration_results', 'json_path_expressions', 'json_path_match', 'json_path_matches', 'ld_context_states_sub_class_of', 'named_instances', 'resource_json_is',",
"@step_extension def ld_context_states_sub_class_of(subclass_uri, superclass_uri): data = http_response.json() g = Graph().parse(data=json.dumps(data), format='json-ld') superclasses =",
"'is_valid_resource', 'is_valid_resource_type', 'an_registration_data', 'check_registration_results', 'json_path_expressions', 'json_path_match', 'json_path_matches', 'ld_context_states_sub_class_of', 'named_instances', 'resource_json_is', 'response_json_matches', ] named_instances",
"= json_path_match[0].value assert condition( json_path_match ), f\"expr: {expr} \\ncondition: {condition}, \\n match: {match}\"",
"http_response, json_values_match, ) from safetydance_django.test import Http # noqa: F401 from safetydance_test.step_extension import",
"an_instance_named(name: str, instance: Model): named_instances[name] = instance @step_extension def is_valid_resource(name: str): instance =",
"instance: Model): named_instances[name] = instance @step_extension def is_valid_resource(name: str): instance = named_instances[name] assert",
"compiled_expr return compiled_expr @step_extension def json_path_matches(expr, condition): data = http_response.json() compiled_expr = get_compiled_expression(expr,",
"assert result.type_uri == expected['rdf_type_uri'] assert result.slug == resource_type_name assert result.context_uri == expected['json_ld_context_url'] assert",
"compiled_expr = compiled_expressions.get(expr, None) if compiled_expr is None: compiled_expr = parse(expr) compiled_expressions[expr] =",
"resource_data assert isinstance(resource_data['etag'], str) assert 'content' in resource_data assert isinstance(resource_data['content'], dict) response =",
"= step_data(object) sub_class_of = URIRef(\"http://www.w3.org/2000/01/rdf-schema#subClassOf\") @step_extension def an_instance_named(name: str, instance: Model): named_instances[name] =",
"str): instance = named_instances[name] assert isinstance(instance, Resource) assert isinstance(instance.content, dict) assert isinstance(instance.modified_at, datetime)",
"Resource) assert isinstance(instance.content, dict) assert isinstance(instance.modified_at, datetime) assert isinstance(instance.etag, str) assert len(instance.etag) ==",
"== expected['rdf_type_uri'] assert result.slug == resource_type_name assert result.context_uri == expected['json_ld_context_url'] assert result.schema_uri ==",
"import parse from rdflib import Graph, URIRef from safetydance import step_data from safetydance_django.steps",
"== expected['json_ld_context_url'] assert result.schema_uri == expected['json_schema_url'] def get_compiled_expression(expr, compiled_expressions): compiled_expr = compiled_expressions.get(expr, None)",
"= instance @step_extension def is_valid_resource(name: str): instance = named_instances[name] assert isinstance(instance, Resource) assert",
"return compiled_expr @step_extension def json_path_matches(expr, condition): data = http_response.json() compiled_expr = get_compiled_expression(expr, json_path_expressions)",
"list(g.transitive_objects(subclass_uri, sub_class_of)) assert len(superclasses) > 0, superclasses assert superclass_uri in superclasses, superclasses #",
"assert result.schema_uri == expected['json_schema_url'] def get_compiled_expression(expr, compiled_expressions): compiled_expr = compiled_expressions.get(expr, None) if compiled_expr",
"datetime) assert isinstance(instance.etag, str) assert len(instance.etag) == 32 @step_extension def is_valid_resource_type(name: str): instance",
"= http_response.json() compiled_expr = get_compiled_expression(expr, json_path_expressions) json_path_match = compiled_expr.find(data) assert len(json_path_match) > 0,",
"import json from datetime import datetime from django.db.models import Model from jsonpath_ng import",
"compiled_expr = get_compiled_expression(expr, json_path_expressions) json_path_match = compiled_expr.find(data) assert len(json_path_match) > 0, data match",
"response[\"content\"] == resource_data[\"content\"] def resource_json_is(resource_data): response = http_response.json() assert response == resource_data, response",
"def get_compiled_expression(expr, compiled_expressions): compiled_expr = compiled_expressions.get(expr, None) if compiled_expr is None: compiled_expr =",
"safetydance_test.step_extension import step_extension from scrud_django.models import Resource, ResourceType __all__ = [ 'an_instance_named', 'is_valid_resource',",
"# register named_registration_data = step_data(dict, initializer=dict) @step_extension def an_registration_data(name: str, registration_data: dict): named_registration_data[name]",
"register_resource_type(**expected) resource_type_name = list(expected.keys())[0] expected = expected[resource_type_name] assert result.type_uri == expected['rdf_type_uri'] assert result.slug",
"'href' in resource_data assert isinstance(resource_data['href'], str) assert 'last_modified' in resource_data assert isinstance(resource_data['last_modified'], str)",
"compiled_expressions): compiled_expr = compiled_expressions.get(expr, None) if compiled_expr is None: compiled_expr = parse(expr) compiled_expressions[expr]",
"= list(g.transitive_objects(subclass_uri, sub_class_of)) assert len(superclasses) > 0, superclasses assert superclass_uri in superclasses, superclasses",
"resource_data assert isinstance(resource_data['content'], dict) response = http_response.json() assert response[\"content\"] == resource_data[\"content\"] def resource_json_is(resource_data):",
"assert isinstance(resource_data['content'], dict) response = http_response.json() assert response[\"content\"] == resource_data[\"content\"] def resource_json_is(resource_data): response",
"from scrud_django.models import Resource, ResourceType __all__ = [ 'an_instance_named', 'is_valid_resource', 'is_valid_resource_type', 'an_registration_data', 'check_registration_results',",
"resource_data[\"content\"] def resource_json_is(resource_data): response = http_response.json() assert response == resource_data, response def response_json_matches(expected):",
"# noqa: F401 from safetydance_test.step_extension import step_extension from scrud_django.models import Resource, ResourceType __all__",
"'an_instance_named', 'is_valid_resource', 'is_valid_resource_type', 'an_registration_data', 'check_registration_results', 'json_path_expressions', 'json_path_match', 'json_path_matches', 'ld_context_states_sub_class_of', 'named_instances', 'resource_json_is', 'response_json_matches', ]",
"@step_extension def an_instance_named(name: str, instance: Model): named_instances[name] = instance @step_extension def is_valid_resource(name: str):",
"expected = expected[resource_type_name] assert result.type_uri == expected['rdf_type_uri'] assert result.slug == resource_type_name assert result.context_uri",
"named_instances[name] = instance @step_extension def is_valid_resource(name: str): instance = named_instances[name] assert isinstance(instance, Resource)",
"def is_valid_resource_type(name: str): instance = named_instances[name] assert isinstance(instance, ResourceType) assert isinstance(instance.type_uri, str) assert",
"'resource_json_is', 'response_json_matches', ] named_instances = step_data(dict, initializer=dict) json_path_expressions = step_data(dict, initializer=dict) json_path_match =",
"step_data from safetydance_django.steps import ( # noqa: F401 http_client, http_response, json_values_match, ) from",
"def resource_envelope_json_is(resource_data: dict): assert 'href' in resource_data assert isinstance(resource_data['href'], str) assert 'last_modified' in",
"URIRef from safetydance import step_data from safetydance_django.steps import ( # noqa: F401 http_client,",
"isinstance(instance.type_uri, str) assert len(instance.type_uri) > 0 @step_extension def ld_context_states_sub_class_of(subclass_uri, superclass_uri): data = http_response.json()",
"== resource_data, response def response_json_matches(expected): observed = http_response.json() assert json_values_match(expected, observed), http_response resource_envelope_json_is",
"json_path_match[0].value assert condition( json_path_match ), f\"expr: {expr} \\ncondition: {condition}, \\n match: {match}\" def",
"datetime import datetime from django.db.models import Model from jsonpath_ng import parse from rdflib",
"json_path_expressions) json_path_match = compiled_expr.find(data) assert len(json_path_match) > 0, data match = json_path_match[0].value assert",
"'is_valid_resource_type', 'an_registration_data', 'check_registration_results', 'json_path_expressions', 'json_path_match', 'json_path_matches', 'ld_context_states_sub_class_of', 'named_instances', 'resource_json_is', 'response_json_matches', ] named_instances =",
"{expr} \\ncondition: {condition}, \\n match: {match}\" def resource_envelope_json_is(resource_data: dict): assert 'href' in resource_data",
"def an_instance_named(name: str, instance: Model): named_instances[name] = instance @step_extension def is_valid_resource(name: str): instance",
"instance @step_extension def is_valid_resource(name: str): instance = named_instances[name] assert isinstance(instance, Resource) assert isinstance(instance.content,",
"Resource, ResourceType __all__ = [ 'an_instance_named', 'is_valid_resource', 'is_valid_resource_type', 'an_registration_data', 'check_registration_results', 'json_path_expressions', 'json_path_match', 'json_path_matches',",
"assert len(json_path_match) > 0, data match = json_path_match[0].value assert condition( json_path_match ), f\"expr:",
"isinstance(instance.etag, str) assert len(instance.etag) == 32 @step_extension def is_valid_resource_type(name: str): instance = named_instances[name]",
"step_data(dict, initializer=dict) json_path_match = step_data(object) sub_class_of = URIRef(\"http://www.w3.org/2000/01/rdf-schema#subClassOf\") @step_extension def an_instance_named(name: str, instance:",
"expected = named_registration_data[name] # result = register_resource_type(**expected) resource_type_name = list(expected.keys())[0] expected = expected[resource_type_name]",
"resource_data assert isinstance(resource_data['last_modified'], str) assert 'etag' in resource_data assert isinstance(resource_data['etag'], str) assert 'content'",
"named_registration_data[name] # result = register_resource_type(**expected) resource_type_name = list(expected.keys())[0] expected = expected[resource_type_name] assert result.type_uri",
"@step_extension def is_valid_resource_type(name: str): instance = named_instances[name] assert isinstance(instance, ResourceType) assert isinstance(instance.type_uri, str)",
"http_response.json() assert response[\"content\"] == resource_data[\"content\"] def resource_json_is(resource_data): response = http_response.json() assert response ==",
"== expected['json_schema_url'] def get_compiled_expression(expr, compiled_expressions): compiled_expr = compiled_expressions.get(expr, None) if compiled_expr is None:",
"match = json_path_match[0].value assert condition( json_path_match ), f\"expr: {expr} \\ncondition: {condition}, \\n match:",
"isinstance(instance.modified_at, datetime) assert isinstance(instance.etag, str) assert len(instance.etag) == 32 @step_extension def is_valid_resource_type(name: str):",
"from safetydance_django.steps import ( # noqa: F401 http_client, http_response, json_values_match, ) from safetydance_django.test",
"superclass_uri): data = http_response.json() g = Graph().parse(data=json.dumps(data), format='json-ld') superclasses = list(g.transitive_objects(subclass_uri, sub_class_of)) assert",
"assert len(instance.type_uri) > 0 @step_extension def ld_context_states_sub_class_of(subclass_uri, superclass_uri): data = http_response.json() g =",
"] named_instances = step_data(dict, initializer=dict) json_path_expressions = step_data(dict, initializer=dict) json_path_match = step_data(object) sub_class_of",
"'etag' in resource_data assert isinstance(resource_data['etag'], str) assert 'content' in resource_data assert isinstance(resource_data['content'], dict)",
"str) assert 'etag' in resource_data assert isinstance(resource_data['etag'], str) assert 'content' in resource_data assert",
"from safetydance_django.test import Http # noqa: F401 from safetydance_test.step_extension import step_extension from scrud_django.models",
"= http_response.json() g = Graph().parse(data=json.dumps(data), format='json-ld') superclasses = list(g.transitive_objects(subclass_uri, sub_class_of)) assert len(superclasses) >",
"= http_response.json() assert response == resource_data, response def response_json_matches(expected): observed = http_response.json() assert",
"result.slug == resource_type_name assert result.context_uri == expected['json_ld_context_url'] assert result.schema_uri == expected['json_schema_url'] def get_compiled_expression(expr,",
"assert isinstance(instance.type_uri, str) assert len(instance.type_uri) > 0 @step_extension def ld_context_states_sub_class_of(subclass_uri, superclass_uri): data =",
"isinstance(instance.content, dict) assert isinstance(instance.modified_at, datetime) assert isinstance(instance.etag, str) assert len(instance.etag) == 32 @step_extension",
"jsonpath_ng import parse from rdflib import Graph, URIRef from safetydance import step_data from",
"assert condition( json_path_match ), f\"expr: {expr} \\ncondition: {condition}, \\n match: {match}\" def resource_envelope_json_is(resource_data:",
"Model from jsonpath_ng import parse from rdflib import Graph, URIRef from safetydance import",
"0, data match = json_path_match[0].value assert condition( json_path_match ), f\"expr: {expr} \\ncondition: {condition},",
"== 32 @step_extension def is_valid_resource_type(name: str): instance = named_instances[name] assert isinstance(instance, ResourceType) assert",
"str) assert len(instance.type_uri) > 0 @step_extension def ld_context_states_sub_class_of(subclass_uri, superclass_uri): data = http_response.json() g",
"assert response == resource_data, response def response_json_matches(expected): observed = http_response.json() assert json_values_match(expected, observed),",
"= step_data(dict, initializer=dict) json_path_match = step_data(object) sub_class_of = URIRef(\"http://www.w3.org/2000/01/rdf-schema#subClassOf\") @step_extension def an_instance_named(name: str,",
"format='json-ld') superclasses = list(g.transitive_objects(subclass_uri, sub_class_of)) assert len(superclasses) > 0, superclasses assert superclass_uri in",
"assert isinstance(resource_data['etag'], str) assert 'content' in resource_data assert isinstance(resource_data['content'], dict) response = http_response.json()",
"'check_registration_results', 'json_path_expressions', 'json_path_match', 'json_path_matches', 'ld_context_states_sub_class_of', 'named_instances', 'resource_json_is', 'response_json_matches', ] named_instances = step_data(dict, initializer=dict)",
"step_data(dict, initializer=dict) @step_extension def an_registration_data(name: str, registration_data: dict): named_registration_data[name] = registration_data @step_extension def",
"expected[resource_type_name] assert result.type_uri == expected['rdf_type_uri'] assert result.slug == resource_type_name assert result.context_uri == expected['json_ld_context_url']",
"registration_data: dict): named_registration_data[name] = registration_data @step_extension def check_registration_results(name: str, result): expected = named_registration_data[name]",
"len(instance.type_uri) > 0 @step_extension def ld_context_states_sub_class_of(subclass_uri, superclass_uri): data = http_response.json() g = Graph().parse(data=json.dumps(data),",
"step_data(dict, initializer=dict) json_path_expressions = step_data(dict, initializer=dict) json_path_match = step_data(object) sub_class_of = URIRef(\"http://www.w3.org/2000/01/rdf-schema#subClassOf\") @step_extension",
"assert len(instance.etag) == 32 @step_extension def is_valid_resource_type(name: str): instance = named_instances[name] assert isinstance(instance,",
"assert 'etag' in resource_data assert isinstance(resource_data['etag'], str) assert 'content' in resource_data assert isinstance(resource_data['content'],",
"= compiled_expr return compiled_expr @step_extension def json_path_matches(expr, condition): data = http_response.json() compiled_expr =",
"\\n match: {match}\" def resource_envelope_json_is(resource_data: dict): assert 'href' in resource_data assert isinstance(resource_data['href'], str)",
"condition( json_path_match ), f\"expr: {expr} \\ncondition: {condition}, \\n match: {match}\" def resource_envelope_json_is(resource_data: dict):",
"observed = http_response.json() assert json_values_match(expected, observed), http_response resource_envelope_json_is = step_extension( f=resource_envelope_json_is, target_type=Http )",
"register named_registration_data = step_data(dict, initializer=dict) @step_extension def an_registration_data(name: str, registration_data: dict): named_registration_data[name] =",
"isinstance(resource_data['href'], str) assert 'last_modified' in resource_data assert isinstance(resource_data['last_modified'], str) assert 'etag' in resource_data",
"'last_modified' in resource_data assert isinstance(resource_data['last_modified'], str) assert 'etag' in resource_data assert isinstance(resource_data['etag'], str)",
"django.db.models import Model from jsonpath_ng import parse from rdflib import Graph, URIRef from",
"data = http_response.json() compiled_expr = get_compiled_expression(expr, json_path_expressions) json_path_match = compiled_expr.find(data) assert len(json_path_match) >",
"import Model from jsonpath_ng import parse from rdflib import Graph, URIRef from safetydance",
"str) assert 'content' in resource_data assert isinstance(resource_data['content'], dict) response = http_response.json() assert response[\"content\"]",
"= expected[resource_type_name] assert result.type_uri == expected['rdf_type_uri'] assert result.slug == resource_type_name assert result.context_uri ==",
"http_response resource_envelope_json_is = step_extension( f=resource_envelope_json_is, target_type=Http ) resource_json_is = step_extension(f=resource_json_is, target_type=Http) response_json_matches =",
"str) assert 'last_modified' in resource_data assert isinstance(resource_data['last_modified'], str) assert 'etag' in resource_data assert",
"from safetydance_test.step_extension import step_extension from scrud_django.models import Resource, ResourceType __all__ = [ 'an_instance_named',",
"an_registration_data(name: str, registration_data: dict): named_registration_data[name] = registration_data @step_extension def check_registration_results(name: str, result): expected",
"'ld_context_states_sub_class_of', 'named_instances', 'resource_json_is', 'response_json_matches', ] named_instances = step_data(dict, initializer=dict) json_path_expressions = step_data(dict, initializer=dict)",
"named_instances = step_data(dict, initializer=dict) json_path_expressions = step_data(dict, initializer=dict) json_path_match = step_data(object) sub_class_of =",
"'json_path_expressions', 'json_path_match', 'json_path_matches', 'ld_context_states_sub_class_of', 'named_instances', 'resource_json_is', 'response_json_matches', ] named_instances = step_data(dict, initializer=dict) json_path_expressions",
"= list(expected.keys())[0] expected = expected[resource_type_name] assert result.type_uri == expected['rdf_type_uri'] assert result.slug == resource_type_name",
"len(instance.etag) == 32 @step_extension def is_valid_resource_type(name: str): instance = named_instances[name] assert isinstance(instance, ResourceType)",
"resource_envelope_json_is = step_extension( f=resource_envelope_json_is, target_type=Http ) resource_json_is = step_extension(f=resource_json_is, target_type=Http) response_json_matches = step_extension(f=response_json_matches,",
"Model): named_instances[name] = instance @step_extension def is_valid_resource(name: str): instance = named_instances[name] assert isinstance(instance,",
"compiled_expr @step_extension def json_path_matches(expr, condition): data = http_response.json() compiled_expr = get_compiled_expression(expr, json_path_expressions) json_path_match",
"superclasses = list(g.transitive_objects(subclass_uri, sub_class_of)) assert len(superclasses) > 0, superclasses assert superclass_uri in superclasses,",
"parse(expr) compiled_expressions[expr] = compiled_expr return compiled_expr @step_extension def json_path_matches(expr, condition): data = http_response.json()",
"= compiled_expr.find(data) assert len(json_path_match) > 0, data match = json_path_match[0].value assert condition( json_path_match",
"= registration_data @step_extension def check_registration_results(name: str, result): expected = named_registration_data[name] # result =",
"json_values_match(expected, observed), http_response resource_envelope_json_is = step_extension( f=resource_envelope_json_is, target_type=Http ) resource_json_is = step_extension(f=resource_json_is, target_type=Http)",
"assert isinstance(instance, Resource) assert isinstance(instance.content, dict) assert isinstance(instance.modified_at, datetime) assert isinstance(instance.etag, str) assert",
"= step_data(dict, initializer=dict) @step_extension def an_registration_data(name: str, registration_data: dict): named_registration_data[name] = registration_data @step_extension",
"get_compiled_expression(expr, json_path_expressions) json_path_match = compiled_expr.find(data) assert len(json_path_match) > 0, data match = json_path_match[0].value",
"assert response[\"content\"] == resource_data[\"content\"] def resource_json_is(resource_data): response = http_response.json() assert response == resource_data,",
"'named_instances', 'resource_json_is', 'response_json_matches', ] named_instances = step_data(dict, initializer=dict) json_path_expressions = step_data(dict, initializer=dict) json_path_match"
] |
[
"app.utils.base_service import BaseService from .model import Entity from .interfaces import EntityInterfaces class EntityService(BaseService):",
".model import Entity from .interfaces import EntityInterfaces class EntityService(BaseService): model = Entity interfaces",
"BaseService from .model import Entity from .interfaces import EntityInterfaces class EntityService(BaseService): model =",
"Entity from .interfaces import EntityInterfaces class EntityService(BaseService): model = Entity interfaces = EntityInterfaces",
"import Entity from .interfaces import EntityInterfaces class EntityService(BaseService): model = Entity interfaces =",
"<gh_stars>0 from app.utils.base_service import BaseService from .model import Entity from .interfaces import EntityInterfaces",
"from .model import Entity from .interfaces import EntityInterfaces class EntityService(BaseService): model = Entity",
"import BaseService from .model import Entity from .interfaces import EntityInterfaces class EntityService(BaseService): model",
"from app.utils.base_service import BaseService from .model import Entity from .interfaces import EntityInterfaces class"
] |
[
"django.urls import path # Localfolder Library from .views.paypal_config import UpdatePaypalConfigView # http://www.secnot.com/django-shop-paypal-rest-1.html app_name",
"import path # Localfolder Library from .views.paypal_config import UpdatePaypalConfigView # http://www.secnot.com/django-shop-paypal-rest-1.html app_name =",
"Library from .views.paypal_config import UpdatePaypalConfigView # http://www.secnot.com/django-shop-paypal-rest-1.html app_name = 'paypal' urlpatterns = [",
"path # Localfolder Library from .views.paypal_config import UpdatePaypalConfigView # http://www.secnot.com/django-shop-paypal-rest-1.html app_name = 'paypal'",
"Localfolder Library from .views.paypal_config import UpdatePaypalConfigView # http://www.secnot.com/django-shop-paypal-rest-1.html app_name = 'paypal' urlpatterns =",
".views.paypal_config import UpdatePaypalConfigView # http://www.secnot.com/django-shop-paypal-rest-1.html app_name = 'paypal' urlpatterns = [ path('paypal-config/<int:pk>', UpdatePaypalConfigView.as_view(),",
"# Django Library from django.urls import path # Localfolder Library from .views.paypal_config import",
"from .views.paypal_config import UpdatePaypalConfigView # http://www.secnot.com/django-shop-paypal-rest-1.html app_name = 'paypal' urlpatterns = [ path('paypal-config/<int:pk>',",
"import UpdatePaypalConfigView # http://www.secnot.com/django-shop-paypal-rest-1.html app_name = 'paypal' urlpatterns = [ path('paypal-config/<int:pk>', UpdatePaypalConfigView.as_view(), name='paypal-config'),",
"from django.urls import path # Localfolder Library from .views.paypal_config import UpdatePaypalConfigView # http://www.secnot.com/django-shop-paypal-rest-1.html",
"UpdatePaypalConfigView # http://www.secnot.com/django-shop-paypal-rest-1.html app_name = 'paypal' urlpatterns = [ path('paypal-config/<int:pk>', UpdatePaypalConfigView.as_view(), name='paypal-config'), ]",
"Django Library from django.urls import path # Localfolder Library from .views.paypal_config import UpdatePaypalConfigView",
"# Localfolder Library from .views.paypal_config import UpdatePaypalConfigView # http://www.secnot.com/django-shop-paypal-rest-1.html app_name = 'paypal' urlpatterns",
"Library from django.urls import path # Localfolder Library from .views.paypal_config import UpdatePaypalConfigView #"
] |
[
"case id is valid\") text = str(re.sub(\"','|', '\", 'USCIS website', text)) status_message =",
"status_message) if p is not None: match = p.group(0) last_update_date = datetime.strptime(str(match), \"%B",
"= datetime.strptime(str(match), \"%B %d, %Y\") last_update_date = last_update_date.strftime('%m/%d/%Y') return {'status': status_message, 'date': last_update_date}",
"data=data) content = html.fromstring(r.content) text = str(content.xpath(UPDATE_TEXT_XPATH)) if len(text) < 2: raise ValueError(\"Please",
"import requests from datetime import datetime CASE_DATE_PATTERN = r\"[(A-Za-z)]*\\s[\\d]*,\\s[\\d]*\" URL = \"https://egov.uscis.gov/casestatus/mycasestatus.do\" APP_RECEIPT_NUM",
"you case id is valid\") text = str(re.sub(\"','|', '\", 'USCIS website', text)) status_message",
"'\", 'USCIS website', text)) status_message = re.sub(r\"['\\[\\]]\", ' ', text) p = re.search(CASE_DATE_PATTERN,",
"%Y\") last_update_date = last_update_date.strftime('%m/%d/%Y') return {'status': status_message, 'date': last_update_date} else: raise ValueError(\"Please make",
"make sure you case id is valid\") text = str(re.sub(\"','|', '\", 'USCIS website',",
"if len(text) < 2: raise ValueError(\"Please make sure you case id is valid\")",
"last_update_date.strftime('%m/%d/%Y') return {'status': status_message, 'date': last_update_date} else: raise ValueError(\"Please make sure you case",
"lxml import html import re import requests from datetime import datetime CASE_DATE_PATTERN =",
"status_message = re.sub(r\"['\\[\\]]\", ' ', text) p = re.search(CASE_DATE_PATTERN, status_message) if p is",
"r\"[(A-Za-z)]*\\s[\\d]*,\\s[\\d]*\" URL = \"https://egov.uscis.gov/casestatus/mycasestatus.do\" APP_RECEIPT_NUM = \"appReceiptNum\" INIT_CASE_SEARCH = \"initCaseSearch\" CASE_STATUS = \"CHECK",
"website', text)) status_message = re.sub(r\"['\\[\\]]\", ' ', text) p = re.search(CASE_DATE_PATTERN, status_message) if",
"\"appReceiptNum\" INIT_CASE_SEARCH = \"initCaseSearch\" CASE_STATUS = \"CHECK STATUS\" UPDATE_TEXT_XPATH = \"/html/body/div[2]/form/div/div[1]/div/div/div[2]/div[3]/p/text()\" MISSING_URL_PATTEN =",
"= {APP_RECEIPT_NUM: case_id, INIT_CASE_SEARCH: CASE_STATUS} r = requests.post(URL, data=data) content = html.fromstring(r.content) text",
"\"initCaseSearch\" CASE_STATUS = \"CHECK STATUS\" UPDATE_TEXT_XPATH = \"/html/body/div[2]/form/div/div[1]/div/div/div[2]/div[3]/p/text()\" MISSING_URL_PATTEN = \"','|', '\" TEXT_FILTER_PATTERN",
"p.group(0) last_update_date = datetime.strptime(str(match), \"%B %d, %Y\") last_update_date = last_update_date.strftime('%m/%d/%Y') return {'status': status_message,",
"len(text) < 2: raise ValueError(\"Please make sure you case id is valid\") text",
"text = str(content.xpath(UPDATE_TEXT_XPATH)) if len(text) < 2: raise ValueError(\"Please make sure you case",
"CASE_STATUS} r = requests.post(URL, data=data) content = html.fromstring(r.content) text = str(content.xpath(UPDATE_TEXT_XPATH)) if len(text)",
"raise ValueError(\"Please make sure you case id is valid\") text = str(re.sub(\"','|', '\",",
"not None: match = p.group(0) last_update_date = datetime.strptime(str(match), \"%B %d, %Y\") last_update_date =",
"re.sub(r\"['\\[\\]]\", ' ', text) p = re.search(CASE_DATE_PATTERN, status_message) if p is not None:",
"< 2: raise ValueError(\"Please make sure you case id is valid\") text =",
"<filename>uscisstatus/__init__.py from lxml import html import re import requests from datetime import datetime",
"' ', text) p = re.search(CASE_DATE_PATTERN, status_message) if p is not None: match",
"data = {APP_RECEIPT_NUM: case_id, INIT_CASE_SEARCH: CASE_STATUS} r = requests.post(URL, data=data) content = html.fromstring(r.content)",
"str(re.sub(\"','|', '\", 'USCIS website', text)) status_message = re.sub(r\"['\\[\\]]\", ' ', text) p =",
"= re.sub(r\"['\\[\\]]\", ' ', text) p = re.search(CASE_DATE_PATTERN, status_message) if p is not",
"= last_update_date.strftime('%m/%d/%Y') return {'status': status_message, 'date': last_update_date} else: raise ValueError(\"Please make sure you",
"%d, %Y\") last_update_date = last_update_date.strftime('%m/%d/%Y') return {'status': status_message, 'date': last_update_date} else: raise ValueError(\"Please",
"'\" TEXT_FILTER_PATTERN = r\"['\\[\\]]\" def get_case_status(case_id): data = {APP_RECEIPT_NUM: case_id, INIT_CASE_SEARCH: CASE_STATUS} r",
"requests.post(URL, data=data) content = html.fromstring(r.content) text = str(content.xpath(UPDATE_TEXT_XPATH)) if len(text) < 2: raise",
"if p is not None: match = p.group(0) last_update_date = datetime.strptime(str(match), \"%B %d,",
"UPDATE_TEXT_XPATH = \"/html/body/div[2]/form/div/div[1]/div/div/div[2]/div[3]/p/text()\" MISSING_URL_PATTEN = \"','|', '\" TEXT_FILTER_PATTERN = r\"['\\[\\]]\" def get_case_status(case_id): data",
"def get_case_status(case_id): data = {APP_RECEIPT_NUM: case_id, INIT_CASE_SEARCH: CASE_STATUS} r = requests.post(URL, data=data) content",
"html.fromstring(r.content) text = str(content.xpath(UPDATE_TEXT_XPATH)) if len(text) < 2: raise ValueError(\"Please make sure you",
"r\"['\\[\\]]\" def get_case_status(case_id): data = {APP_RECEIPT_NUM: case_id, INIT_CASE_SEARCH: CASE_STATUS} r = requests.post(URL, data=data)",
"return {'status': status_message, 'date': last_update_date} else: raise ValueError(\"Please make sure you case id",
"re import requests from datetime import datetime CASE_DATE_PATTERN = r\"[(A-Za-z)]*\\s[\\d]*,\\s[\\d]*\" URL = \"https://egov.uscis.gov/casestatus/mycasestatus.do\"",
"\"CHECK STATUS\" UPDATE_TEXT_XPATH = \"/html/body/div[2]/form/div/div[1]/div/div/div[2]/div[3]/p/text()\" MISSING_URL_PATTEN = \"','|', '\" TEXT_FILTER_PATTERN = r\"['\\[\\]]\" def",
"', text) p = re.search(CASE_DATE_PATTERN, status_message) if p is not None: match =",
"html import re import requests from datetime import datetime CASE_DATE_PATTERN = r\"[(A-Za-z)]*\\s[\\d]*,\\s[\\d]*\" URL",
"match = p.group(0) last_update_date = datetime.strptime(str(match), \"%B %d, %Y\") last_update_date = last_update_date.strftime('%m/%d/%Y') return",
"valid\") text = str(re.sub(\"','|', '\", 'USCIS website', text)) status_message = re.sub(r\"['\\[\\]]\", ' ',",
"= r\"[(A-Za-z)]*\\s[\\d]*,\\s[\\d]*\" URL = \"https://egov.uscis.gov/casestatus/mycasestatus.do\" APP_RECEIPT_NUM = \"appReceiptNum\" INIT_CASE_SEARCH = \"initCaseSearch\" CASE_STATUS =",
"r = requests.post(URL, data=data) content = html.fromstring(r.content) text = str(content.xpath(UPDATE_TEXT_XPATH)) if len(text) <",
"import html import re import requests from datetime import datetime CASE_DATE_PATTERN = r\"[(A-Za-z)]*\\s[\\d]*,\\s[\\d]*\"",
"'USCIS website', text)) status_message = re.sub(r\"['\\[\\]]\", ' ', text) p = re.search(CASE_DATE_PATTERN, status_message)",
"from datetime import datetime CASE_DATE_PATTERN = r\"[(A-Za-z)]*\\s[\\d]*,\\s[\\d]*\" URL = \"https://egov.uscis.gov/casestatus/mycasestatus.do\" APP_RECEIPT_NUM = \"appReceiptNum\"",
"TEXT_FILTER_PATTERN = r\"['\\[\\]]\" def get_case_status(case_id): data = {APP_RECEIPT_NUM: case_id, INIT_CASE_SEARCH: CASE_STATUS} r =",
"last_update_date = last_update_date.strftime('%m/%d/%Y') return {'status': status_message, 'date': last_update_date} else: raise ValueError(\"Please make sure",
"= html.fromstring(r.content) text = str(content.xpath(UPDATE_TEXT_XPATH)) if len(text) < 2: raise ValueError(\"Please make sure",
"from lxml import html import re import requests from datetime import datetime CASE_DATE_PATTERN",
"INIT_CASE_SEARCH: CASE_STATUS} r = requests.post(URL, data=data) content = html.fromstring(r.content) text = str(content.xpath(UPDATE_TEXT_XPATH)) if",
"import re import requests from datetime import datetime CASE_DATE_PATTERN = r\"[(A-Za-z)]*\\s[\\d]*,\\s[\\d]*\" URL =",
"last_update_date = datetime.strptime(str(match), \"%B %d, %Y\") last_update_date = last_update_date.strftime('%m/%d/%Y') return {'status': status_message, 'date':",
"CASE_DATE_PATTERN = r\"[(A-Za-z)]*\\s[\\d]*,\\s[\\d]*\" URL = \"https://egov.uscis.gov/casestatus/mycasestatus.do\" APP_RECEIPT_NUM = \"appReceiptNum\" INIT_CASE_SEARCH = \"initCaseSearch\" CASE_STATUS",
"= \"appReceiptNum\" INIT_CASE_SEARCH = \"initCaseSearch\" CASE_STATUS = \"CHECK STATUS\" UPDATE_TEXT_XPATH = \"/html/body/div[2]/form/div/div[1]/div/div/div[2]/div[3]/p/text()\" MISSING_URL_PATTEN",
"id is valid\") text = str(re.sub(\"','|', '\", 'USCIS website', text)) status_message = re.sub(r\"['\\[\\]]\",",
"text)) status_message = re.sub(r\"['\\[\\]]\", ' ', text) p = re.search(CASE_DATE_PATTERN, status_message) if p",
"= \"initCaseSearch\" CASE_STATUS = \"CHECK STATUS\" UPDATE_TEXT_XPATH = \"/html/body/div[2]/form/div/div[1]/div/div/div[2]/div[3]/p/text()\" MISSING_URL_PATTEN = \"','|', '\"",
"sure you case id is valid\") text = str(re.sub(\"','|', '\", 'USCIS website', text))",
"datetime CASE_DATE_PATTERN = r\"[(A-Za-z)]*\\s[\\d]*,\\s[\\d]*\" URL = \"https://egov.uscis.gov/casestatus/mycasestatus.do\" APP_RECEIPT_NUM = \"appReceiptNum\" INIT_CASE_SEARCH = \"initCaseSearch\"",
"p is not None: match = p.group(0) last_update_date = datetime.strptime(str(match), \"%B %d, %Y\")",
"\"%B %d, %Y\") last_update_date = last_update_date.strftime('%m/%d/%Y') return {'status': status_message, 'date': last_update_date} else: raise",
"import datetime CASE_DATE_PATTERN = r\"[(A-Za-z)]*\\s[\\d]*,\\s[\\d]*\" URL = \"https://egov.uscis.gov/casestatus/mycasestatus.do\" APP_RECEIPT_NUM = \"appReceiptNum\" INIT_CASE_SEARCH =",
"{APP_RECEIPT_NUM: case_id, INIT_CASE_SEARCH: CASE_STATUS} r = requests.post(URL, data=data) content = html.fromstring(r.content) text =",
"is valid\") text = str(re.sub(\"','|', '\", 'USCIS website', text)) status_message = re.sub(r\"['\\[\\]]\", '",
"None: match = p.group(0) last_update_date = datetime.strptime(str(match), \"%B %d, %Y\") last_update_date = last_update_date.strftime('%m/%d/%Y')",
"text = str(re.sub(\"','|', '\", 'USCIS website', text)) status_message = re.sub(r\"['\\[\\]]\", ' ', text)",
"datetime import datetime CASE_DATE_PATTERN = r\"[(A-Za-z)]*\\s[\\d]*,\\s[\\d]*\" URL = \"https://egov.uscis.gov/casestatus/mycasestatus.do\" APP_RECEIPT_NUM = \"appReceiptNum\" INIT_CASE_SEARCH",
"= \"/html/body/div[2]/form/div/div[1]/div/div/div[2]/div[3]/p/text()\" MISSING_URL_PATTEN = \"','|', '\" TEXT_FILTER_PATTERN = r\"['\\[\\]]\" def get_case_status(case_id): data =",
"datetime.strptime(str(match), \"%B %d, %Y\") last_update_date = last_update_date.strftime('%m/%d/%Y') return {'status': status_message, 'date': last_update_date} else:",
"= str(content.xpath(UPDATE_TEXT_XPATH)) if len(text) < 2: raise ValueError(\"Please make sure you case id",
"INIT_CASE_SEARCH = \"initCaseSearch\" CASE_STATUS = \"CHECK STATUS\" UPDATE_TEXT_XPATH = \"/html/body/div[2]/form/div/div[1]/div/div/div[2]/div[3]/p/text()\" MISSING_URL_PATTEN = \"','|',",
"requests from datetime import datetime CASE_DATE_PATTERN = r\"[(A-Za-z)]*\\s[\\d]*,\\s[\\d]*\" URL = \"https://egov.uscis.gov/casestatus/mycasestatus.do\" APP_RECEIPT_NUM =",
"APP_RECEIPT_NUM = \"appReceiptNum\" INIT_CASE_SEARCH = \"initCaseSearch\" CASE_STATUS = \"CHECK STATUS\" UPDATE_TEXT_XPATH = \"/html/body/div[2]/form/div/div[1]/div/div/div[2]/div[3]/p/text()\"",
"= re.search(CASE_DATE_PATTERN, status_message) if p is not None: match = p.group(0) last_update_date =",
"URL = \"https://egov.uscis.gov/casestatus/mycasestatus.do\" APP_RECEIPT_NUM = \"appReceiptNum\" INIT_CASE_SEARCH = \"initCaseSearch\" CASE_STATUS = \"CHECK STATUS\"",
"MISSING_URL_PATTEN = \"','|', '\" TEXT_FILTER_PATTERN = r\"['\\[\\]]\" def get_case_status(case_id): data = {APP_RECEIPT_NUM: case_id,",
"= \"','|', '\" TEXT_FILTER_PATTERN = r\"['\\[\\]]\" def get_case_status(case_id): data = {APP_RECEIPT_NUM: case_id, INIT_CASE_SEARCH:",
"= r\"['\\[\\]]\" def get_case_status(case_id): data = {APP_RECEIPT_NUM: case_id, INIT_CASE_SEARCH: CASE_STATUS} r = requests.post(URL,",
"\"/html/body/div[2]/form/div/div[1]/div/div/div[2]/div[3]/p/text()\" MISSING_URL_PATTEN = \"','|', '\" TEXT_FILTER_PATTERN = r\"['\\[\\]]\" def get_case_status(case_id): data = {APP_RECEIPT_NUM:",
"case_id, INIT_CASE_SEARCH: CASE_STATUS} r = requests.post(URL, data=data) content = html.fromstring(r.content) text = str(content.xpath(UPDATE_TEXT_XPATH))",
"CASE_STATUS = \"CHECK STATUS\" UPDATE_TEXT_XPATH = \"/html/body/div[2]/form/div/div[1]/div/div/div[2]/div[3]/p/text()\" MISSING_URL_PATTEN = \"','|', '\" TEXT_FILTER_PATTERN =",
"\"','|', '\" TEXT_FILTER_PATTERN = r\"['\\[\\]]\" def get_case_status(case_id): data = {APP_RECEIPT_NUM: case_id, INIT_CASE_SEARCH: CASE_STATUS}",
"= \"CHECK STATUS\" UPDATE_TEXT_XPATH = \"/html/body/div[2]/form/div/div[1]/div/div/div[2]/div[3]/p/text()\" MISSING_URL_PATTEN = \"','|', '\" TEXT_FILTER_PATTERN = r\"['\\[\\]]\"",
"STATUS\" UPDATE_TEXT_XPATH = \"/html/body/div[2]/form/div/div[1]/div/div/div[2]/div[3]/p/text()\" MISSING_URL_PATTEN = \"','|', '\" TEXT_FILTER_PATTERN = r\"['\\[\\]]\" def get_case_status(case_id):",
"status_message, 'date': last_update_date} else: raise ValueError(\"Please make sure you case id is valid\")",
"get_case_status(case_id): data = {APP_RECEIPT_NUM: case_id, INIT_CASE_SEARCH: CASE_STATUS} r = requests.post(URL, data=data) content =",
"is not None: match = p.group(0) last_update_date = datetime.strptime(str(match), \"%B %d, %Y\") last_update_date",
"= p.group(0) last_update_date = datetime.strptime(str(match), \"%B %d, %Y\") last_update_date = last_update_date.strftime('%m/%d/%Y') return {'status':",
"= requests.post(URL, data=data) content = html.fromstring(r.content) text = str(content.xpath(UPDATE_TEXT_XPATH)) if len(text) < 2:",
"str(content.xpath(UPDATE_TEXT_XPATH)) if len(text) < 2: raise ValueError(\"Please make sure you case id is",
"text) p = re.search(CASE_DATE_PATTERN, status_message) if p is not None: match = p.group(0)",
"p = re.search(CASE_DATE_PATTERN, status_message) if p is not None: match = p.group(0) last_update_date",
"2: raise ValueError(\"Please make sure you case id is valid\") text = str(re.sub(\"','|',",
"= \"https://egov.uscis.gov/casestatus/mycasestatus.do\" APP_RECEIPT_NUM = \"appReceiptNum\" INIT_CASE_SEARCH = \"initCaseSearch\" CASE_STATUS = \"CHECK STATUS\" UPDATE_TEXT_XPATH",
"{'status': status_message, 'date': last_update_date} else: raise ValueError(\"Please make sure you case id is",
"\"https://egov.uscis.gov/casestatus/mycasestatus.do\" APP_RECEIPT_NUM = \"appReceiptNum\" INIT_CASE_SEARCH = \"initCaseSearch\" CASE_STATUS = \"CHECK STATUS\" UPDATE_TEXT_XPATH =",
"content = html.fromstring(r.content) text = str(content.xpath(UPDATE_TEXT_XPATH)) if len(text) < 2: raise ValueError(\"Please make",
"ValueError(\"Please make sure you case id is valid\") text = str(re.sub(\"','|', '\", 'USCIS",
"re.search(CASE_DATE_PATTERN, status_message) if p is not None: match = p.group(0) last_update_date = datetime.strptime(str(match),",
"= str(re.sub(\"','|', '\", 'USCIS website', text)) status_message = re.sub(r\"['\\[\\]]\", ' ', text) p"
] |
[
"def fromFile(self, f): ## Parse XML ## logging.info(\"Reading from scene file `%s'.\", f)",
"in child.attrib: key = child.attrib[\"key\"] if key in self.metaData: raise SceneFileException(\"MetaData key already",
"must have key attribute.\") elif child.tag == \"command\": if (\"start\" in child.attrib) and",
"{} commands = {} def fromFile(self, f): ## Parse XML ## logging.info(\"Reading from",
"from scene file `%s'.\", f) tree = ET.parse(f) root = tree.getroot() ## Check",
"Get children ## for child in root: ## Check element name ## if",
"as ET from Exceptions import SceneFileException import SceneCommands class Scene(object): metaData = {}",
"## Check root element (scene) ## if root.tag != \"scene\": raise SceneFileException(\"Root tag",
"child.attrib[\"key\"] if key in self.metaData: raise SceneFileException(\"MetaData key already exists: %s.\" % key)",
"import logging import xml.etree.ElementTree as ET from Exceptions import SceneFileException import SceneCommands class",
"tag must have key attribute.\") elif child.tag == \"command\": if (\"start\" in child.attrib)",
"logging import xml.etree.ElementTree as ET from Exceptions import SceneFileException import SceneCommands class Scene(object):",
"in self.commands: self.commands[key] = [] self.commands[key].append(SceneCommands.Helpers.get(child.attrib[\"value\"])) else: raise SceneFileException(\"Command tag must have start",
"SceneFileException import SceneCommands class Scene(object): metaData = {} commands = {} def fromFile(self,",
"start and value attributes.\") else: raise SceneFileException(\"Child tag must be named meta or",
"in l[1]: tmp = l[0] + c.getDuration() if tmp > dur: dur =",
"raise SceneFileException(\"MetaData key already exists: %s.\" % key) else: self.metaData[key] = child.text else:",
"SceneFileException(\"Root tag must be named scene.\") ## Get children ## for child in",
"for l in self.commands.items(): for c in l[1]: tmp = l[0] + c.getDuration()",
"ET from Exceptions import SceneFileException import SceneCommands class Scene(object): metaData = {} commands",
"self.metaData: raise SceneFileException(\"MetaData key already exists: %s.\" % key) else: self.metaData[key] = child.text",
"Scene(object): metaData = {} commands = {} def fromFile(self, f): ## Parse XML",
"self.commands.items(): for c in l[1]: tmp = l[0] + c.getDuration() if tmp >",
"if child.tag == \"meta\": if \"key\" in child.attrib: key = child.attrib[\"key\"] if key",
"key) else: self.metaData[key] = child.text else: raise SceneFileException(\"Meta tag must have key attribute.\")",
"f) tree = ET.parse(f) root = tree.getroot() ## Check root element (scene) ##",
"tag must be named scene.\") ## Get children ## for child in root:",
"!= \"scene\": raise SceneFileException(\"Root tag must be named scene.\") ## Get children ##",
"child.attrib): key = int(child.attrib[\"start\"]) if not key in self.commands: self.commands[key] = [] self.commands[key].append(SceneCommands.Helpers.get(child.attrib[\"value\"]))",
"must have start and value attributes.\") else: raise SceneFileException(\"Child tag must be named",
"= child.text else: raise SceneFileException(\"Meta tag must have key attribute.\") elif child.tag ==",
"key in self.commands: self.commands[key] = [] self.commands[key].append(SceneCommands.Helpers.get(child.attrib[\"value\"])) else: raise SceneFileException(\"Command tag must have",
"children ## for child in root: ## Check element name ## if child.tag",
"scene.\") ## Get children ## for child in root: ## Check element name",
"element name ## if child.tag == \"meta\": if \"key\" in child.attrib: key =",
"child.text else: raise SceneFileException(\"Meta tag must have key attribute.\") elif child.tag == \"command\":",
"l in self.commands.items(): for c in l[1]: tmp = l[0] + c.getDuration() if",
"child.attrib: key = child.attrib[\"key\"] if key in self.metaData: raise SceneFileException(\"MetaData key already exists:",
"0 for l in self.commands.items(): for c in l[1]: tmp = l[0] +",
"int(child.attrib[\"start\"]) if not key in self.commands: self.commands[key] = [] self.commands[key].append(SceneCommands.Helpers.get(child.attrib[\"value\"])) else: raise SceneFileException(\"Command",
"self.commands[key] = [] self.commands[key].append(SceneCommands.Helpers.get(child.attrib[\"value\"])) else: raise SceneFileException(\"Command tag must have start and value",
"exists: %s.\" % key) else: self.metaData[key] = child.text else: raise SceneFileException(\"Meta tag must",
"from Exceptions import SceneFileException import SceneCommands class Scene(object): metaData = {} commands =",
"`%s'.\", f) tree = ET.parse(f) root = tree.getroot() ## Check root element (scene)",
"{} def fromFile(self, f): ## Parse XML ## logging.info(\"Reading from scene file `%s'.\",",
"SceneCommands class Scene(object): metaData = {} commands = {} def fromFile(self, f): ##",
"root element (scene) ## if root.tag != \"scene\": raise SceneFileException(\"Root tag must be",
"root.tag != \"scene\": raise SceneFileException(\"Root tag must be named scene.\") ## Get children",
"## Get children ## for child in root: ## Check element name ##",
"named scene.\") ## Get children ## for child in root: ## Check element",
"tree = ET.parse(f) root = tree.getroot() ## Check root element (scene) ## if",
"f): ## Parse XML ## logging.info(\"Reading from scene file `%s'.\", f) tree =",
"## Check element name ## if child.tag == \"meta\": if \"key\" in child.attrib:",
"\"scene\": raise SceneFileException(\"Root tag must be named scene.\") ## Get children ## for",
"== \"meta\": if \"key\" in child.attrib: key = child.attrib[\"key\"] if key in self.metaData:",
"%s.\" % key) else: self.metaData[key] = child.text else: raise SceneFileException(\"Meta tag must have",
"tag must have start and value attributes.\") else: raise SceneFileException(\"Child tag must be",
"= 0 for l in self.commands.items(): for c in l[1]: tmp = l[0]",
"key attribute.\") elif child.tag == \"command\": if (\"start\" in child.attrib) and (\"value\" in",
"not .\" % child.tag) def getDuration(self): dur = 0 for l in self.commands.items():",
"[] self.commands[key].append(SceneCommands.Helpers.get(child.attrib[\"value\"])) else: raise SceneFileException(\"Command tag must have start and value attributes.\") else:",
"\"key\" in child.attrib: key = child.attrib[\"key\"] if key in self.metaData: raise SceneFileException(\"MetaData key",
"attributes.\") else: raise SceneFileException(\"Child tag must be named meta or command, not .\"",
"key = int(child.attrib[\"start\"]) if not key in self.commands: self.commands[key] = [] self.commands[key].append(SceneCommands.Helpers.get(child.attrib[\"value\"])) else:",
"Parse XML ## logging.info(\"Reading from scene file `%s'.\", f) tree = ET.parse(f) root",
"tree.getroot() ## Check root element (scene) ## if root.tag != \"scene\": raise SceneFileException(\"Root",
"Exceptions import SceneFileException import SceneCommands class Scene(object): metaData = {} commands = {}",
"already exists: %s.\" % key) else: self.metaData[key] = child.text else: raise SceneFileException(\"Meta tag",
"must be named scene.\") ## Get children ## for child in root: ##",
"getDuration(self): dur = 0 for l in self.commands.items(): for c in l[1]: tmp",
"child.tag) def getDuration(self): dur = 0 for l in self.commands.items(): for c in",
"raise SceneFileException(\"Child tag must be named meta or command, not .\" % child.tag)",
"% key) else: self.metaData[key] = child.text else: raise SceneFileException(\"Meta tag must have key",
"SceneFileException(\"Child tag must be named meta or command, not .\" % child.tag) def",
"raise SceneFileException(\"Command tag must have start and value attributes.\") else: raise SceneFileException(\"Child tag",
"(\"value\" in child.attrib): key = int(child.attrib[\"start\"]) if not key in self.commands: self.commands[key] =",
"c in l[1]: tmp = l[0] + c.getDuration() if tmp > dur: dur",
"must be named meta or command, not .\" % child.tag) def getDuration(self): dur",
"element (scene) ## if root.tag != \"scene\": raise SceneFileException(\"Root tag must be named",
"## for child in root: ## Check element name ## if child.tag ==",
"child in root: ## Check element name ## if child.tag == \"meta\": if",
"in child.attrib) and (\"value\" in child.attrib): key = int(child.attrib[\"start\"]) if not key in",
"import xml.etree.ElementTree as ET from Exceptions import SceneFileException import SceneCommands class Scene(object): metaData",
"else: raise SceneFileException(\"Meta tag must have key attribute.\") elif child.tag == \"command\": if",
"## if root.tag != \"scene\": raise SceneFileException(\"Root tag must be named scene.\") ##",
"tmp = l[0] + c.getDuration() if tmp > dur: dur = tmp return",
"if \"key\" in child.attrib: key = child.attrib[\"key\"] if key in self.metaData: raise SceneFileException(\"MetaData",
"== \"command\": if (\"start\" in child.attrib) and (\"value\" in child.attrib): key = int(child.attrib[\"start\"])",
"root = tree.getroot() ## Check root element (scene) ## if root.tag != \"scene\":",
"if root.tag != \"scene\": raise SceneFileException(\"Root tag must be named scene.\") ## Get",
"scene file `%s'.\", f) tree = ET.parse(f) root = tree.getroot() ## Check root",
"= child.attrib[\"key\"] if key in self.metaData: raise SceneFileException(\"MetaData key already exists: %s.\" %",
"key already exists: %s.\" % key) else: self.metaData[key] = child.text else: raise SceneFileException(\"Meta",
".\" % child.tag) def getDuration(self): dur = 0 for l in self.commands.items(): for",
"be named scene.\") ## Get children ## for child in root: ## Check",
"SceneFileException(\"Command tag must have start and value attributes.\") else: raise SceneFileException(\"Child tag must",
"file `%s'.\", f) tree = ET.parse(f) root = tree.getroot() ## Check root element",
"= int(child.attrib[\"start\"]) if not key in self.commands: self.commands[key] = [] self.commands[key].append(SceneCommands.Helpers.get(child.attrib[\"value\"])) else: raise",
"else: raise SceneFileException(\"Child tag must be named meta or command, not .\" %",
"def getDuration(self): dur = 0 for l in self.commands.items(): for c in l[1]:",
"named meta or command, not .\" % child.tag) def getDuration(self): dur = 0",
"if key in self.metaData: raise SceneFileException(\"MetaData key already exists: %s.\" % key) else:",
"and (\"value\" in child.attrib): key = int(child.attrib[\"start\"]) if not key in self.commands: self.commands[key]",
"if not key in self.commands: self.commands[key] = [] self.commands[key].append(SceneCommands.Helpers.get(child.attrib[\"value\"])) else: raise SceneFileException(\"Command tag",
"in self.commands.items(): for c in l[1]: tmp = l[0] + c.getDuration() if tmp",
"\"command\": if (\"start\" in child.attrib) and (\"value\" in child.attrib): key = int(child.attrib[\"start\"]) if",
"root: ## Check element name ## if child.tag == \"meta\": if \"key\" in",
"\"meta\": if \"key\" in child.attrib: key = child.attrib[\"key\"] if key in self.metaData: raise",
"key in self.metaData: raise SceneFileException(\"MetaData key already exists: %s.\" % key) else: self.metaData[key]",
"self.commands[key].append(SceneCommands.Helpers.get(child.attrib[\"value\"])) else: raise SceneFileException(\"Command tag must have start and value attributes.\") else: raise",
"command, not .\" % child.tag) def getDuration(self): dur = 0 for l in",
"child.tag == \"meta\": if \"key\" in child.attrib: key = child.attrib[\"key\"] if key in",
"commands = {} def fromFile(self, f): ## Parse XML ## logging.info(\"Reading from scene",
"child.attrib) and (\"value\" in child.attrib): key = int(child.attrib[\"start\"]) if not key in self.commands:",
"else: raise SceneFileException(\"Command tag must have start and value attributes.\") else: raise SceneFileException(\"Child",
"have start and value attributes.\") else: raise SceneFileException(\"Child tag must be named meta",
"xml.etree.ElementTree as ET from Exceptions import SceneFileException import SceneCommands class Scene(object): metaData =",
"be named meta or command, not .\" % child.tag) def getDuration(self): dur =",
"ET.parse(f) root = tree.getroot() ## Check root element (scene) ## if root.tag !=",
"% child.tag) def getDuration(self): dur = 0 for l in self.commands.items(): for c",
"l[1]: tmp = l[0] + c.getDuration() if tmp > dur: dur = tmp",
"fromFile(self, f): ## Parse XML ## logging.info(\"Reading from scene file `%s'.\", f) tree",
"## logging.info(\"Reading from scene file `%s'.\", f) tree = ET.parse(f) root = tree.getroot()",
"dur = 0 for l in self.commands.items(): for c in l[1]: tmp =",
"= tree.getroot() ## Check root element (scene) ## if root.tag != \"scene\": raise",
"have key attribute.\") elif child.tag == \"command\": if (\"start\" in child.attrib) and (\"value\"",
"tag must be named meta or command, not .\" % child.tag) def getDuration(self):",
"## if child.tag == \"meta\": if \"key\" in child.attrib: key = child.attrib[\"key\"] if",
"elif child.tag == \"command\": if (\"start\" in child.attrib) and (\"value\" in child.attrib): key",
"raise SceneFileException(\"Root tag must be named scene.\") ## Get children ## for child",
"not key in self.commands: self.commands[key] = [] self.commands[key].append(SceneCommands.Helpers.get(child.attrib[\"value\"])) else: raise SceneFileException(\"Command tag must",
"name ## if child.tag == \"meta\": if \"key\" in child.attrib: key = child.attrib[\"key\"]",
"attribute.\") elif child.tag == \"command\": if (\"start\" in child.attrib) and (\"value\" in child.attrib):",
"= l[0] + c.getDuration() if tmp > dur: dur = tmp return dur",
"SceneFileException(\"Meta tag must have key attribute.\") elif child.tag == \"command\": if (\"start\" in",
"value attributes.\") else: raise SceneFileException(\"Child tag must be named meta or command, not",
"class Scene(object): metaData = {} commands = {} def fromFile(self, f): ## Parse",
"## Parse XML ## logging.info(\"Reading from scene file `%s'.\", f) tree = ET.parse(f)",
"= ET.parse(f) root = tree.getroot() ## Check root element (scene) ## if root.tag",
"Check root element (scene) ## if root.tag != \"scene\": raise SceneFileException(\"Root tag must",
"Check element name ## if child.tag == \"meta\": if \"key\" in child.attrib: key",
"for c in l[1]: tmp = l[0] + c.getDuration() if tmp > dur:",
"import SceneFileException import SceneCommands class Scene(object): metaData = {} commands = {} def",
"= [] self.commands[key].append(SceneCommands.Helpers.get(child.attrib[\"value\"])) else: raise SceneFileException(\"Command tag must have start and value attributes.\")",
"in child.attrib): key = int(child.attrib[\"start\"]) if not key in self.commands: self.commands[key] = []",
"in root: ## Check element name ## if child.tag == \"meta\": if \"key\"",
"import SceneCommands class Scene(object): metaData = {} commands = {} def fromFile(self, f):",
"#!/usr/bin/python3 import logging import xml.etree.ElementTree as ET from Exceptions import SceneFileException import SceneCommands",
"metaData = {} commands = {} def fromFile(self, f): ## Parse XML ##",
"logging.info(\"Reading from scene file `%s'.\", f) tree = ET.parse(f) root = tree.getroot() ##",
"for child in root: ## Check element name ## if child.tag == \"meta\":",
"= {} commands = {} def fromFile(self, f): ## Parse XML ## logging.info(\"Reading",
"in self.metaData: raise SceneFileException(\"MetaData key already exists: %s.\" % key) else: self.metaData[key] =",
"else: self.metaData[key] = child.text else: raise SceneFileException(\"Meta tag must have key attribute.\") elif",
"self.metaData[key] = child.text else: raise SceneFileException(\"Meta tag must have key attribute.\") elif child.tag",
"raise SceneFileException(\"Meta tag must have key attribute.\") elif child.tag == \"command\": if (\"start\"",
"child.tag == \"command\": if (\"start\" in child.attrib) and (\"value\" in child.attrib): key =",
"or command, not .\" % child.tag) def getDuration(self): dur = 0 for l",
"key = child.attrib[\"key\"] if key in self.metaData: raise SceneFileException(\"MetaData key already exists: %s.\"",
"and value attributes.\") else: raise SceneFileException(\"Child tag must be named meta or command,",
"meta or command, not .\" % child.tag) def getDuration(self): dur = 0 for",
"= {} def fromFile(self, f): ## Parse XML ## logging.info(\"Reading from scene file",
"(\"start\" in child.attrib) and (\"value\" in child.attrib): key = int(child.attrib[\"start\"]) if not key",
"SceneFileException(\"MetaData key already exists: %s.\" % key) else: self.metaData[key] = child.text else: raise",
"if (\"start\" in child.attrib) and (\"value\" in child.attrib): key = int(child.attrib[\"start\"]) if not",
"self.commands: self.commands[key] = [] self.commands[key].append(SceneCommands.Helpers.get(child.attrib[\"value\"])) else: raise SceneFileException(\"Command tag must have start and",
"XML ## logging.info(\"Reading from scene file `%s'.\", f) tree = ET.parse(f) root =",
"(scene) ## if root.tag != \"scene\": raise SceneFileException(\"Root tag must be named scene.\")",
"<reponame>rookies/dmx #!/usr/bin/python3 import logging import xml.etree.ElementTree as ET from Exceptions import SceneFileException import"
] |
[
"loading caption file of output \" \"marked for report.\", e) @property def is_img(self):",
"prepare end times timeline = [{\"rule\": rec.rule, \"starttime\": datetime.datetime.fromtimestamp(rec.starttime).isoformat(), \"endtime\": datetime.datetime.fromtimestamp(rec.endtime).isoformat()} for rec",
"except KeyError as e: print(e) logger.warning(\"Metadata for file {} was created with a",
"f in job.expanded_output: meta = persistence.metadata(f) if not meta: logger.warning(\"Missing metadata for file",
"\" \"report: {}\".format(url)) def auto_report(dag, path): try: from jinja2 import Template, Environment, PackageLoader",
"+ 100 # add offset to account for labels ymax = max(y for",
"import Snakemake from snakemake import __version__ class EmbeddedMixin(object): \"\"\" Replaces the URI of",
"<NAME>\" __email__ = \"<EMAIL>\" __license__ = \"MIT\" import os import sys import mimetypes",
"in text @property def icon(self): if self.is_img: return \"image\" elif self.is_text: return \"file-text\"",
"pos.values()) def encode_node(node): x, y = pos[node] return {\"rule\": node, \"fx\": x, \"fy\":",
"register) new image:: and figure:: directives that use a base64 # data URI",
"e) g = nx.DiGraph() g.add_nodes_from(sorted(job.rule.name for job in dag.jobs)) for job in dag.jobs:",
"an HTML file.\") definitions = textwrap.dedent(\"\"\" .. role:: raw-html(raw) :format: html \"\"\") metadata",
"has to be an HTML file.\") definitions = textwrap.dedent(\"\"\" .. role:: raw-html(raw) :format:",
"Snakemake: config = dag.workflow.config text = f.read() + rst_links text = publish_parts(env.from_string(text).render( snakemake=Snakemake,",
"else \"\", date=datetime.date.today().isoformat()) text = format(textwrap.dedent(text), stepout=3) attachments = [] if files: attachments",
"meta[\"singularity_img_url\"] rec.output.append(f) except KeyError as e: print(e) logger.warning(\"Metadata for file {} was created",
"collections import namedtuple, defaultdict import requests from docutils.parsers.rst.directives.images import Image, Figure from docutils.parsers.rst",
"meta = persistence.metadata(f) if not meta: logger.warning(\"Missing metadata for file {}\".format(f)) continue try:",
"import __version__ class EmbeddedMixin(object): \"\"\" Replaces the URI of a directive with a",
"\"-density\", \"100\", self.path, \"png:-\"], stderr=sp.PIPE) uri = data_uri(png, os.path.basename(self.path) + \".png\", mime=\"image/png\") self.png_uri",
"not in rules: rules[rec.rule].append(rule) else: merged = False for other in rules[rec.rule]: if",
"\"imagemagick convert: {}\".format(e.stderr)) else: logger.warning(\"Command convert not in $PATH. Install \" \"imagemagick in",
"\"text/plain\", \"text/tab-separated-values\"} return self.mime in text @property def icon(self): if self.is_img: return \"image\"",
"must be installed to create reports.\") if not path.endswith(\".html\"): raise WorkflowError(\"Report file does",
"as e: raise WorkflowError(\"Error loading caption file of output \" \"marked for report.\",",
"in job.expanded_output: meta = persistence.metadata(f) if not meta: logger.warning(\"Missing metadata for file {}\".format(f))",
"= data_uri_from_file(path) self.id = uuid.uuid4() self.job = job self.png_uri = None if self.is_img:",
"rec.rule)] # prepare per-rule information rules = defaultdict(list) for rec in records.values(): rule",
"meta[\"starttime\"]) rec.endtime = max(rec.endtime, meta[\"endtime\"]) rec.conda_env_file = None rec.conda_env = meta[\"conda_env\"] rec.singularity_img_url =",
"\"_\") }} {% for res in catresults %} .. _{{ res.name }}: #{{",
"does \" \"not exist.\".format(f)) if os.path.isfile(f): report_obj = get_flag_value(f, \"report\") category = report_obj.category",
"data_uri(data, filename, encoding=\"utf8\", mime=\"text/plain\"): \"\"\"Craft a base64 data URI from file with proper",
"merged = False for other in rules[rec.rule]: if rule == other: other.add(rec) merged",
"[] for file in sorted(_files): data, _ = data_uri_from_file(file) links.append(':raw-html:`<a href=\"{data}\" download=\"{filename}\" draggable=\"true\">{filename}</a>`'.format(",
"base64.b64decode(job_rec.conda_env).decode() self.conda_env = yaml.load(self._conda_env_raw) self.n_jobs = 1 self.output = list(job_rec.output) self.id = uuid.uuid4()",
"EmbeddedFigure) def data_uri(data, filename, encoding=\"utf8\", mime=\"text/plain\"): \"\"\"Craft a base64 data URI from file",
"f: class Snakemake: config = dag.workflow.config text = f.read() + rst_links text =",
"xmax, ymax def get_resource_as_string(url): r = requests.get(url) if r.status_code == requests.codes.ok: return r.text",
"open(dag.workflow.report_text) as f: class Snakemake: config = dag.workflow.config text = f.read() + rst_links",
"\"MIT\" import os import sys import mimetypes import base64 import textwrap import datetime",
"too \" \"old Snakemake version.\".format(f)) for catresults in results.values(): catresults.sort(key=lambda res: res.name) #",
"and self.conda_env == other.conda_env and self.singularity_img_url == other.singularity_img_url) class JobRecord: def __init__(self): self.rule",
"\"not exist.\".format(f)) if os.path.isfile(f): report_obj = get_flag_value(f, \"report\") category = report_obj.category or \"",
"logger.info(\"Adding {}.\".format(self.name)) self.raw_caption = caption self.data_uri, self.mime = data_uri_from_file(path) self.id = uuid.uuid4() self.job",
"created with a too \" \"old Snakemake version.\".format(f)) for catresults in results.values(): catresults.sort(key=lambda",
"{% for res in catresults %} .. _{{ res.name }}: #{{ res.id }}",
"assuming \" \"text/plain.\".format(file)) if encoding is None: encoding = defaultenc with open(file, \"rb\")",
"proper encoding and mimetype.\"\"\" data = base64.b64encode(data) uri = (\"data:{mime};charset={charset};filename={filename};base64,{data}\" \"\".format(filename=filename, mime=mime, charset=encoding,",
"in $PATH. Install \" \"imagemagick in order to have embedded \" \"images and",
"report...\") persistence = dag.workflow.persistence results = defaultdict(list) records = defaultdict(JobRecord) recorded_files = set()",
"[{\"target\": idx[u], \"source\": idx[v], \"value\": 1} for u, v in g.edges] return {\"nodes\":",
"rule = meta[\"rule\"] rec = records[(job_hash, rule)] rec.rule = rule rec.starttime = min(rec.starttime,",
"dag.jobs: target = job.rule.name for dep in dag.dependencies[job]: source = dep.rule.name g.add_edge(source, target)",
"out: out.write(template.render(results=results, results_size=results_size, text=text, rulegraph_nodes=rulegraph[\"nodes\"], rulegraph_links=rulegraph[\"links\"], rulegraph_width=xmax + 20, rulegraph_height=ymax + 20, runtimes=runtimes,",
"in enumerate(g.nodes)} links = [{\"target\": idx[u], \"source\": idx[v], \"value\": 1} for u, v",
"reports.\") if not path.endswith(\".html\"): raise WorkflowError(\"Report file does not end with .html\") logger.info(\"Creating",
"self.path = path logger.info(\"Adding {}.\".format(self.name)) self.raw_caption = caption self.data_uri, self.mime = data_uri_from_file(path) self.id",
"to create reports.\") if not path.endswith(\".html\"): raise WorkflowError(\"Report file does not end with",
"uuid import json import time import shutil import subprocess as sp import itertools",
"rst_links = textwrap.dedent(\"\"\" .. _Results: #results .. _Rules: #rules .. _Statistics: #stats {%",
"import json import time import shutil import subprocess as sp import itertools from",
"dag.workflow.persistence results = defaultdict(list) records = defaultdict(JobRecord) recorded_files = set() for job in",
"catresults.sort(key=lambda res: res.name) # prepare runtimes runtimes = [{\"rule\": rec.rule, \"runtime\": rec.endtime -",
"return os.path.getsize(self.path) def rulegraph_d3_spec(dag): try: import networkx as nx from networkx.drawing.nx_agraph import graphviz_layout",
"self.conda_env_file = None self.singularity_img_url = None class FileRecord: def __init__(self, path, job, caption):",
"= False for other in rules[rec.rule]: if rule == other: other.add(rec) merged =",
"container:: :name: {name} {name}: {links} '''.format(name=name, links=links)) text = definitions + text +",
"records.values(): rule = RuleRecord(job, rec) if rec.rule not in rules: rules[rec.rule].append(rule) else: merged",
"in dag.jobs)) for job in dag.jobs: target = job.rule.name for dep in dag.dependencies[job]:",
"== other.singularity_img_url) class JobRecord: def __init__(self): self.rule = None self.starttime = sys.maxsize self.endtime",
"is not None: try: from jinja2 import Template except ImportError as e: raise",
"filename, encoding=\"utf8\", mime=\"text/plain\"): \"\"\"Craft a base64 data URI from file with proper encoding",
"be an HTML file.\") definitions = textwrap.dedent(\"\"\" .. role:: raw-html(raw) :format: html \"\"\")",
"other): return (self.name == other.name and self.conda_env == other.conda_env and self.singularity_img_url == other.singularity_img_url)",
"render HTML template = env.get_template(\"report.html\") with open(path, \"w\", encoding=\"utf-8\") as out: out.write(template.render(results=results, results_size=results_size,",
"overrides = dict() if template is not None: overrides[\"template\"] = template if stylesheet",
"job.rule.name, None) try: caption = open(self.raw_caption).read() + rst_links caption = env.from_string(caption).render(snakemake=snakemake, results=results) self.caption",
"except ImportError as e: raise WorkflowError(\"Python packages networkx and pygraphviz must be \"",
"{} was created with a too \" \"old Snakemake version.\".format(f)) for catresults in",
"run(self): \"\"\" Image.run() handles most of the \"\"\" result = Image.run(self) reference =",
"= dag.workflow.persistence results = defaultdict(list) records = defaultdict(JobRecord) recorded_files = set() for job",
"caption self.data_uri, self.mime = data_uri_from_file(path) self.id = uuid.uuid4() self.job = job self.png_uri =",
"e: raise WorkflowError(\"Error loading caption file of output \" \"marked for report.\", e)",
"self.job snakemake = Snakemake(job.input, job.output, job.params, job.wildcards, job.threads, job.resources, job.log, job.dag.workflow.config, job.rule.name, None)",
"report.\") def render(self, env, rst_links, results): if self.raw_caption is not None: try: from",
"in dag.dependencies[job]: source = dep.rule.name g.add_edge(source, target) pos = graphviz_layout(g, \"dot\", args=\"-Grankdir=BT\") xmax",
"defaultdict(list) records = defaultdict(JobRecord) recorded_files = set() for job in dag.jobs: for f",
"for x, y in pos.values()) + 100 # add offset to account for",
"\"imagemagick in order to have embedded \" \"images and pdfs in the report.\")",
"publish_parts(caption, writer_name=\"html\")[\"body\"] except Exception as e: raise WorkflowError(\"Error loading caption file of output",
"global description text = \"\" if dag.workflow.report_text: with open(dag.workflow.report_text) as f: class Snakemake:",
"= defaultenc with open(file, \"rb\") as f: return data_uri(f.read(), os.path.basename(file), encoding, mime), mime",
"(self.name == other.name and self.conda_env == other.conda_env and self.singularity_img_url == other.singularity_img_url) class JobRecord:",
"= graphviz_layout(g, \"dot\", args=\"-Grankdir=BT\") xmax = max(x for x, y in pos.values()) +",
"= rulegraph_d3_spec(dag) env = Environment(loader=PackageLoader(\"snakemake\", \"report\"), trim_blocks=True, lstrip_blocks=True) env.filters[\"get_resource_as_string\"] = get_resource_as_string rst_links =",
"WorkflowError(\"Failed to download resource needed for \" \"report: {}\".format(url)) def auto_report(dag, path): try:",
"\"\"\" Image.run() handles most of the \"\"\" result = Image.run(self) reference = directives.uri(self.arguments[0])",
"html = open(path, \"w\") publish_file(source=io.StringIO(text), destination=html, writer_name=\"html\", settings_overrides=overrides) class RuleRecord: def __init__(self, job,",
"f.exists: raise WorkflowError(\"File {} marked for report but does \" \"not exist.\".format(f)) if",
"self.conda_env = None self._conda_env_raw = None if job_rec.conda_env: self._conda_env_raw = base64.b64decode(job_rec.conda_env).decode() self.conda_env =",
"not None: try: from jinja2 import Template except ImportError as e: raise WorkflowError(\"Python",
"textwrap.dedent(\"\"\" .. _Results: #results .. _Rules: #rules .. _Statistics: #stats {% for cat,",
"uuid.uuid4() self.job = job self.png_uri = None if self.is_img: convert = shutil.which(\"convert\") if",
"rec.singularity_img_url = meta[\"singularity_img_url\"] rec.output.append(f) except KeyError as e: print(e) logger.warning(\"Metadata for file {}",
"web_safe = {\"image/gif\", \"image/jpeg\", \"image/png\", \"image/svg+xml\", \"application/pdf\"} return self.mime in web_safe @property def",
"None: encoding = defaultenc with open(file, \"rb\") as f: return data_uri(f.read(), os.path.basename(file), encoding,",
"endfor %} .. _ \"\"\") for cat, catresults in results.items(): for res in",
"\"endtime\": datetime.datetime.fromtimestamp(rec.endtime).isoformat()} for rec in sorted(records.values(), key=lambda rec: rec.rule)] # prepare per-rule information",
"f in itertools.chain(job.expanded_output, job.input): if is_flagged(f, \"report\") and f not in recorded_files: if",
"= \"\" if dag.workflow.report_text: with open(dag.workflow.report_text) as f: class Snakemake: config = dag.workflow.config",
"web_safe @property def is_text(self): text = {\"text/csv\", \"text/plain\", \"text/tab-separated-values\"} return self.mime in text",
"return {\"nodes\": nodes, \"links\": links}, xmax, ymax def get_resource_as_string(url): r = requests.get(url) if",
"dag.workflow.config text = f.read() + rst_links text = publish_parts(env.from_string(text).render( snakemake=Snakemake, results=results), writer_name=\"html\")[\"body\"] #",
"uri def data_uri_from_file(file, defaultenc=\"utf8\"): \"\"\"Craft a base64 data URI from file with proper",
"snakemake.io import is_flagged, get_flag_value from snakemake.exceptions import WorkflowError from snakemake.script import Snakemake from",
"use a base64 # data URI instead of pointing to a filename. class",
"= env.from_string(caption).render(snakemake=snakemake, results=results) self.caption = publish_parts(caption, writer_name=\"html\")[\"body\"] except Exception as e: raise WorkflowError(\"Error",
"= textwrap.dedent(\"\"\" .. _Results: #results .. _Rules: #rules .. _Statistics: #stats {% for",
"requests from docutils.parsers.rst.directives.images import Image, Figure from docutils.parsers.rst import directives from docutils.core import",
"raise ValueError(\"Path to report output has to be an HTML file.\") definitions =",
"= stylesheet html = open(path, \"w\") publish_file(source=io.StringIO(text), destination=html, writer_name=\"html\", settings_overrides=overrides) class RuleRecord: def",
"_ \"\"\") for cat, catresults in results.items(): for res in catresults: res.render(env, rst_links,",
"timeline = [{\"rule\": rec.rule, \"starttime\": datetime.datetime.fromtimestamp(rec.starttime).isoformat(), \"endtime\": datetime.datetime.fromtimestamp(rec.endtime).isoformat()} for rec in sorted(records.values(), key=lambda",
"writer_name=\"html\")[\"body\"] # record time now = \"{} {}\".format(datetime.datetime.now().ctime(), time.tzname[0]) results_size = sum(res.size for",
"name(self): return os.path.basename(self.path) @property def size(self): \"\"\"Return size in Bytes.\"\"\" return os.path.getsize(self.path) def",
"def render(self, env, rst_links, results): if self.raw_caption is not None: try: from jinja2",
"job.log, job.dag.workflow.config, job.rule.name, None) try: caption = open(self.raw_caption).read() + rst_links caption = env.from_string(caption).render(snakemake=snakemake,",
"mimetype.\"\"\" mime, encoding = mimetypes.guess_type(file) if mime is None: mime = \"text/plain\" logger.info(\"Could",
"rules: rules[rec.rule].append(rule) else: merged = False for other in rules[rec.rule]: if rule ==",
"None: try: from jinja2 import Template except ImportError as e: raise WorkflowError(\"Python package",
"in sorted(files.items()): if not isinstance(_files, list): _files = [_files] links = [] for",
"- rec.starttime} for rec in sorted(records.values(), key=lambda rec: rec.rule)] # prepare end times",
"\"report: {}\".format(url)) def auto_report(dag, path): try: from jinja2 import Template, Environment, PackageLoader except",
"= defaultdict(JobRecord) recorded_files = set() for job in dag.jobs: for f in itertools.chain(job.expanded_output,",
"\"links\": links}, xmax, ymax def get_resource_as_string(url): r = requests.get(url) if r.status_code == requests.codes.ok:",
"+ rst_links caption = env.from_string(caption).render(snakemake=snakemake, results=results) self.caption = publish_parts(caption, writer_name=\"html\")[\"body\"] except Exception as",
"# prepare end times timeline = [{\"rule\": rec.rule, \"starttime\": datetime.datetime.fromtimestamp(rec.starttime).isoformat(), \"endtime\": datetime.datetime.fromtimestamp(rec.endtime).isoformat()} for",
"images/figures in reports. \"\"\" def run(self): \"\"\" Image.run() handles most of the \"\"\"",
"end times timeline = [{\"rule\": rec.rule, \"starttime\": datetime.datetime.fromtimestamp(rec.starttime).isoformat(), \"endtime\": datetime.datetime.fromtimestamp(rec.endtime).isoformat()} for rec in",
"= meta[\"job_hash\"] rule = meta[\"rule\"] rec = records[(job_hash, rule)] rec.rule = rule rec.starttime",
"import subprocess as sp import itertools from collections import namedtuple, defaultdict import requests",
"= caption self.data_uri, self.mime = data_uri_from_file(path) self.id = uuid.uuid4() self.job = job self.png_uri",
"time now = \"{} {}\".format(datetime.datetime.now().ctime(), time.tzname[0]) results_size = sum(res.size for cat in results.values()",
"record time now = \"{} {}\".format(datetime.datetime.now().ctime(), time.tzname[0]) results_size = sum(res.size for cat in",
"png with \" \"imagemagick convert: {}\".format(e.stderr)) else: logger.warning(\"Command convert not in $PATH. Install",
".. _{{ res.name }}: #{{ res.id }} {% endfor %} {% endfor %}",
"import directives from docutils.core import publish_file, publish_parts from snakemake.utils import format from snakemake.logging",
"= data_uri(png, os.path.basename(self.path) + \".png\", mime=\"image/png\") self.png_uri = uri except sp.CalledProcessError as e:",
"= mimetypes.guess_type(file) if mime is None: mime = \"text/plain\" logger.info(\"Could not detect mimetype",
"return self.mime in web_safe @property def is_text(self): text = {\"text/csv\", \"text/plain\", \"text/tab-separated-values\"} return",
"a base64 # data URI instead of pointing to a filename. class EmbeddedImage(Image,",
"job_rec.rule self.singularity_img_url = job_rec.singularity_img_url self.conda_env = None self._conda_env_raw = None if job_rec.conda_env: self._conda_env_raw",
"pos = graphviz_layout(g, \"dot\", args=\"-Grankdir=BT\") xmax = max(x for x, y in pos.values())",
"= None if job_rec.conda_env: self._conda_env_raw = base64.b64decode(job_rec.conda_env).decode() self.conda_env = yaml.load(self._conda_env_raw) self.n_jobs = 1",
"return self.mime in text @property def icon(self): if self.is_img: return \"image\" elif self.is_text:",
"for job in dag.jobs)) for job in dag.jobs: target = job.rule.name for dep",
"file {} was created with a too \" \"old Snakemake version.\".format(f)) for catresults",
"json_graph except ImportError as e: raise WorkflowError(\"Python packages networkx and pygraphviz must be",
"information rules = defaultdict(list) for rec in records.values(): rule = RuleRecord(job, rec) if",
"from snakemake import __version__ class EmbeddedMixin(object): \"\"\" Replaces the URI of a directive",
"{links} '''.format(name=name, links=links)) text = definitions + text + \"\\n\\n\" + \"\\n\\n\".join(attachments) +",
"max(rec.endtime, meta[\"endtime\"]) rec.conda_env_file = None rec.conda_env = meta[\"conda_env\"] rec.singularity_img_url = meta[\"singularity_img_url\"] rec.output.append(f) except",
"dep in dag.dependencies[job]: source = dep.rule.name g.add_edge(source, target) pos = graphviz_layout(g, \"dot\", args=\"-Grankdir=BT\")",
"self.endtime = 0 self.output = [] self.conda_env_file = None self.singularity_img_url = None class",
"\"\"\").format(metadata=metadata + \" | \" if metadata else \"\", date=datetime.date.today().isoformat()) text = format(textwrap.dedent(text),",
"= defaultdict(list) records = defaultdict(JobRecord) recorded_files = set() for job in dag.jobs: for",
"metadata overrides = dict() if template is not None: overrides[\"template\"] = template if",
"dag.workflow.report_text: with open(dag.workflow.report_text) as f: class Snakemake: config = dag.workflow.config text = f.read()",
"itertools from collections import namedtuple, defaultdict import requests from docutils.parsers.rst.directives.images import Image, Figure",
"reference = directives.uri(self.arguments[0]) self.options['uri'] = data_uri_from_file(reference)[0] return result # Create (and register) new",
"in results.values(): catresults.sort(key=lambda res: res.name) # prepare runtimes runtimes = [{\"rule\": rec.rule, \"runtime\":",
"f not in recorded_files: if not f.exists: raise WorkflowError(\"File {} marked for report",
"os.path.isfile(f): report_obj = get_flag_value(f, \"report\") category = report_obj.category or \" \" results[category].append( FileRecord(f,",
"None if job_rec.conda_env: self._conda_env_raw = base64.b64decode(job_rec.conda_env).decode() self.conda_env = yaml.load(self._conda_env_raw) self.n_jobs = 1 self.output",
"Image.run() handles most of the \"\"\" result = Image.run(self) reference = directives.uri(self.arguments[0]) self.options['uri']",
"= \"MIT\" import os import sys import mimetypes import base64 import textwrap import",
"convert image to png with \" \"imagemagick convert: {}\".format(e.stderr)) else: logger.warning(\"Command convert not",
"import shutil import subprocess as sp import itertools from collections import namedtuple, defaultdict",
"rule == other: other.add(rec) merged = True break if not merged: rules[rec.rule].append(rule) #",
"textwrap.dedent(\"\"\" .. container:: :name: metadata {metadata}{date} \"\"\").format(metadata=metadata + \" | \" if metadata",
"sorted(records.values(), key=lambda rec: rec.rule)] # prepare end times timeline = [{\"rule\": rec.rule, \"starttime\":",
"rulegraph, xmax, ymax = rulegraph_d3_spec(dag) env = Environment(loader=PackageLoader(\"snakemake\", \"report\"), trim_blocks=True, lstrip_blocks=True) env.filters[\"get_resource_as_string\"] =",
"self.raw_caption is not None: try: from jinja2 import Template except ImportError as e:",
"res in cat) # render HTML template = env.get_template(\"report.html\") with open(path, \"w\", encoding=\"utf-8\")",
"_ = data_uri_from_file(file) links.append(':raw-html:`<a href=\"{data}\" download=\"{filename}\" draggable=\"true\">{filename}</a>`'.format( data=data, filename=os.path.basename(file))) links = \"\\n\\n \".join(links)",
"to be an HTML file.\") definitions = textwrap.dedent(\"\"\" .. role:: raw-html(raw) :format: html",
"in Bytes.\"\"\" return os.path.getsize(self.path) def rulegraph_d3_spec(dag): try: import networkx as nx from networkx.drawing.nx_agraph",
"networkx.drawing.nx_agraph import graphviz_layout from networkx.readwrite import json_graph except ImportError as e: raise WorkflowError(\"Python",
"= requests.get(url) if r.status_code == requests.codes.ok: return r.text raise WorkflowError(\"Failed to download resource",
"target) pos = graphviz_layout(g, \"dot\", args=\"-Grankdir=BT\") xmax = max(x for x, y in",
"try: caption = open(self.raw_caption).read() + rst_links caption = env.from_string(caption).render(snakemake=snakemake, results=results) self.caption = publish_parts(caption,",
"rec.starttime = min(rec.starttime, meta[\"starttime\"]) rec.endtime = max(rec.endtime, meta[\"endtime\"]) rec.conda_env_file = None rec.conda_env =",
"caption = env.from_string(caption).render(snakemake=snakemake, results=results) self.caption = publish_parts(caption, writer_name=\"html\")[\"body\"] except Exception as e: raise",
"class EmbeddedFigure(Figure, EmbeddedMixin): pass directives.register_directive('embeddedfigure', EmbeddedFigure) def data_uri(data, filename, encoding=\"utf8\", mime=\"text/plain\"): \"\"\"Craft a",
"cat, catresults in results|dictsort %} .. _{{ cat }}: #results-{{ cat|replace(\" \", \"_\")",
"in g.edges] return {\"nodes\": nodes, \"links\": links}, xmax, ymax def get_resource_as_string(url): r =",
"stylesheet is not None: overrides[\"stylesheet_path\"] = stylesheet html = open(path, \"w\") publish_file(source=io.StringIO(text), destination=html,",
"Useful for embedding images/figures in reports. \"\"\" def run(self): \"\"\" Image.run() handles most",
"trim_blocks=True, lstrip_blocks=True) env.filters[\"get_resource_as_string\"] = get_resource_as_string rst_links = textwrap.dedent(\"\"\" .. _Results: #results .. _Rules:",
"@property def is_img(self): web_safe = {\"image/gif\", \"image/jpeg\", \"image/png\", \"image/svg+xml\", \"application/pdf\"} return self.mime in",
"self.is_img: return \"image\" elif self.is_text: return \"file-text\" else: return \"file\" @property def name(self):",
"import Template except ImportError as e: raise WorkflowError(\"Python package jinja2 must be installed",
"None self.singularity_img_url = None class FileRecord: def __init__(self, path, job, caption): self.path =",
"graphviz_layout(g, \"dot\", args=\"-Grankdir=BT\") xmax = max(x for x, y in pos.values()) + 100",
"= [{\"target\": idx[u], \"source\": idx[v], \"value\": 1} for u, v in g.edges] return",
"for cat, catresults in results.items(): for res in catresults: res.render(env, rst_links, results) #",
"__author__ = \"<NAME>\" __copyright__ = \"Copyright 2015, <NAME>\" __email__ = \"<EMAIL>\" __license__ =",
"def __eq__(self, other): return (self.name == other.name and self.conda_env == other.conda_env and self.singularity_img_url",
"{\"text/csv\", \"text/plain\", \"text/tab-separated-values\"} return self.mime in text @property def icon(self): if self.is_img: return",
"publish_parts(env.from_string(text).render( snakemake=Snakemake, results=results), writer_name=\"html\")[\"body\"] # record time now = \"{} {}\".format(datetime.datetime.now().ctime(), time.tzname[0]) results_size",
"for file {} was created with a too \" \"old Snakemake version.\".format(f)) for",
"as e: logger.warning(\"Failed to convert image to png with \" \"imagemagick convert: {}\".format(e.stderr))",
".. _Rules: #rules .. _Statistics: #stats {% for cat, catresults in results|dictsort %}",
"\" | \" if metadata else \"\", date=datetime.date.today().isoformat()) text = format(textwrap.dedent(text), stepout=3) attachments",
"return data_uri(f.read(), os.path.basename(file), encoding, mime), mime def report(text, path, stylesheet=os.path.join(os.path.dirname(__file__), \"report.css\"), defaultenc=\"utf8\", template=None,",
"if files: attachments = [textwrap.dedent(\"\"\" .. container:: :name: attachments \"\"\")] for name, _files",
"JobRecord: def __init__(self): self.rule = None self.starttime = sys.maxsize self.endtime = 0 self.output",
"rec) if rec.rule not in rules: rules[rec.rule].append(rule) else: merged = False for other",
"textwrap.dedent(\"\"\" .. role:: raw-html(raw) :format: html \"\"\") metadata = textwrap.dedent(\"\"\" .. container:: :name:",
"json import time import shutil import subprocess as sp import itertools from collections",
"links = [] for file in sorted(_files): data, _ = data_uri_from_file(file) links.append(':raw-html:`<a href=\"{data}\"",
"= self.job snakemake = Snakemake(job.input, job.output, job.params, job.wildcards, job.threads, job.resources, job.log, job.dag.workflow.config, job.rule.name,",
".. _{{ cat }}: #results-{{ cat|replace(\" \", \"_\") }} {% for res in",
"None class FileRecord: def __init__(self, path, job, caption): self.path = path logger.info(\"Adding {}.\".format(self.name))",
"def report(text, path, stylesheet=os.path.join(os.path.dirname(__file__), \"report.css\"), defaultenc=\"utf8\", template=None, metadata=None, **files): outmime, _ = mimetypes.guess_type(path)",
"import networkx as nx from networkx.drawing.nx_agraph import graphviz_layout from networkx.readwrite import json_graph except",
"format from snakemake.logging import logger from snakemake.io import is_flagged, get_flag_value from snakemake.exceptions import",
"directives.register_directive('embeddedfigure', EmbeddedFigure) def data_uri(data, filename, encoding=\"utf8\", mime=\"text/plain\"): \"\"\"Craft a base64 data URI from",
"\"\"\") for cat, catresults in results.items(): for res in catresults: res.render(env, rst_links, results)",
"WorkflowError(\"Python package jinja2 must be installed to create reports.\") if not path.endswith(\".html\"): raise",
"cat, catresults in results.items(): for res in catresults: res.render(env, rst_links, results) # global",
"path, job, caption): self.path = path logger.info(\"Adding {}.\".format(self.name)) self.raw_caption = caption self.data_uri, self.mime",
"idx[u], \"source\": idx[v], \"value\": 1} for u, v in g.edges] return {\"nodes\": nodes,",
"f.read() + rst_links text = publish_parts(env.from_string(text).render( snakemake=Snakemake, results=results), writer_name=\"html\")[\"body\"] # record time now",
"\"\"\"Craft a base64 data URI from file with proper encoding and mimetype.\"\"\" data",
"job.dag.workflow.config, job.rule.name, None) try: caption = open(self.raw_caption).read() + rst_links caption = env.from_string(caption).render(snakemake=snakemake, results=results)",
"%} {% endfor %} .. _ \"\"\") for cat, catresults in results.items(): for",
"= [] if files: attachments = [textwrap.dedent(\"\"\" .. container:: :name: attachments \"\"\")] for",
"isinstance(_files, list): _files = [_files] links = [] for file in sorted(_files): data,",
"from networkx.drawing.nx_agraph import graphviz_layout from networkx.readwrite import json_graph except ImportError as e: raise",
"rule = RuleRecord(job, rec) if rec.rule not in rules: rules[rec.rule].append(rule) else: merged =",
"from file with proper encoding and mimetype.\"\"\" data = base64.b64encode(data) uri = (\"data:{mime};charset={charset};filename={filename};base64,{data}\"",
"job.output, job.params, job.wildcards, job.threads, job.resources, job.log, job.dag.workflow.config, job.rule.name, None) try: caption = open(self.raw_caption).read()",
"logger.warning(\"Missing metadata for file {}\".format(f)) continue try: job_hash = meta[\"job_hash\"] rule = meta[\"rule\"]",
"_files = [_files] links = [] for file in sorted(_files): data, _ =",
"from file with proper encoding and mimetype.\"\"\" mime, encoding = mimetypes.guess_type(file) if mime",
"+ metadata overrides = dict() if template is not None: overrides[\"template\"] = template",
"continue try: job_hash = meta[\"job_hash\"] rule = meta[\"rule\"] rec = records[(job_hash, rule)] rec.rule",
"\" results[category].append( FileRecord(f, job, report_obj.caption)) recorded_files.add(f) for f in job.expanded_output: meta = persistence.metadata(f)",
"}}: #{{ res.id }} {% endfor %} {% endfor %} .. _ \"\"\")",
":format: html \"\"\") metadata = textwrap.dedent(\"\"\" .. container:: :name: metadata {metadata}{date} \"\"\").format(metadata=metadata +",
"\".join(links) attachments.append(''' .. container:: :name: {name} {name}: {links} '''.format(name=name, links=links)) text = definitions",
"mime=mime, charset=encoding, data=data.decode(\"utf-8\"))) return uri def data_uri_from_file(file, defaultenc=\"utf8\"): \"\"\"Craft a base64 data URI",
"other.name and self.conda_env == other.conda_env and self.singularity_img_url == other.singularity_img_url) class JobRecord: def __init__(self):",
"rec.rule = rule rec.starttime = min(rec.starttime, meta[\"starttime\"]) rec.endtime = max(rec.endtime, meta[\"endtime\"]) rec.conda_env_file =",
"\"Copyright 2015, <NAME>\" __email__ = \"<EMAIL>\" __license__ = \"MIT\" import os import sys",
"a directive with a base64-encoded version. Useful for embedding images/figures in reports. \"\"\"",
"{}.\".format(self.name)) self.raw_caption = caption self.data_uri, self.mime = data_uri_from_file(path) self.id = uuid.uuid4() self.job =",
"rulegraph_width=xmax + 20, rulegraph_height=ymax + 20, runtimes=runtimes, timeline=timeline, rules=[rec for recs in rules.values()",
"Environment(loader=PackageLoader(\"snakemake\", \"report\"), trim_blocks=True, lstrip_blocks=True) env.filters[\"get_resource_as_string\"] = get_resource_as_string rst_links = textwrap.dedent(\"\"\" .. _Results: #results",
"%} .. _ \"\"\") for cat, catresults in results.items(): for res in catresults:",
"import logger from snakemake.io import is_flagged, get_flag_value from snakemake.exceptions import WorkflowError from snakemake.script",
"= None rec.conda_env = meta[\"conda_env\"] rec.singularity_img_url = meta[\"singularity_img_url\"] rec.output.append(f) except KeyError as e:",
"if job_rec.conda_env: self._conda_env_raw = base64.b64decode(job_rec.conda_env).decode() self.conda_env = yaml.load(self._conda_env_raw) self.n_jobs = 1 self.output =",
"\"marked for report.\", e) @property def is_img(self): web_safe = {\"image/gif\", \"image/jpeg\", \"image/png\", \"image/svg+xml\",",
"links = \"\\n\\n \".join(links) attachments.append(''' .. container:: :name: {name} {name}: {links} '''.format(name=name, links=links))",
"os.path.getsize(self.path) def rulegraph_d3_spec(dag): try: import networkx as nx from networkx.drawing.nx_agraph import graphviz_layout from",
"convert not in $PATH. Install \" \"imagemagick in order to have embedded \"",
"file {}\".format(f)) continue try: job_hash = meta[\"job_hash\"] rule = meta[\"rule\"] rec = records[(job_hash,",
"in pos.values()) def encode_node(node): x, y = pos[node] return {\"rule\": node, \"fx\": x,",
"\"report\") category = report_obj.category or \" \" results[category].append( FileRecord(f, job, report_obj.caption)) recorded_files.add(f) for",
"base64.b64encode(data) uri = (\"data:{mime};charset={charset};filename={filename};base64,{data}\" \"\".format(filename=filename, mime=mime, charset=encoding, data=data.decode(\"utf-8\"))) return uri def data_uri_from_file(file, defaultenc=\"utf8\"):",
"key=lambda rec: rec.rule)] # prepare per-rule information rules = defaultdict(list) for rec in",
"jinja2 import Template except ImportError as e: raise WorkflowError(\"Python package jinja2 must be",
"ImportError as e: raise WorkflowError(\"Python packages networkx and pygraphviz must be \" \"installed",
"catresults %} .. _{{ res.name }}: #{{ res.id }} {% endfor %} {%",
"prepare per-rule information rules = defaultdict(list) for rec in records.values(): rule = RuleRecord(job,",
"\" \"marked for report.\", e) @property def is_img(self): web_safe = {\"image/gif\", \"image/jpeg\", \"image/png\",",
"= path logger.info(\"Adding {}.\".format(self.name)) self.raw_caption = caption self.data_uri, self.mime = data_uri_from_file(path) self.id =",
"{}\".format(e.stderr)) else: logger.warning(\"Command convert not in $PATH. Install \" \"imagemagick in order to",
"data_uri(png, os.path.basename(self.path) + \".png\", mime=\"image/png\") self.png_uri = uri except sp.CalledProcessError as e: logger.warning(\"Failed",
"attachments = [] if files: attachments = [textwrap.dedent(\"\"\" .. container:: :name: attachments \"\"\")]",
"is not None: try: png = sp.check_output([\"convert\", \"-density\", \"100\", self.path, \"png:-\"], stderr=sp.PIPE) uri",
"mime = \"text/plain\" logger.info(\"Could not detect mimetype for {}, assuming \" \"text/plain.\".format(file)) if",
"catresults in results.values(): catresults.sort(key=lambda res: res.name) # prepare runtimes runtimes = [{\"rule\": rec.rule,",
"import json_graph except ImportError as e: raise WorkflowError(\"Python packages networkx and pygraphviz must",
"from collections import namedtuple, defaultdict import requests from docutils.parsers.rst.directives.images import Image, Figure from",
"= job.rule.name for dep in dag.dependencies[job]: source = dep.rule.name g.add_edge(source, target) pos =",
"is_flagged, get_flag_value from snakemake.exceptions import WorkflowError from snakemake.script import Snakemake from snakemake import",
"most of the \"\"\" result = Image.run(self) reference = directives.uri(self.arguments[0]) self.options['uri'] = data_uri_from_file(reference)[0]",
"res.id }} {% endfor %} {% endfor %} .. _ \"\"\") for cat,",
"stderr=sp.PIPE) uri = data_uri(png, os.path.basename(self.path) + \".png\", mime=\"image/png\") self.png_uri = uri except sp.CalledProcessError",
"and mimetype.\"\"\" data = base64.b64encode(data) uri = (\"data:{mime};charset={charset};filename={filename};base64,{data}\" \"\".format(filename=filename, mime=mime, charset=encoding, data=data.decode(\"utf-8\"))) return",
"for dep in dag.dependencies[job]: source = dep.rule.name g.add_edge(source, target) pos = graphviz_layout(g, \"dot\",",
"return \"file-text\" else: return \"file\" @property def name(self): return os.path.basename(self.path) @property def size(self):",
"size in Bytes.\"\"\" return os.path.getsize(self.path) def rulegraph_d3_spec(dag): try: import networkx as nx from",
"the \"\"\" result = Image.run(self) reference = directives.uri(self.arguments[0]) self.options['uri'] = data_uri_from_file(reference)[0] return result",
"# Create (and register) new image:: and figure:: directives that use a base64",
"import namedtuple, defaultdict import requests from docutils.parsers.rst.directives.images import Image, Figure from docutils.parsers.rst import",
"installed to create reports.\") job = self.job snakemake = Snakemake(job.input, job.output, job.params, job.wildcards,",
"job in dag.jobs)) for job in dag.jobs: target = job.rule.name for dep in",
"to create reports.\", e) g = nx.DiGraph() g.add_nodes_from(sorted(job.rule.name for job in dag.jobs)) for",
"dep.rule.name g.add_edge(source, target) pos = graphviz_layout(g, \"dot\", args=\"-Grankdir=BT\") xmax = max(x for x,",
"rules[rec.rule]: if rule == other: other.add(rec) merged = True break if not merged:",
"res.render(env, rst_links, results) # global description text = \"\" if dag.workflow.report_text: with open(dag.workflow.report_text)",
"results.values() for res in cat) # render HTML template = env.get_template(\"report.html\") with open(path,",
"not meta: logger.warning(\"Missing metadata for file {}\".format(f)) continue try: job_hash = meta[\"job_hash\"] rule",
"\"\\n\\n \".join(links) attachments.append(''' .. container:: :name: {name} {name}: {links} '''.format(name=name, links=links)) text =",
"for x, y in pos.values()) def encode_node(node): x, y = pos[node] return {\"rule\":",
"self.is_text: return \"file-text\" else: return \"file\" @property def name(self): return os.path.basename(self.path) @property def",
"if not path.endswith(\".html\"): raise WorkflowError(\"Report file does not end with .html\") logger.info(\"Creating report...\")",
"#{{ res.id }} {% endfor %} {% endfor %} .. _ \"\"\") for",
"sum(res.size for cat in results.values() for res in cat) # render HTML template",
"import time import shutil import subprocess as sp import itertools from collections import",
"{}\".format(datetime.datetime.now().ctime(), time.tzname[0]) results_size = sum(res.size for cat in results.values() for res in cat)",
"name, _files in sorted(files.items()): if not isinstance(_files, list): _files = [_files] links =",
"not None: overrides[\"template\"] = template if stylesheet is not None: overrides[\"stylesheet_path\"] = stylesheet",
"HTML template = env.get_template(\"report.html\") with open(path, \"w\", encoding=\"utf-8\") as out: out.write(template.render(results=results, results_size=results_size, text=text,",
"max(y for x, y in pos.values()) def encode_node(node): x, y = pos[node] return",
"job, report_obj.caption)) recorded_files.add(f) for f in job.expanded_output: meta = persistence.metadata(f) if not meta:",
"\"\"\" Replaces the URI of a directive with a base64-encoded version. Useful for",
"g.nodes)) idx = {node: i for i, node in enumerate(g.nodes)} links = [{\"target\":",
"min(rec.starttime, meta[\"starttime\"]) rec.endtime = max(rec.endtime, meta[\"endtime\"]) rec.conda_env_file = None rec.conda_env = meta[\"conda_env\"] rec.singularity_img_url",
"convert: {}\".format(e.stderr)) else: logger.warning(\"Command convert not in $PATH. Install \" \"imagemagick in order",
"other: other.add(rec) merged = True break if not merged: rules[rec.rule].append(rule) # rulegraph rulegraph,",
"enumerate(g.nodes)} links = [{\"target\": idx[u], \"source\": idx[v], \"value\": 1} for u, v in",
"job self.png_uri = None if self.is_img: convert = shutil.which(\"convert\") if convert is not",
"\"installed to create reports.\", e) g = nx.DiGraph() g.add_nodes_from(sorted(job.rule.name for job in dag.jobs))",
"account for labels ymax = max(y for x, y in pos.values()) def encode_node(node):",
"for res in catresults %} .. _{{ res.name }}: #{{ res.id }} {%",
"caption file of output \" \"marked for report.\", e) @property def is_img(self): web_safe",
"[] if files: attachments = [textwrap.dedent(\"\"\" .. container:: :name: attachments \"\"\")] for name,",
"+ \".png\", mime=\"image/png\") self.png_uri = uri except sp.CalledProcessError as e: logger.warning(\"Failed to convert",
"= textwrap.dedent(\"\"\" .. role:: raw-html(raw) :format: html \"\"\") metadata = textwrap.dedent(\"\"\" .. container::",
"print(e) logger.warning(\"Metadata for file {} was created with a too \" \"old Snakemake",
"in itertools.chain(job.expanded_output, job.input): if is_flagged(f, \"report\") and f not in recorded_files: if not",
"env = Environment(loader=PackageLoader(\"snakemake\", \"report\"), trim_blocks=True, lstrip_blocks=True) env.filters[\"get_resource_as_string\"] = get_resource_as_string rst_links = textwrap.dedent(\"\"\" ..",
"yaml self.name = job_rec.rule self.singularity_img_url = job_rec.singularity_img_url self.conda_env = None self._conda_env_raw = None",
"file with proper encoding and mimetype.\"\"\" mime, encoding = mimetypes.guess_type(file) if mime is",
"= sp.check_output([\"convert\", \"-density\", \"100\", self.path, \"png:-\"], stderr=sp.PIPE) uri = data_uri(png, os.path.basename(self.path) + \".png\",",
"or \" \" results[category].append( FileRecord(f, job, report_obj.caption)) recorded_files.add(f) for f in job.expanded_output: meta",
"u, v in g.edges] return {\"nodes\": nodes, \"links\": links}, xmax, ymax def get_resource_as_string(url):",
"= {\"text/csv\", \"text/plain\", \"text/tab-separated-values\"} return self.mime in text @property def icon(self): if self.is_img:",
"in dag.jobs: for f in itertools.chain(job.expanded_output, job.input): if is_flagged(f, \"report\") and f not",
"Template except ImportError as e: raise WorkflowError(\"Python package jinja2 must be installed to",
"metadata=None, **files): outmime, _ = mimetypes.guess_type(path) if outmime != \"text/html\": raise ValueError(\"Path to",
"{node: i for i, node in enumerate(g.nodes)} links = [{\"target\": idx[u], \"source\": idx[v],",
"[] self.conda_env_file = None self.singularity_img_url = None class FileRecord: def __init__(self, path, job,",
"logger.warning(\"Failed to convert image to png with \" \"imagemagick convert: {}\".format(e.stderr)) else: logger.warning(\"Command",
"data, _ = data_uri_from_file(file) links.append(':raw-html:`<a href=\"{data}\" download=\"{filename}\" draggable=\"true\">{filename}</a>`'.format( data=data, filename=os.path.basename(file))) links = \"\\n\\n",
"try: job_hash = meta[\"job_hash\"] rule = meta[\"rule\"] rec = records[(job_hash, rule)] rec.rule =",
"env.from_string(caption).render(snakemake=snakemake, results=results) self.caption = publish_parts(caption, writer_name=\"html\")[\"body\"] except Exception as e: raise WorkflowError(\"Error loading",
"import textwrap import datetime import io import uuid import json import time import",
"_{{ cat }}: #results-{{ cat|replace(\" \", \"_\") }} {% for res in catresults",
"else: merged = False for other in rules[rec.rule]: if rule == other: other.add(rec)",
"# add offset to account for labels ymax = max(y for x, y",
"y in pos.values()) + 100 # add offset to account for labels ymax",
"embedded \" \"images and pdfs in the report.\") def render(self, env, rst_links, results):",
".. container:: :name: metadata {metadata}{date} \"\"\").format(metadata=metadata + \" | \" if metadata else",
"report_obj.caption)) recorded_files.add(f) for f in job.expanded_output: meta = persistence.metadata(f) if not meta: logger.warning(\"Missing",
"overrides[\"stylesheet_path\"] = stylesheet html = open(path, \"w\") publish_file(source=io.StringIO(text), destination=html, writer_name=\"html\", settings_overrides=overrides) class RuleRecord:",
"results_size = sum(res.size for cat in results.values() for res in cat) # render",
"self.png_uri = uri except sp.CalledProcessError as e: logger.warning(\"Failed to convert image to png",
"offset to account for labels ymax = max(y for x, y in pos.values())",
"results = defaultdict(list) records = defaultdict(JobRecord) recorded_files = set() for job in dag.jobs:",
"for embedding images/figures in reports. \"\"\" def run(self): \"\"\" Image.run() handles most of",
"rule)] rec.rule = rule rec.starttime = min(rec.starttime, meta[\"starttime\"]) rec.endtime = max(rec.endtime, meta[\"endtime\"]) rec.conda_env_file",
"directive with a base64-encoded version. Useful for embedding images/figures in reports. \"\"\" def",
"with open(file, \"rb\") as f: return data_uri(f.read(), os.path.basename(file), encoding, mime), mime def report(text,",
"get_resource_as_string(url): r = requests.get(url) if r.status_code == requests.codes.ok: return r.text raise WorkflowError(\"Failed to",
"with proper encoding and mimetype.\"\"\" data = base64.b64encode(data) uri = (\"data:{mime};charset={charset};filename={filename};base64,{data}\" \"\".format(filename=filename, mime=mime,",
"self.output = list(job_rec.output) self.id = uuid.uuid4() def add(self, job_rec): self.n_jobs += 1 self.output.extend(job_rec.output)",
"not None: try: png = sp.check_output([\"convert\", \"-density\", \"100\", self.path, \"png:-\"], stderr=sp.PIPE) uri =",
"mime=\"text/plain\"): \"\"\"Craft a base64 data URI from file with proper encoding and mimetype.\"\"\"",
"from docutils.parsers.rst.directives.images import Image, Figure from docutils.parsers.rst import directives from docutils.core import publish_file,",
"role:: raw-html(raw) :format: html \"\"\") metadata = textwrap.dedent(\"\"\" .. container:: :name: metadata {metadata}{date}",
"import graphviz_layout from networkx.readwrite import json_graph except ImportError as e: raise WorkflowError(\"Python packages",
"def rulegraph_d3_spec(dag): try: import networkx as nx from networkx.drawing.nx_agraph import graphviz_layout from networkx.readwrite",
"HTML file.\") definitions = textwrap.dedent(\"\"\" .. role:: raw-html(raw) :format: html \"\"\") metadata =",
"time import shutil import subprocess as sp import itertools from collections import namedtuple,",
"data_uri(f.read(), os.path.basename(file), encoding, mime), mime def report(text, path, stylesheet=os.path.join(os.path.dirname(__file__), \"report.css\"), defaultenc=\"utf8\", template=None, metadata=None,",
"job.expanded_output: meta = persistence.metadata(f) if not meta: logger.warning(\"Missing metadata for file {}\".format(f)) continue",
"Environment, PackageLoader except ImportError as e: raise WorkflowError(\"Python package jinja2 must be installed",
"\"image\" elif self.is_text: return \"file-text\" else: return \"file\" @property def name(self): return os.path.basename(self.path)",
"try: png = sp.check_output([\"convert\", \"-density\", \"100\", self.path, \"png:-\"], stderr=sp.PIPE) uri = data_uri(png, os.path.basename(self.path)",
"return \"image\" elif self.is_text: return \"file-text\" else: return \"file\" @property def name(self): return",
"def add(self, job_rec): self.n_jobs += 1 self.output.extend(job_rec.output) def __eq__(self, other): return (self.name ==",
"pos[node] return {\"rule\": node, \"fx\": x, \"fy\": y} nodes = list(map(encode_node, g.nodes)) idx",
"for report.\", e) @property def is_img(self): web_safe = {\"image/gif\", \"image/jpeg\", \"image/png\", \"image/svg+xml\", \"application/pdf\"}",
"not None: overrides[\"stylesheet_path\"] = stylesheet html = open(path, \"w\") publish_file(source=io.StringIO(text), destination=html, writer_name=\"html\", settings_overrides=overrides)",
"base64 # data URI instead of pointing to a filename. class EmbeddedImage(Image, EmbeddedMixin):",
"logger.warning(\"Command convert not in $PATH. Install \" \"imagemagick in order to have embedded",
"= template if stylesheet is not None: overrides[\"stylesheet_path\"] = stylesheet html = open(path,",
"class Snakemake: config = dag.workflow.config text = f.read() + rst_links text = publish_parts(env.from_string(text).render(",
"data_uri_from_file(file) links.append(':raw-html:`<a href=\"{data}\" download=\"{filename}\" draggable=\"true\">{filename}</a>`'.format( data=data, filename=os.path.basename(file))) links = \"\\n\\n \".join(links) attachments.append(''' ..",
"to report output has to be an HTML file.\") definitions = textwrap.dedent(\"\"\" ..",
"data=data, filename=os.path.basename(file))) links = \"\\n\\n \".join(links) attachments.append(''' .. container:: :name: {name} {name}: {links}",
"import itertools from collections import namedtuple, defaultdict import requests from docutils.parsers.rst.directives.images import Image,",
"job.params, job.wildcards, job.threads, job.resources, job.log, job.dag.workflow.config, job.rule.name, None) try: caption = open(self.raw_caption).read() +",
"catresults in results|dictsort %} .. _{{ cat }}: #results-{{ cat|replace(\" \", \"_\") }}",
"config = dag.workflow.config text = f.read() + rst_links text = publish_parts(env.from_string(text).render( snakemake=Snakemake, results=results),",
"i, node in enumerate(g.nodes)} links = [{\"target\": idx[u], \"source\": idx[v], \"value\": 1} for",
":name: metadata {metadata}{date} \"\"\").format(metadata=metadata + \" | \" if metadata else \"\", date=datetime.date.today().isoformat())",
"pass directives.register_directive('embeddedimage', EmbeddedImage) class EmbeddedFigure(Figure, EmbeddedMixin): pass directives.register_directive('embeddedfigure', EmbeddedFigure) def data_uri(data, filename, encoding=\"utf8\",",
"in order to have embedded \" \"images and pdfs in the report.\") def",
"\".png\", mime=\"image/png\") self.png_uri = uri except sp.CalledProcessError as e: logger.warning(\"Failed to convert image",
"as out: out.write(template.render(results=results, results_size=results_size, text=text, rulegraph_nodes=rulegraph[\"nodes\"], rulegraph_links=rulegraph[\"links\"], rulegraph_width=xmax + 20, rulegraph_height=ymax + 20,",
"with .html\") logger.info(\"Creating report...\") persistence = dag.workflow.persistence results = defaultdict(list) records = defaultdict(JobRecord)",
"job in dag.jobs: target = job.rule.name for dep in dag.dependencies[job]: source = dep.rule.name",
"stylesheet=os.path.join(os.path.dirname(__file__), \"report.css\"), defaultenc=\"utf8\", template=None, metadata=None, **files): outmime, _ = mimetypes.guess_type(path) if outmime !=",
"order to have embedded \" \"images and pdfs in the report.\") def render(self,",
"import WorkflowError from snakemake.script import Snakemake from snakemake import __version__ class EmbeddedMixin(object): \"\"\"",
"text = publish_parts(env.from_string(text).render( snakemake=Snakemake, results=results), writer_name=\"html\")[\"body\"] # record time now = \"{} {}\".format(datetime.datetime.now().ctime(),",
"\"starttime\": datetime.datetime.fromtimestamp(rec.starttime).isoformat(), \"endtime\": datetime.datetime.fromtimestamp(rec.endtime).isoformat()} for rec in sorted(records.values(), key=lambda rec: rec.rule)] # prepare",
"2015, <NAME>\" __email__ = \"<EMAIL>\" __license__ = \"MIT\" import os import sys import",
"self.starttime = sys.maxsize self.endtime = 0 self.output = [] self.conda_env_file = None self.singularity_img_url",
"try: from jinja2 import Template, Environment, PackageLoader except ImportError as e: raise WorkflowError(\"Python",
"node, \"fx\": x, \"fy\": y} nodes = list(map(encode_node, g.nodes)) idx = {node: i",
"for job in dag.jobs: for f in itertools.chain(job.expanded_output, job.input): if is_flagged(f, \"report\") and",
"a base64 data URI from file with proper encoding and mimetype.\"\"\" data =",
"= base64.b64decode(job_rec.conda_env).decode() self.conda_env = yaml.load(self._conda_env_raw) self.n_jobs = 1 self.output = list(job_rec.output) self.id =",
"job, caption): self.path = path logger.info(\"Adding {}.\".format(self.name)) self.raw_caption = caption self.data_uri, self.mime =",
"requests.codes.ok: return r.text raise WorkflowError(\"Failed to download resource needed for \" \"report: {}\".format(url))",
"have embedded \" \"images and pdfs in the report.\") def render(self, env, rst_links,",
"{% for cat, catresults in results|dictsort %} .. _{{ cat }}: #results-{{ cat|replace(\"",
"key=lambda rec: rec.rule)] # prepare end times timeline = [{\"rule\": rec.rule, \"starttime\": datetime.datetime.fromtimestamp(rec.starttime).isoformat(),",
"results.items(): for res in catresults: res.render(env, rst_links, results) # global description text =",
"for cat, catresults in results|dictsort %} .. _{{ cat }}: #results-{{ cat|replace(\" \",",
"and pygraphviz must be \" \"installed to create reports.\", e) g = nx.DiGraph()",
"URI instead of pointing to a filename. class EmbeddedImage(Image, EmbeddedMixin): pass directives.register_directive('embeddedimage', EmbeddedImage)",
"= None self.starttime = sys.maxsize self.endtime = 0 self.output = [] self.conda_env_file =",
"FileRecord: def __init__(self, path, job, caption): self.path = path logger.info(\"Adding {}.\".format(self.name)) self.raw_caption =",
"a base64-encoded version. Useful for embedding images/figures in reports. \"\"\" def run(self): \"\"\"",
"class RuleRecord: def __init__(self, job, job_rec): import yaml self.name = job_rec.rule self.singularity_img_url =",
"return {\"rule\": node, \"fx\": x, \"fy\": y} nodes = list(map(encode_node, g.nodes)) idx =",
"as f: class Snakemake: config = dag.workflow.config text = f.read() + rst_links text",
"embedding images/figures in reports. \"\"\" def run(self): \"\"\" Image.run() handles most of the",
"a filename. class EmbeddedImage(Image, EmbeddedMixin): pass directives.register_directive('embeddedimage', EmbeddedImage) class EmbeddedFigure(Figure, EmbeddedMixin): pass directives.register_directive('embeddedfigure',",
"namedtuple, defaultdict import requests from docutils.parsers.rst.directives.images import Image, Figure from docutils.parsers.rst import directives",
"import yaml self.name = job_rec.rule self.singularity_img_url = job_rec.singularity_img_url self.conda_env = None self._conda_env_raw =",
"self.png_uri = None if self.is_img: convert = shutil.which(\"convert\") if convert is not None:",
"\"images and pdfs in the report.\") def render(self, env, rst_links, results): if self.raw_caption",
"def is_text(self): text = {\"text/csv\", \"text/plain\", \"text/tab-separated-values\"} return self.mime in text @property def",
"Snakemake version.\".format(f)) for catresults in results.values(): catresults.sort(key=lambda res: res.name) # prepare runtimes runtimes",
"{\"rule\": node, \"fx\": x, \"fy\": y} nodes = list(map(encode_node, g.nodes)) idx = {node:",
"report_obj = get_flag_value(f, \"report\") category = report_obj.category or \" \" results[category].append( FileRecord(f, job,",
"from snakemake.script import Snakemake from snakemake import __version__ class EmbeddedMixin(object): \"\"\" Replaces the",
"= None self._conda_env_raw = None if job_rec.conda_env: self._conda_env_raw = base64.b64decode(job_rec.conda_env).decode() self.conda_env = yaml.load(self._conda_env_raw)",
"results[category].append( FileRecord(f, job, report_obj.caption)) recorded_files.add(f) for f in job.expanded_output: meta = persistence.metadata(f) if",
"logger.info(\"Could not detect mimetype for {}, assuming \" \"text/plain.\".format(file)) if encoding is None:",
"add(self, job_rec): self.n_jobs += 1 self.output.extend(job_rec.output) def __eq__(self, other): return (self.name == other.name",
"pass directives.register_directive('embeddedfigure', EmbeddedFigure) def data_uri(data, filename, encoding=\"utf8\", mime=\"text/plain\"): \"\"\"Craft a base64 data URI",
"class JobRecord: def __init__(self): self.rule = None self.starttime = sys.maxsize self.endtime = 0",
"self.singularity_img_url = None class FileRecord: def __init__(self, path, job, caption): self.path = path",
"file of output \" \"marked for report.\", e) @property def is_img(self): web_safe =",
"r.status_code == requests.codes.ok: return r.text raise WorkflowError(\"Failed to download resource needed for \"",
"target = job.rule.name for dep in dag.dependencies[job]: source = dep.rule.name g.add_edge(source, target) pos",
"rec.rule, \"starttime\": datetime.datetime.fromtimestamp(rec.starttime).isoformat(), \"endtime\": datetime.datetime.fromtimestamp(rec.endtime).isoformat()} for rec in sorted(records.values(), key=lambda rec: rec.rule)] #",
"x, y in pos.values()) + 100 # add offset to account for labels",
"[{\"rule\": rec.rule, \"starttime\": datetime.datetime.fromtimestamp(rec.starttime).isoformat(), \"endtime\": datetime.datetime.fromtimestamp(rec.endtime).isoformat()} for rec in sorted(records.values(), key=lambda rec: rec.rule)]",
"Snakemake(job.input, job.output, job.params, job.wildcards, job.threads, job.resources, job.log, job.dag.workflow.config, job.rule.name, None) try: caption =",
"rec.starttime} for rec in sorted(records.values(), key=lambda rec: rec.rule)] # prepare end times timeline",
"raise WorkflowError(\"Python package jinja2 must be installed to create reports.\") job = self.job",
"import datetime import io import uuid import json import time import shutil import",
"= textwrap.dedent(\"\"\" .. container:: :name: metadata {metadata}{date} \"\"\").format(metadata=metadata + \" | \" if",
"__version__ class EmbeddedMixin(object): \"\"\" Replaces the URI of a directive with a base64-encoded",
"snakemake import __version__ class EmbeddedMixin(object): \"\"\" Replaces the URI of a directive with",
"io import uuid import json import time import shutil import subprocess as sp",
"= \"<EMAIL>\" __license__ = \"MIT\" import os import sys import mimetypes import base64",
"{% endfor %} {% endfor %} .. _ \"\"\") for cat, catresults in",
"g.add_nodes_from(sorted(job.rule.name for job in dag.jobs)) for job in dag.jobs: target = job.rule.name for",
"convert is not None: try: png = sp.check_output([\"convert\", \"-density\", \"100\", self.path, \"png:-\"], stderr=sp.PIPE)",
"networkx.readwrite import json_graph except ImportError as e: raise WorkflowError(\"Python packages networkx and pygraphviz",
"with a base64-encoded version. Useful for embedding images/figures in reports. \"\"\" def run(self):",
"%} .. _{{ res.name }}: #{{ res.id }} {% endfor %} {% endfor",
"shutil.which(\"convert\") if convert is not None: try: png = sp.check_output([\"convert\", \"-density\", \"100\", self.path,",
"text=text, rulegraph_nodes=rulegraph[\"nodes\"], rulegraph_links=rulegraph[\"links\"], rulegraph_width=xmax + 20, rulegraph_height=ymax + 20, runtimes=runtimes, timeline=timeline, rules=[rec for",
"$PATH. Install \" \"imagemagick in order to have embedded \" \"images and pdfs",
"rec.output.append(f) except KeyError as e: print(e) logger.warning(\"Metadata for file {} was created with",
"{\"image/gif\", \"image/jpeg\", \"image/png\", \"image/svg+xml\", \"application/pdf\"} return self.mime in web_safe @property def is_text(self): text",
"return r.text raise WorkflowError(\"Failed to download resource needed for \" \"report: {}\".format(url)) def",
"\"\".format(filename=filename, mime=mime, charset=encoding, data=data.decode(\"utf-8\"))) return uri def data_uri_from_file(file, defaultenc=\"utf8\"): \"\"\"Craft a base64 data",
"\" \"imagemagick convert: {}\".format(e.stderr)) else: logger.warning(\"Command convert not in $PATH. Install \" \"imagemagick",
"= meta[\"rule\"] rec = records[(job_hash, rule)] rec.rule = rule rec.starttime = min(rec.starttime, meta[\"starttime\"])",
"report_obj.category or \" \" results[category].append( FileRecord(f, job, report_obj.caption)) recorded_files.add(f) for f in job.expanded_output:",
"= nx.DiGraph() g.add_nodes_from(sorted(job.rule.name for job in dag.jobs)) for job in dag.jobs: target =",
"= Snakemake(job.input, job.output, job.params, job.wildcards, job.threads, job.resources, job.log, job.dag.workflow.config, job.rule.name, None) try: caption",
"e: raise WorkflowError(\"Python package jinja2 must be installed to create reports.\") if not",
"self.rule = None self.starttime = sys.maxsize self.endtime = 0 self.output = [] self.conda_env_file",
"Figure from docutils.parsers.rst import directives from docutils.core import publish_file, publish_parts from snakemake.utils import",
"path logger.info(\"Adding {}.\".format(self.name)) self.raw_caption = caption self.data_uri, self.mime = data_uri_from_file(path) self.id = uuid.uuid4()",
"be \" \"installed to create reports.\", e) g = nx.DiGraph() g.add_nodes_from(sorted(job.rule.name for job",
"caption = open(self.raw_caption).read() + rst_links caption = env.from_string(caption).render(snakemake=snakemake, results=results) self.caption = publish_parts(caption, writer_name=\"html\")[\"body\"]",
"itertools.chain(job.expanded_output, job.input): if is_flagged(f, \"report\") and f not in recorded_files: if not f.exists:",
"mime=\"image/png\") self.png_uri = uri except sp.CalledProcessError as e: logger.warning(\"Failed to convert image to",
"= \"<NAME>\" __copyright__ = \"Copyright 2015, <NAME>\" __email__ = \"<EMAIL>\" __license__ = \"MIT\"",
"= True break if not merged: rules[rec.rule].append(rule) # rulegraph rulegraph, xmax, ymax =",
"metadata = textwrap.dedent(\"\"\" .. container:: :name: metadata {metadata}{date} \"\"\").format(metadata=metadata + \" | \"",
"as e: print(e) logger.warning(\"Metadata for file {} was created with a too \"",
"text @property def icon(self): if self.is_img: return \"image\" elif self.is_text: return \"file-text\" else:",
"\"\"\") metadata = textwrap.dedent(\"\"\" .. container:: :name: metadata {metadata}{date} \"\"\").format(metadata=metadata + \" |",
"+ \"\\n\\n\".join(attachments) + metadata overrides = dict() if template is not None: overrides[\"template\"]",
"dict() if template is not None: overrides[\"template\"] = template if stylesheet is not",
"+ rst_links text = publish_parts(env.from_string(text).render( snakemake=Snakemake, results=results), writer_name=\"html\")[\"body\"] # record time now =",
"\"text/plain\" logger.info(\"Could not detect mimetype for {}, assuming \" \"text/plain.\".format(file)) if encoding is",
"with a too \" \"old Snakemake version.\".format(f)) for catresults in results.values(): catresults.sort(key=lambda res:",
"\"\", date=datetime.date.today().isoformat()) text = format(textwrap.dedent(text), stepout=3) attachments = [] if files: attachments =",
"for rec in records.values(): rule = RuleRecord(job, rec) if rec.rule not in rules:",
"data URI from file with proper encoding and mimetype.\"\"\" mime, encoding = mimetypes.guess_type(file)",
"job_rec.singularity_img_url self.conda_env = None self._conda_env_raw = None if job_rec.conda_env: self._conda_env_raw = base64.b64decode(job_rec.conda_env).decode() self.conda_env",
"Snakemake from snakemake import __version__ class EmbeddedMixin(object): \"\"\" Replaces the URI of a",
"does not end with .html\") logger.info(\"Creating report...\") persistence = dag.workflow.persistence results = defaultdict(list)",
"date=datetime.date.today().isoformat()) text = format(textwrap.dedent(text), stepout=3) attachments = [] if files: attachments = [textwrap.dedent(\"\"\"",
"defaultenc with open(file, \"rb\") as f: return data_uri(f.read(), os.path.basename(file), encoding, mime), mime def",
"encoding and mimetype.\"\"\" data = base64.b64encode(data) uri = (\"data:{mime};charset={charset};filename={filename};base64,{data}\" \"\".format(filename=filename, mime=mime, charset=encoding, data=data.decode(\"utf-8\")))",
"if encoding is None: encoding = defaultenc with open(file, \"rb\") as f: return",
"self.is_img: convert = shutil.which(\"convert\") if convert is not None: try: png = sp.check_output([\"convert\",",
"ImportError as e: raise WorkflowError(\"Python package jinja2 must be installed to create reports.\")",
"rules[rec.rule].append(rule) # rulegraph rulegraph, xmax, ymax = rulegraph_d3_spec(dag) env = Environment(loader=PackageLoader(\"snakemake\", \"report\"), trim_blocks=True,",
"raise WorkflowError(\"Report file does not end with .html\") logger.info(\"Creating report...\") persistence = dag.workflow.persistence",
"and mimetype.\"\"\" mime, encoding = mimetypes.guess_type(file) if mime is None: mime = \"text/plain\"",
"self.options['uri'] = data_uri_from_file(reference)[0] return result # Create (and register) new image:: and figure::",
"EmbeddedMixin(object): \"\"\" Replaces the URI of a directive with a base64-encoded version. Useful",
"WorkflowError(\"Error loading caption file of output \" \"marked for report.\", e) @property def",
"list(map(encode_node, g.nodes)) idx = {node: i for i, node in enumerate(g.nodes)} links =",
"rec.rule)] # prepare end times timeline = [{\"rule\": rec.rule, \"starttime\": datetime.datetime.fromtimestamp(rec.starttime).isoformat(), \"endtime\": datetime.datetime.fromtimestamp(rec.endtime).isoformat()}",
"category = report_obj.category or \" \" results[category].append( FileRecord(f, job, report_obj.caption)) recorded_files.add(f) for f",
"\"application/pdf\"} return self.mime in web_safe @property def is_text(self): text = {\"text/csv\", \"text/plain\", \"text/tab-separated-values\"}",
"not end with .html\") logger.info(\"Creating report...\") persistence = dag.workflow.persistence results = defaultdict(list) records",
"data URI from file with proper encoding and mimetype.\"\"\" data = base64.b64encode(data) uri",
"for report but does \" \"not exist.\".format(f)) if os.path.isfile(f): report_obj = get_flag_value(f, \"report\")",
"env.get_template(\"report.html\") with open(path, \"w\", encoding=\"utf-8\") as out: out.write(template.render(results=results, results_size=results_size, text=text, rulegraph_nodes=rulegraph[\"nodes\"], rulegraph_links=rulegraph[\"links\"], rulegraph_width=xmax",
"def size(self): \"\"\"Return size in Bytes.\"\"\" return os.path.getsize(self.path) def rulegraph_d3_spec(dag): try: import networkx",
"download resource needed for \" \"report: {}\".format(url)) def auto_report(dag, path): try: from jinja2",
"overrides[\"template\"] = template if stylesheet is not None: overrides[\"stylesheet_path\"] = stylesheet html =",
"not merged: rules[rec.rule].append(rule) # rulegraph rulegraph, xmax, ymax = rulegraph_d3_spec(dag) env = Environment(loader=PackageLoader(\"snakemake\",",
"{} marked for report but does \" \"not exist.\".format(f)) if os.path.isfile(f): report_obj =",
"snakemake.utils import format from snakemake.logging import logger from snakemake.io import is_flagged, get_flag_value from",
"report(text, path, stylesheet=os.path.join(os.path.dirname(__file__), \"report.css\"), defaultenc=\"utf8\", template=None, metadata=None, **files): outmime, _ = mimetypes.guess_type(path) if",
"0 self.output = [] self.conda_env_file = None self.singularity_img_url = None class FileRecord: def",
"for rec in sorted(records.values(), key=lambda rec: rec.rule)] # prepare end times timeline =",
"= set() for job in dag.jobs: for f in itertools.chain(job.expanded_output, job.input): if is_flagged(f,",
"logger from snakemake.io import is_flagged, get_flag_value from snakemake.exceptions import WorkflowError from snakemake.script import",
"outmime != \"text/html\": raise ValueError(\"Path to report output has to be an HTML",
"uri = (\"data:{mime};charset={charset};filename={filename};base64,{data}\" \"\".format(filename=filename, mime=mime, charset=encoding, data=data.decode(\"utf-8\"))) return uri def data_uri_from_file(file, defaultenc=\"utf8\"): \"\"\"Craft",
"output has to be an HTML file.\") definitions = textwrap.dedent(\"\"\" .. role:: raw-html(raw)",
"encoding = mimetypes.guess_type(file) if mime is None: mime = \"text/plain\" logger.info(\"Could not detect",
"rulegraph_d3_spec(dag): try: import networkx as nx from networkx.drawing.nx_agraph import graphviz_layout from networkx.readwrite import",
"except sp.CalledProcessError as e: logger.warning(\"Failed to convert image to png with \" \"imagemagick",
"@property def name(self): return os.path.basename(self.path) @property def size(self): \"\"\"Return size in Bytes.\"\"\" return",
"add offset to account for labels ymax = max(y for x, y in",
"raw-html(raw) :format: html \"\"\") metadata = textwrap.dedent(\"\"\" .. container:: :name: metadata {metadata}{date} \"\"\").format(metadata=metadata",
"mimetype for {}, assuming \" \"text/plain.\".format(file)) if encoding is None: encoding = defaultenc",
"rec: rec.rule)] # prepare per-rule information rules = defaultdict(list) for rec in records.values():",
"\"report\"), trim_blocks=True, lstrip_blocks=True) env.filters[\"get_resource_as_string\"] = get_resource_as_string rst_links = textwrap.dedent(\"\"\" .. _Results: #results ..",
"render(self, env, rst_links, results): if self.raw_caption is not None: try: from jinja2 import",
"if not f.exists: raise WorkflowError(\"File {} marked for report but does \" \"not",
"mime, encoding = mimetypes.guess_type(file) if mime is None: mime = \"text/plain\" logger.info(\"Could not",
"sp.check_output([\"convert\", \"-density\", \"100\", self.path, \"png:-\"], stderr=sp.PIPE) uri = data_uri(png, os.path.basename(self.path) + \".png\", mime=\"image/png\")",
"\"report.css\"), defaultenc=\"utf8\", template=None, metadata=None, **files): outmime, _ = mimetypes.guess_type(path) if outmime != \"text/html\":",
"records[(job_hash, rule)] rec.rule = rule rec.starttime = min(rec.starttime, meta[\"starttime\"]) rec.endtime = max(rec.endtime, meta[\"endtime\"])",
"Image, Figure from docutils.parsers.rst import directives from docutils.core import publish_file, publish_parts from snakemake.utils",
"is None: mime = \"text/plain\" logger.info(\"Could not detect mimetype for {}, assuming \"",
"== other.name and self.conda_env == other.conda_env and self.singularity_img_url == other.singularity_img_url) class JobRecord: def",
"from snakemake.io import is_flagged, get_flag_value from snakemake.exceptions import WorkflowError from snakemake.script import Snakemake",
"_ = mimetypes.guess_type(path) if outmime != \"text/html\": raise ValueError(\"Path to report output has",
"reports.\", e) g = nx.DiGraph() g.add_nodes_from(sorted(job.rule.name for job in dag.jobs)) for job in",
"if r.status_code == requests.codes.ok: return r.text raise WorkflowError(\"Failed to download resource needed for",
"from jinja2 import Template, Environment, PackageLoader except ImportError as e: raise WorkflowError(\"Python package",
"None self.starttime = sys.maxsize self.endtime = 0 self.output = [] self.conda_env_file = None",
"of a directive with a base64-encoded version. Useful for embedding images/figures in reports.",
"data URI instead of pointing to a filename. class EmbeddedImage(Image, EmbeddedMixin): pass directives.register_directive('embeddedimage',",
"except Exception as e: raise WorkflowError(\"Error loading caption file of output \" \"marked",
"metadata {metadata}{date} \"\"\").format(metadata=metadata + \" | \" if metadata else \"\", date=datetime.date.today().isoformat()) text",
"in records.values(): rule = RuleRecord(job, rec) if rec.rule not in rules: rules[rec.rule].append(rule) else:",
"def run(self): \"\"\" Image.run() handles most of the \"\"\" result = Image.run(self) reference",
"env.filters[\"get_resource_as_string\"] = get_resource_as_string rst_links = textwrap.dedent(\"\"\" .. _Results: #results .. _Rules: #rules ..",
"WorkflowError(\"Report file does not end with .html\") logger.info(\"Creating report...\") persistence = dag.workflow.persistence results",
"\" \"old Snakemake version.\".format(f)) for catresults in results.values(): catresults.sort(key=lambda res: res.name) # prepare",
"convert = shutil.which(\"convert\") if convert is not None: try: png = sp.check_output([\"convert\", \"-density\",",
"from snakemake.logging import logger from snakemake.io import is_flagged, get_flag_value from snakemake.exceptions import WorkflowError",
"with open(path, \"w\", encoding=\"utf-8\") as out: out.write(template.render(results=results, results_size=results_size, text=text, rulegraph_nodes=rulegraph[\"nodes\"], rulegraph_links=rulegraph[\"links\"], rulegraph_width=xmax +",
"\" \"images and pdfs in the report.\") def render(self, env, rst_links, results): if",
"= \"\\n\\n \".join(links) attachments.append(''' .. container:: :name: {name} {name}: {links} '''.format(name=name, links=links)) text",
"time.tzname[0]) results_size = sum(res.size for cat in results.values() for res in cat) #",
"text = {\"text/csv\", \"text/plain\", \"text/tab-separated-values\"} return self.mime in text @property def icon(self): if",
"text = f.read() + rst_links text = publish_parts(env.from_string(text).render( snakemake=Snakemake, results=results), writer_name=\"html\")[\"body\"] # record",
"marked for report but does \" \"not exist.\".format(f)) if os.path.isfile(f): report_obj = get_flag_value(f,",
"import requests from docutils.parsers.rst.directives.images import Image, Figure from docutils.parsers.rst import directives from docutils.core",
"rec: rec.rule)] # prepare end times timeline = [{\"rule\": rec.rule, \"starttime\": datetime.datetime.fromtimestamp(rec.starttime).isoformat(), \"endtime\":",
"\"\"\")] for name, _files in sorted(files.items()): if not isinstance(_files, list): _files = [_files]",
"size(self): \"\"\"Return size in Bytes.\"\"\" return os.path.getsize(self.path) def rulegraph_d3_spec(dag): try: import networkx as",
"be installed to create reports.\") job = self.job snakemake = Snakemake(job.input, job.output, job.params,",
"encode_node(node): x, y = pos[node] return {\"rule\": node, \"fx\": x, \"fy\": y} nodes",
"self.path, \"png:-\"], stderr=sp.PIPE) uri = data_uri(png, os.path.basename(self.path) + \".png\", mime=\"image/png\") self.png_uri = uri",
"if dag.workflow.report_text: with open(dag.workflow.report_text) as f: class Snakemake: config = dag.workflow.config text =",
"logger.warning(\"Metadata for file {} was created with a too \" \"old Snakemake version.\".format(f))",
"None self._conda_env_raw = None if job_rec.conda_env: self._conda_env_raw = base64.b64decode(job_rec.conda_env).decode() self.conda_env = yaml.load(self._conda_env_raw) self.n_jobs",
"y in pos.values()) def encode_node(node): x, y = pos[node] return {\"rule\": node, \"fx\":",
"= (\"data:{mime};charset={charset};filename={filename};base64,{data}\" \"\".format(filename=filename, mime=mime, charset=encoding, data=data.decode(\"utf-8\"))) return uri def data_uri_from_file(file, defaultenc=\"utf8\"): \"\"\"Craft a",
"format(textwrap.dedent(text), stepout=3) attachments = [] if files: attachments = [textwrap.dedent(\"\"\" .. container:: :name:",
"if stylesheet is not None: overrides[\"stylesheet_path\"] = stylesheet html = open(path, \"w\") publish_file(source=io.StringIO(text),",
"= max(x for x, y in pos.values()) + 100 # add offset to",
"1 self.output.extend(job_rec.output) def __eq__(self, other): return (self.name == other.name and self.conda_env == other.conda_env",
"datetime import io import uuid import json import time import shutil import subprocess",
"in catresults: res.render(env, rst_links, results) # global description text = \"\" if dag.workflow.report_text:",
"else: return \"file\" @property def name(self): return os.path.basename(self.path) @property def size(self): \"\"\"Return size",
"stepout=3) attachments = [] if files: attachments = [textwrap.dedent(\"\"\" .. container:: :name: attachments",
"networkx as nx from networkx.drawing.nx_agraph import graphviz_layout from networkx.readwrite import json_graph except ImportError",
"= {\"image/gif\", \"image/jpeg\", \"image/png\", \"image/svg+xml\", \"application/pdf\"} return self.mime in web_safe @property def is_text(self):",
"from jinja2 import Template except ImportError as e: raise WorkflowError(\"Python package jinja2 must",
"logger.info(\"Creating report...\") persistence = dag.workflow.persistence results = defaultdict(list) records = defaultdict(JobRecord) recorded_files =",
"class EmbeddedMixin(object): \"\"\" Replaces the URI of a directive with a base64-encoded version.",
"uri except sp.CalledProcessError as e: logger.warning(\"Failed to convert image to png with \"",
"if mime is None: mime = \"text/plain\" logger.info(\"Could not detect mimetype for {},",
"rulegraph rulegraph, xmax, ymax = rulegraph_d3_spec(dag) env = Environment(loader=PackageLoader(\"snakemake\", \"report\"), trim_blocks=True, lstrip_blocks=True) env.filters[\"get_resource_as_string\"]",
"# data URI instead of pointing to a filename. class EmbeddedImage(Image, EmbeddedMixin): pass",
"= base64.b64encode(data) uri = (\"data:{mime};charset={charset};filename={filename};base64,{data}\" \"\".format(filename=filename, mime=mime, charset=encoding, data=data.decode(\"utf-8\"))) return uri def data_uri_from_file(file,",
"EmbeddedImage(Image, EmbeddedMixin): pass directives.register_directive('embeddedimage', EmbeddedImage) class EmbeddedFigure(Figure, EmbeddedMixin): pass directives.register_directive('embeddedfigure', EmbeddedFigure) def data_uri(data,",
"def __init__(self, job, job_rec): import yaml self.name = job_rec.rule self.singularity_img_url = job_rec.singularity_img_url self.conda_env",
"rulegraph_height=ymax + 20, runtimes=runtimes, timeline=timeline, rules=[rec for recs in rules.values() for rec in",
"meta[\"job_hash\"] rule = meta[\"rule\"] rec = records[(job_hash, rule)] rec.rule = rule rec.starttime =",
"PackageLoader except ImportError as e: raise WorkflowError(\"Python package jinja2 must be installed to",
"timeline=timeline, rules=[rec for recs in rules.values() for rec in recs], version=__version__, now=now)) logger.info(\"Report",
"Replaces the URI of a directive with a base64-encoded version. Useful for embedding",
"return result # Create (and register) new image:: and figure:: directives that use",
"try: import networkx as nx from networkx.drawing.nx_agraph import graphviz_layout from networkx.readwrite import json_graph",
"for i, node in enumerate(g.nodes)} links = [{\"target\": idx[u], \"source\": idx[v], \"value\": 1}",
"data=data.decode(\"utf-8\"))) return uri def data_uri_from_file(file, defaultenc=\"utf8\"): \"\"\"Craft a base64 data URI from file",
"job.input): if is_flagged(f, \"report\") and f not in recorded_files: if not f.exists: raise",
"data_uri_from_file(file, defaultenc=\"utf8\"): \"\"\"Craft a base64 data URI from file with proper encoding and",
"def __init__(self, path, job, caption): self.path = path logger.info(\"Adding {}.\".format(self.name)) self.raw_caption = caption",
"{name}: {links} '''.format(name=name, links=links)) text = definitions + text + \"\\n\\n\" + \"\\n\\n\".join(attachments)",
"container:: :name: attachments \"\"\")] for name, _files in sorted(files.items()): if not isinstance(_files, list):",
"result = Image.run(self) reference = directives.uri(self.arguments[0]) self.options['uri'] = data_uri_from_file(reference)[0] return result # Create",
"attachments \"\"\")] for name, _files in sorted(files.items()): if not isinstance(_files, list): _files =",
"\"png:-\"], stderr=sp.PIPE) uri = data_uri(png, os.path.basename(self.path) + \".png\", mime=\"image/png\") self.png_uri = uri except",
"= job self.png_uri = None if self.is_img: convert = shutil.which(\"convert\") if convert is",
"Install \" \"imagemagick in order to have embedded \" \"images and pdfs in",
"self.data_uri, self.mime = data_uri_from_file(path) self.id = uuid.uuid4() self.job = job self.png_uri = None",
"proper encoding and mimetype.\"\"\" mime, encoding = mimetypes.guess_type(file) if mime is None: mime",
"\"\"\"Craft a base64 data URI from file with proper encoding and mimetype.\"\"\" mime,",
"= Image.run(self) reference = directives.uri(self.arguments[0]) self.options['uri'] = data_uri_from_file(reference)[0] return result # Create (and",
"be installed to create reports.\") if not path.endswith(\".html\"): raise WorkflowError(\"Report file does not",
"in rules: rules[rec.rule].append(rule) else: merged = False for other in rules[rec.rule]: if rule",
"meta[\"rule\"] rec = records[(job_hash, rule)] rec.rule = rule rec.starttime = min(rec.starttime, meta[\"starttime\"]) rec.endtime",
"= get_flag_value(f, \"report\") category = report_obj.category or \" \" results[category].append( FileRecord(f, job, report_obj.caption))",
"data = base64.b64encode(data) uri = (\"data:{mime};charset={charset};filename={filename};base64,{data}\" \"\".format(filename=filename, mime=mime, charset=encoding, data=data.decode(\"utf-8\"))) return uri def",
"\"source\": idx[v], \"value\": 1} for u, v in g.edges] return {\"nodes\": nodes, \"links\":",
"try: from jinja2 import Template except ImportError as e: raise WorkflowError(\"Python package jinja2",
"snakemake = Snakemake(job.input, job.output, job.params, job.wildcards, job.threads, job.resources, job.log, job.dag.workflow.config, job.rule.name, None) try:",
"pdfs in the report.\") def render(self, env, rst_links, results): if self.raw_caption is not",
"100 # add offset to account for labels ymax = max(y for x,",
"= [] for file in sorted(_files): data, _ = data_uri_from_file(file) links.append(':raw-html:`<a href=\"{data}\" download=\"{filename}\"",
"publish_parts from snakemake.utils import format from snakemake.logging import logger from snakemake.io import is_flagged,",
"\"\"\" result = Image.run(self) reference = directives.uri(self.arguments[0]) self.options['uri'] = data_uri_from_file(reference)[0] return result #",
"= job_rec.singularity_img_url self.conda_env = None self._conda_env_raw = None if job_rec.conda_env: self._conda_env_raw = base64.b64decode(job_rec.conda_env).decode()",
"in sorted(records.values(), key=lambda rec: rec.rule)] # prepare per-rule information rules = defaultdict(list) for",
"\"file\" @property def name(self): return os.path.basename(self.path) @property def size(self): \"\"\"Return size in Bytes.\"\"\"",
"if self.is_img: return \"image\" elif self.is_text: return \"file-text\" else: return \"file\" @property def",
"for cat in results.values() for res in cat) # render HTML template =",
"1} for u, v in g.edges] return {\"nodes\": nodes, \"links\": links}, xmax, ymax",
"self._conda_env_raw = None if job_rec.conda_env: self._conda_env_raw = base64.b64decode(job_rec.conda_env).decode() self.conda_env = yaml.load(self._conda_env_raw) self.n_jobs =",
"exist.\".format(f)) if os.path.isfile(f): report_obj = get_flag_value(f, \"report\") category = report_obj.category or \" \"",
"directives from docutils.core import publish_file, publish_parts from snakemake.utils import format from snakemake.logging import",
"g.edges] return {\"nodes\": nodes, \"links\": links}, xmax, ymax def get_resource_as_string(url): r = requests.get(url)",
"= RuleRecord(job, rec) if rec.rule not in rules: rules[rec.rule].append(rule) else: merged = False",
"html \"\"\") metadata = textwrap.dedent(\"\"\" .. container:: :name: metadata {metadata}{date} \"\"\").format(metadata=metadata + \"",
"job_hash = meta[\"job_hash\"] rule = meta[\"rule\"] rec = records[(job_hash, rule)] rec.rule = rule",
"# rulegraph rulegraph, xmax, ymax = rulegraph_d3_spec(dag) env = Environment(loader=PackageLoader(\"snakemake\", \"report\"), trim_blocks=True, lstrip_blocks=True)",
"\"text/plain.\".format(file)) if encoding is None: encoding = defaultenc with open(file, \"rb\") as f:",
"= shutil.which(\"convert\") if convert is not None: try: png = sp.check_output([\"convert\", \"-density\", \"100\",",
"rec.endtime = max(rec.endtime, meta[\"endtime\"]) rec.conda_env_file = None rec.conda_env = meta[\"conda_env\"] rec.singularity_img_url = meta[\"singularity_img_url\"]",
"package jinja2 must be installed to create reports.\") job = self.job snakemake =",
"records = defaultdict(JobRecord) recorded_files = set() for job in dag.jobs: for f in",
"open(path, \"w\", encoding=\"utf-8\") as out: out.write(template.render(results=results, results_size=results_size, text=text, rulegraph_nodes=rulegraph[\"nodes\"], rulegraph_links=rulegraph[\"links\"], rulegraph_width=xmax + 20,",
"def get_resource_as_string(url): r = requests.get(url) if r.status_code == requests.codes.ok: return r.text raise WorkflowError(\"Failed",
"@property def size(self): \"\"\"Return size in Bytes.\"\"\" return os.path.getsize(self.path) def rulegraph_d3_spec(dag): try: import",
"if template is not None: overrides[\"template\"] = template if stylesheet is not None:",
"ValueError(\"Path to report output has to be an HTML file.\") definitions = textwrap.dedent(\"\"\"",
"class FileRecord: def __init__(self, path, job, caption): self.path = path logger.info(\"Adding {}.\".format(self.name)) self.raw_caption",
"to convert image to png with \" \"imagemagick convert: {}\".format(e.stderr)) else: logger.warning(\"Command convert",
"Exception as e: raise WorkflowError(\"Error loading caption file of output \" \"marked for",
"Bytes.\"\"\" return os.path.getsize(self.path) def rulegraph_d3_spec(dag): try: import networkx as nx from networkx.drawing.nx_agraph import",
"in pos.values()) + 100 # add offset to account for labels ymax =",
"__eq__(self, other): return (self.name == other.name and self.conda_env == other.conda_env and self.singularity_img_url ==",
"text = \"\" if dag.workflow.report_text: with open(dag.workflow.report_text) as f: class Snakemake: config =",
"self.name = job_rec.rule self.singularity_img_url = job_rec.singularity_img_url self.conda_env = None self._conda_env_raw = None if",
"but does \" \"not exist.\".format(f)) if os.path.isfile(f): report_obj = get_flag_value(f, \"report\") category =",
"datetime.datetime.fromtimestamp(rec.endtime).isoformat()} for rec in sorted(records.values(), key=lambda rec: rec.rule)] # prepare per-rule information rules",
"!= \"text/html\": raise ValueError(\"Path to report output has to be an HTML file.\")",
"Template, Environment, PackageLoader except ImportError as e: raise WorkflowError(\"Python package jinja2 must be",
"None: try: png = sp.check_output([\"convert\", \"-density\", \"100\", self.path, \"png:-\"], stderr=sp.PIPE) uri = data_uri(png,",
"raise WorkflowError(\"Failed to download resource needed for \" \"report: {}\".format(url)) def auto_report(dag, path):",
"outmime, _ = mimetypes.guess_type(path) if outmime != \"text/html\": raise ValueError(\"Path to report output",
"e) @property def is_img(self): web_safe = {\"image/gif\", \"image/jpeg\", \"image/png\", \"image/svg+xml\", \"application/pdf\"} return self.mime",
"links = [{\"target\": idx[u], \"source\": idx[v], \"value\": 1} for u, v in g.edges]",
"None) try: caption = open(self.raw_caption).read() + rst_links caption = env.from_string(caption).render(snakemake=snakemake, results=results) self.caption =",
"= [{\"rule\": rec.rule, \"starttime\": datetime.datetime.fromtimestamp(rec.starttime).isoformat(), \"endtime\": datetime.datetime.fromtimestamp(rec.endtime).isoformat()} for rec in sorted(records.values(), key=lambda rec:",
"\"{} {}\".format(datetime.datetime.now().ctime(), time.tzname[0]) results_size = sum(res.size for cat in results.values() for res in",
"caption): self.path = path logger.info(\"Adding {}.\".format(self.name)) self.raw_caption = caption self.data_uri, self.mime = data_uri_from_file(path)",
"endfor %} {% endfor %} .. _ \"\"\") for cat, catresults in results.items():",
"ymax = max(y for x, y in pos.values()) def encode_node(node): x, y =",
"filename=os.path.basename(file))) links = \"\\n\\n \".join(links) attachments.append(''' .. container:: :name: {name} {name}: {links} '''.format(name=name,",
"defaultdict import requests from docutils.parsers.rst.directives.images import Image, Figure from docutils.parsers.rst import directives from",
"__init__(self, path, job, caption): self.path = path logger.info(\"Adding {}.\".format(self.name)) self.raw_caption = caption self.data_uri,",
"return os.path.basename(self.path) @property def size(self): \"\"\"Return size in Bytes.\"\"\" return os.path.getsize(self.path) def rulegraph_d3_spec(dag):",
"results=results) self.caption = publish_parts(caption, writer_name=\"html\")[\"body\"] except Exception as e: raise WorkflowError(\"Error loading caption",
".. container:: :name: attachments \"\"\")] for name, _files in sorted(files.items()): if not isinstance(_files,",
"@property def icon(self): if self.is_img: return \"image\" elif self.is_text: return \"file-text\" else: return",
"+ 20, rulegraph_height=ymax + 20, runtimes=runtimes, timeline=timeline, rules=[rec for recs in rules.values() for",
"#results .. _Rules: #rules .. _Statistics: #stats {% for cat, catresults in results|dictsort",
"raise WorkflowError(\"File {} marked for report but does \" \"not exist.\".format(f)) if os.path.isfile(f):",
"files: attachments = [textwrap.dedent(\"\"\" .. container:: :name: attachments \"\"\")] for name, _files in",
"dag.dependencies[job]: source = dep.rule.name g.add_edge(source, target) pos = graphviz_layout(g, \"dot\", args=\"-Grankdir=BT\") xmax =",
"URI from file with proper encoding and mimetype.\"\"\" data = base64.b64encode(data) uri =",
"sorted(files.items()): if not isinstance(_files, list): _files = [_files] links = [] for file",
"\"rb\") as f: return data_uri(f.read(), os.path.basename(file), encoding, mime), mime def report(text, path, stylesheet=os.path.join(os.path.dirname(__file__),",
"in catresults %} .. _{{ res.name }}: #{{ res.id }} {% endfor %}",
"# render HTML template = env.get_template(\"report.html\") with open(path, \"w\", encoding=\"utf-8\") as out: out.write(template.render(results=results,",
"results.values(): catresults.sort(key=lambda res: res.name) # prepare runtimes runtimes = [{\"rule\": rec.rule, \"runtime\": rec.endtime",
"except ImportError as e: raise WorkflowError(\"Python package jinja2 must be installed to create",
"res in catresults: res.render(env, rst_links, results) # global description text = \"\" if",
"URI of a directive with a base64-encoded version. Useful for embedding images/figures in",
"WorkflowError from snakemake.script import Snakemake from snakemake import __version__ class EmbeddedMixin(object): \"\"\" Replaces",
"[textwrap.dedent(\"\"\" .. container:: :name: attachments \"\"\")] for name, _files in sorted(files.items()): if not",
"= publish_parts(caption, writer_name=\"html\")[\"body\"] except Exception as e: raise WorkflowError(\"Error loading caption file of",
"= data_uri_from_file(reference)[0] return result # Create (and register) new image:: and figure:: directives",
"g.add_edge(source, target) pos = graphviz_layout(g, \"dot\", args=\"-Grankdir=BT\") xmax = max(x for x, y",
"docutils.parsers.rst.directives.images import Image, Figure from docutils.parsers.rst import directives from docutils.core import publish_file, publish_parts",
"defaultenc=\"utf8\"): \"\"\"Craft a base64 data URI from file with proper encoding and mimetype.\"\"\"",
"cat|replace(\" \", \"_\") }} {% for res in catresults %} .. _{{ res.name",
"docutils.core import publish_file, publish_parts from snakemake.utils import format from snakemake.logging import logger from",
"download=\"{filename}\" draggable=\"true\">{filename}</a>`'.format( data=data, filename=os.path.basename(file))) links = \"\\n\\n \".join(links) attachments.append(''' .. container:: :name: {name}",
"draggable=\"true\">{filename}</a>`'.format( data=data, filename=os.path.basename(file))) links = \"\\n\\n \".join(links) attachments.append(''' .. container:: :name: {name} {name}:",
"xmax = max(x for x, y in pos.values()) + 100 # add offset",
"= pos[node] return {\"rule\": node, \"fx\": x, \"fy\": y} nodes = list(map(encode_node, g.nodes))",
".. _Results: #results .. _Rules: #rules .. _Statistics: #stats {% for cat, catresults",
"mime def report(text, path, stylesheet=os.path.join(os.path.dirname(__file__), \"report.css\"), defaultenc=\"utf8\", template=None, metadata=None, **files): outmime, _ =",
"per-rule information rules = defaultdict(list) for rec in records.values(): rule = RuleRecord(job, rec)",
"links}, xmax, ymax def get_resource_as_string(url): r = requests.get(url) if r.status_code == requests.codes.ok: return",
"import uuid import json import time import shutil import subprocess as sp import",
"idx[v], \"value\": 1} for u, v in g.edges] return {\"nodes\": nodes, \"links\": links},",
"if metadata else \"\", date=datetime.date.today().isoformat()) text = format(textwrap.dedent(text), stepout=3) attachments = [] if",
"directives that use a base64 # data URI instead of pointing to a",
"for {}, assuming \" \"text/plain.\".format(file)) if encoding is None: encoding = defaultenc with",
":name: {name} {name}: {links} '''.format(name=name, links=links)) text = definitions + text + \"\\n\\n\"",
"nodes, \"links\": links}, xmax, ymax def get_resource_as_string(url): r = requests.get(url) if r.status_code ==",
"recorded_files: if not f.exists: raise WorkflowError(\"File {} marked for report but does \"",
"{\"nodes\": nodes, \"links\": links}, xmax, ymax def get_resource_as_string(url): r = requests.get(url) if r.status_code",
"= open(path, \"w\") publish_file(source=io.StringIO(text), destination=html, writer_name=\"html\", settings_overrides=overrides) class RuleRecord: def __init__(self, job, job_rec):",
"path.endswith(\".html\"): raise WorkflowError(\"Report file does not end with .html\") logger.info(\"Creating report...\") persistence =",
"self.singularity_img_url == other.singularity_img_url) class JobRecord: def __init__(self): self.rule = None self.starttime = sys.maxsize",
"\" \"not exist.\".format(f)) if os.path.isfile(f): report_obj = get_flag_value(f, \"report\") category = report_obj.category or",
"= directives.uri(self.arguments[0]) self.options['uri'] = data_uri_from_file(reference)[0] return result # Create (and register) new image::",
"def encode_node(node): x, y = pos[node] return {\"rule\": node, \"fx\": x, \"fy\": y}",
"import mimetypes import base64 import textwrap import datetime import io import uuid import",
"rulegraph_nodes=rulegraph[\"nodes\"], rulegraph_links=rulegraph[\"links\"], rulegraph_width=xmax + 20, rulegraph_height=ymax + 20, runtimes=runtimes, timeline=timeline, rules=[rec for recs",
"rst_links, results) # global description text = \"\" if dag.workflow.report_text: with open(dag.workflow.report_text) as",
"\"\"\" def run(self): \"\"\" Image.run() handles most of the \"\"\" result = Image.run(self)",
"# global description text = \"\" if dag.workflow.report_text: with open(dag.workflow.report_text) as f: class",
"y = pos[node] return {\"rule\": node, \"fx\": x, \"fy\": y} nodes = list(map(encode_node,",
"auto_report(dag, path): try: from jinja2 import Template, Environment, PackageLoader except ImportError as e:",
"+ text + \"\\n\\n\" + \"\\n\\n\".join(attachments) + metadata overrides = dict() if template",
"#rules .. _Statistics: #stats {% for cat, catresults in results|dictsort %} .. _{{",
"def icon(self): if self.is_img: return \"image\" elif self.is_text: return \"file-text\" else: return \"file\"",
"for job in dag.jobs: target = job.rule.name for dep in dag.dependencies[job]: source =",
"with open(dag.workflow.report_text) as f: class Snakemake: config = dag.workflow.config text = f.read() +",
"encoding = defaultenc with open(file, \"rb\") as f: return data_uri(f.read(), os.path.basename(file), encoding, mime),",
"@property def is_text(self): text = {\"text/csv\", \"text/plain\", \"text/tab-separated-values\"} return self.mime in text @property",
"is_text(self): text = {\"text/csv\", \"text/plain\", \"text/tab-separated-values\"} return self.mime in text @property def icon(self):",
"rules = defaultdict(list) for rec in records.values(): rule = RuleRecord(job, rec) if rec.rule",
"version.\".format(f)) for catresults in results.values(): catresults.sort(key=lambda res: res.name) # prepare runtimes runtimes =",
"in results|dictsort %} .. _{{ cat }}: #results-{{ cat|replace(\" \", \"_\") }} {%",
"in the report.\") def render(self, env, rst_links, results): if self.raw_caption is not None:",
"yaml.load(self._conda_env_raw) self.n_jobs = 1 self.output = list(job_rec.output) self.id = uuid.uuid4() def add(self, job_rec):",
"= sum(res.size for cat in results.values() for res in cat) # render HTML",
"= None if self.is_img: convert = shutil.which(\"convert\") if convert is not None: try:",
"self.mime in text @property def icon(self): if self.is_img: return \"image\" elif self.is_text: return",
"class EmbeddedImage(Image, EmbeddedMixin): pass directives.register_directive('embeddedimage', EmbeddedImage) class EmbeddedFigure(Figure, EmbeddedMixin): pass directives.register_directive('embeddedfigure', EmbeddedFigure) def",
"r = requests.get(url) if r.status_code == requests.codes.ok: return r.text raise WorkflowError(\"Failed to download",
"links.append(':raw-html:`<a href=\"{data}\" download=\"{filename}\" draggable=\"true\">{filename}</a>`'.format( data=data, filename=os.path.basename(file))) links = \"\\n\\n \".join(links) attachments.append(''' .. container::",
"for f in itertools.chain(job.expanded_output, job.input): if is_flagged(f, \"report\") and f not in recorded_files:",
"return (self.name == other.name and self.conda_env == other.conda_env and self.singularity_img_url == other.singularity_img_url) class",
"for labels ymax = max(y for x, y in pos.values()) def encode_node(node): x,",
"\"dot\", args=\"-Grankdir=BT\") xmax = max(x for x, y in pos.values()) + 100 #",
"other.conda_env and self.singularity_img_url == other.singularity_img_url) class JobRecord: def __init__(self): self.rule = None self.starttime",
"job_rec): self.n_jobs += 1 self.output.extend(job_rec.output) def __eq__(self, other): return (self.name == other.name and",
"writer_name=\"html\", settings_overrides=overrides) class RuleRecord: def __init__(self, job, job_rec): import yaml self.name = job_rec.rule",
"metadata else \"\", date=datetime.date.today().isoformat()) text = format(textwrap.dedent(text), stepout=3) attachments = [] if files:",
"datetime.datetime.fromtimestamp(rec.starttime).isoformat(), \"endtime\": datetime.datetime.fromtimestamp(rec.endtime).isoformat()} for rec in sorted(records.values(), key=lambda rec: rec.rule)] # prepare per-rule",
"= [] self.conda_env_file = None self.singularity_img_url = None class FileRecord: def __init__(self, path,",
"text = format(textwrap.dedent(text), stepout=3) attachments = [] if files: attachments = [textwrap.dedent(\"\"\" ..",
"links=links)) text = definitions + text + \"\\n\\n\" + \"\\n\\n\".join(attachments) + metadata overrides",
"= Environment(loader=PackageLoader(\"snakemake\", \"report\"), trim_blocks=True, lstrip_blocks=True) env.filters[\"get_resource_as_string\"] = get_resource_as_string rst_links = textwrap.dedent(\"\"\" .. _Results:",
"max(x for x, y in pos.values()) + 100 # add offset to account",
"for catresults in results.values(): catresults.sort(key=lambda res: res.name) # prepare runtimes runtimes = [{\"rule\":",
"persistence = dag.workflow.persistence results = defaultdict(list) records = defaultdict(JobRecord) recorded_files = set() for",
"def name(self): return os.path.basename(self.path) @property def size(self): \"\"\"Return size in Bytes.\"\"\" return os.path.getsize(self.path)",
"rec.conda_env_file = None rec.conda_env = meta[\"conda_env\"] rec.singularity_img_url = meta[\"singularity_img_url\"] rec.output.append(f) except KeyError as",
"if rec.rule not in rules: rules[rec.rule].append(rule) else: merged = False for other in",
"\"w\", encoding=\"utf-8\") as out: out.write(template.render(results=results, results_size=results_size, text=text, rulegraph_nodes=rulegraph[\"nodes\"], rulegraph_links=rulegraph[\"links\"], rulegraph_width=xmax + 20, rulegraph_height=ymax",
"}} {% endfor %} {% endfor %} .. _ \"\"\") for cat, catresults",
"= yaml.load(self._conda_env_raw) self.n_jobs = 1 self.output = list(job_rec.output) self.id = uuid.uuid4() def add(self,",
"reports. \"\"\" def run(self): \"\"\" Image.run() handles most of the \"\"\" result =",
"get_flag_value from snakemake.exceptions import WorkflowError from snakemake.script import Snakemake from snakemake import __version__",
"= meta[\"conda_env\"] rec.singularity_img_url = meta[\"singularity_img_url\"] rec.output.append(f) except KeyError as e: print(e) logger.warning(\"Metadata for",
"results): if self.raw_caption is not None: try: from jinja2 import Template except ImportError",
"res.name) # prepare runtimes runtimes = [{\"rule\": rec.rule, \"runtime\": rec.endtime - rec.starttime} for",
"get_resource_as_string rst_links = textwrap.dedent(\"\"\" .. _Results: #results .. _Rules: #rules .. _Statistics: #stats",
"\" \"text/plain.\".format(file)) if encoding is None: encoding = defaultenc with open(file, \"rb\") as",
"if is_flagged(f, \"report\") and f not in recorded_files: if not f.exists: raise WorkflowError(\"File",
"from snakemake.utils import format from snakemake.logging import logger from snakemake.io import is_flagged, get_flag_value",
"is_flagged(f, \"report\") and f not in recorded_files: if not f.exists: raise WorkflowError(\"File {}",
"detect mimetype for {}, assuming \" \"text/plain.\".format(file)) if encoding is None: encoding =",
"sys.maxsize self.endtime = 0 self.output = [] self.conda_env_file = None self.singularity_img_url = None",
"self.caption = publish_parts(caption, writer_name=\"html\")[\"body\"] except Exception as e: raise WorkflowError(\"Error loading caption file",
"runtimes runtimes = [{\"rule\": rec.rule, \"runtime\": rec.endtime - rec.starttime} for rec in sorted(records.values(),",
"os import sys import mimetypes import base64 import textwrap import datetime import io",
"EmbeddedFigure(Figure, EmbeddedMixin): pass directives.register_directive('embeddedfigure', EmbeddedFigure) def data_uri(data, filename, encoding=\"utf8\", mime=\"text/plain\"): \"\"\"Craft a base64",
"def auto_report(dag, path): try: from jinja2 import Template, Environment, PackageLoader except ImportError as",
"WorkflowError(\"File {} marked for report but does \" \"not exist.\".format(f)) if os.path.isfile(f): report_obj",
".. role:: raw-html(raw) :format: html \"\"\") metadata = textwrap.dedent(\"\"\" .. container:: :name: metadata",
"import base64 import textwrap import datetime import io import uuid import json import",
"packages networkx and pygraphviz must be \" \"installed to create reports.\", e) g",
"job.threads, job.resources, job.log, job.dag.workflow.config, job.rule.name, None) try: caption = open(self.raw_caption).read() + rst_links caption",
"encoding and mimetype.\"\"\" mime, encoding = mimetypes.guess_type(file) if mime is None: mime =",
"list(job_rec.output) self.id = uuid.uuid4() def add(self, job_rec): self.n_jobs += 1 self.output.extend(job_rec.output) def __eq__(self,",
"networkx and pygraphviz must be \" \"installed to create reports.\", e) g =",
"rst_links caption = env.from_string(caption).render(snakemake=snakemake, results=results) self.caption = publish_parts(caption, writer_name=\"html\")[\"body\"] except Exception as e:",
"rule rec.starttime = min(rec.starttime, meta[\"starttime\"]) rec.endtime = max(rec.endtime, meta[\"endtime\"]) rec.conda_env_file = None rec.conda_env",
"other in rules[rec.rule]: if rule == other: other.add(rec) merged = True break if",
"# prepare per-rule information rules = defaultdict(list) for rec in records.values(): rule =",
"definitions = textwrap.dedent(\"\"\" .. role:: raw-html(raw) :format: html \"\"\") metadata = textwrap.dedent(\"\"\" ..",
"= [{\"rule\": rec.rule, \"runtime\": rec.endtime - rec.starttime} for rec in sorted(records.values(), key=lambda rec:",
"href=\"{data}\" download=\"{filename}\" draggable=\"true\">{filename}</a>`'.format( data=data, filename=os.path.basename(file))) links = \"\\n\\n \".join(links) attachments.append(''' .. container:: :name:",
"mime is None: mime = \"text/plain\" logger.info(\"Could not detect mimetype for {}, assuming",
"merged: rules[rec.rule].append(rule) # rulegraph rulegraph, xmax, ymax = rulegraph_d3_spec(dag) env = Environment(loader=PackageLoader(\"snakemake\", \"report\"),",
"job = self.job snakemake = Snakemake(job.input, job.output, job.params, job.wildcards, job.threads, job.resources, job.log, job.dag.workflow.config,",
"URI from file with proper encoding and mimetype.\"\"\" mime, encoding = mimetypes.guess_type(file) if",
"if rule == other: other.add(rec) merged = True break if not merged: rules[rec.rule].append(rule)",
"base64-encoded version. Useful for embedding images/figures in reports. \"\"\" def run(self): \"\"\" Image.run()",
"else: logger.warning(\"Command convert not in $PATH. Install \" \"imagemagick in order to have",
"must be \" \"installed to create reports.\", e) g = nx.DiGraph() g.add_nodes_from(sorted(job.rule.name for",
"\" \"imagemagick in order to have embedded \" \"images and pdfs in the",
"res: res.name) # prepare runtimes runtimes = [{\"rule\": rec.rule, \"runtime\": rec.endtime - rec.starttime}",
"EmbeddedImage) class EmbeddedFigure(Figure, EmbeddedMixin): pass directives.register_directive('embeddedfigure', EmbeddedFigure) def data_uri(data, filename, encoding=\"utf8\", mime=\"text/plain\"): \"\"\"Craft",
"# record time now = \"{} {}\".format(datetime.datetime.now().ctime(), time.tzname[0]) results_size = sum(res.size for cat",
"cat }}: #results-{{ cat|replace(\" \", \"_\") }} {% for res in catresults %}",
"from snakemake.exceptions import WorkflowError from snakemake.script import Snakemake from snakemake import __version__ class",
"WorkflowError(\"Python packages networkx and pygraphviz must be \" \"installed to create reports.\", e)",
"create reports.\", e) g = nx.DiGraph() g.add_nodes_from(sorted(job.rule.name for job in dag.jobs)) for job",
"job.rule.name for dep in dag.dependencies[job]: source = dep.rule.name g.add_edge(source, target) pos = graphviz_layout(g,",
"and self.singularity_img_url == other.singularity_img_url) class JobRecord: def __init__(self): self.rule = None self.starttime =",
"None if self.is_img: convert = shutil.which(\"convert\") if convert is not None: try: png",
"e: raise WorkflowError(\"Python packages networkx and pygraphviz must be \" \"installed to create",
"runtimes = [{\"rule\": rec.rule, \"runtime\": rec.endtime - rec.starttime} for rec in sorted(records.values(), key=lambda",
"= dag.workflow.config text = f.read() + rst_links text = publish_parts(env.from_string(text).render( snakemake=Snakemake, results=results), writer_name=\"html\")[\"body\"]",
"data_uri_from_file(reference)[0] return result # Create (and register) new image:: and figure:: directives that",
"{}, assuming \" \"text/plain.\".format(file)) if encoding is None: encoding = defaultenc with open(file,",
"settings_overrides=overrides) class RuleRecord: def __init__(self, job, job_rec): import yaml self.name = job_rec.rule self.singularity_img_url",
"r.text raise WorkflowError(\"Failed to download resource needed for \" \"report: {}\".format(url)) def auto_report(dag,",
"figure:: directives that use a base64 # data URI instead of pointing to",
"docutils.parsers.rst import directives from docutils.core import publish_file, publish_parts from snakemake.utils import format from",
"to a filename. class EmbeddedImage(Image, EmbeddedMixin): pass directives.register_directive('embeddedimage', EmbeddedImage) class EmbeddedFigure(Figure, EmbeddedMixin): pass",
"mimetypes.guess_type(file) if mime is None: mime = \"text/plain\" logger.info(\"Could not detect mimetype for",
"is not None: overrides[\"stylesheet_path\"] = stylesheet html = open(path, \"w\") publish_file(source=io.StringIO(text), destination=html, writer_name=\"html\",",
"the report.\") def render(self, env, rst_links, results): if self.raw_caption is not None: try:",
"with \" \"imagemagick convert: {}\".format(e.stderr)) else: logger.warning(\"Command convert not in $PATH. Install \"",
"in dag.jobs: target = job.rule.name for dep in dag.dependencies[job]: source = dep.rule.name g.add_edge(source,",
"in results.items(): for res in catresults: res.render(env, rst_links, results) # global description text",
"= \"text/plain\" logger.info(\"Could not detect mimetype for {}, assuming \" \"text/plain.\".format(file)) if encoding",
"for other in rules[rec.rule]: if rule == other: other.add(rec) merged = True break",
"to download resource needed for \" \"report: {}\".format(url)) def auto_report(dag, path): try: from",
"__init__(self): self.rule = None self.starttime = sys.maxsize self.endtime = 0 self.output = []",
"job.resources, job.log, job.dag.workflow.config, job.rule.name, None) try: caption = open(self.raw_caption).read() + rst_links caption =",
"report but does \" \"not exist.\".format(f)) if os.path.isfile(f): report_obj = get_flag_value(f, \"report\") category",
"not in $PATH. Install \" \"imagemagick in order to have embedded \" \"images",
"result # Create (and register) new image:: and figure:: directives that use a",
"handles most of the \"\"\" result = Image.run(self) reference = directives.uri(self.arguments[0]) self.options['uri'] =",
"= max(rec.endtime, meta[\"endtime\"]) rec.conda_env_file = None rec.conda_env = meta[\"conda_env\"] rec.singularity_img_url = meta[\"singularity_img_url\"] rec.output.append(f)",
"y} nodes = list(map(encode_node, g.nodes)) idx = {node: i for i, node in",
"# prepare runtimes runtimes = [{\"rule\": rec.rule, \"runtime\": rec.endtime - rec.starttime} for rec",
"= list(job_rec.output) self.id = uuid.uuid4() def add(self, job_rec): self.n_jobs += 1 self.output.extend(job_rec.output) def",
"description text = \"\" if dag.workflow.report_text: with open(dag.workflow.report_text) as f: class Snakemake: config",
"import os import sys import mimetypes import base64 import textwrap import datetime import",
"in recorded_files: if not f.exists: raise WorkflowError(\"File {} marked for report but does",
"not detect mimetype for {}, assuming \" \"text/plain.\".format(file)) if encoding is None: encoding",
"\"old Snakemake version.\".format(f)) for catresults in results.values(): catresults.sort(key=lambda res: res.name) # prepare runtimes",
"rec.endtime - rec.starttime} for rec in sorted(records.values(), key=lambda rec: rec.rule)] # prepare end",
"{name} {name}: {links} '''.format(name=name, links=links)) text = definitions + text + \"\\n\\n\" +",
"from docutils.parsers.rst import directives from docutils.core import publish_file, publish_parts from snakemake.utils import format",
"\"file-text\" else: return \"file\" @property def name(self): return os.path.basename(self.path) @property def size(self): \"\"\"Return",
"\"100\", self.path, \"png:-\"], stderr=sp.PIPE) uri = data_uri(png, os.path.basename(self.path) + \".png\", mime=\"image/png\") self.png_uri =",
"job_rec): import yaml self.name = job_rec.rule self.singularity_img_url = job_rec.singularity_img_url self.conda_env = None self._conda_env_raw",
"= {node: i for i, node in enumerate(g.nodes)} links = [{\"target\": idx[u], \"source\":",
"if not meta: logger.warning(\"Missing metadata for file {}\".format(f)) continue try: job_hash = meta[\"job_hash\"]",
"rulegraph_links=rulegraph[\"links\"], rulegraph_width=xmax + 20, rulegraph_height=ymax + 20, runtimes=runtimes, timeline=timeline, rules=[rec for recs in",
"x, y = pos[node] return {\"rule\": node, \"fx\": x, \"fy\": y} nodes =",
"__copyright__ = \"Copyright 2015, <NAME>\" __email__ = \"<EMAIL>\" __license__ = \"MIT\" import os",
"job, job_rec): import yaml self.name = job_rec.rule self.singularity_img_url = job_rec.singularity_img_url self.conda_env = None",
"#results-{{ cat|replace(\" \", \"_\") }} {% for res in catresults %} .. _{{",
"not path.endswith(\".html\"): raise WorkflowError(\"Report file does not end with .html\") logger.info(\"Creating report...\") persistence",
"recorded_files.add(f) for f in job.expanded_output: meta = persistence.metadata(f) if not meta: logger.warning(\"Missing metadata",
"rules=[rec for recs in rules.values() for rec in recs], version=__version__, now=now)) logger.info(\"Report created.\")",
"\"image/png\", \"image/svg+xml\", \"application/pdf\"} return self.mime in web_safe @property def is_text(self): text = {\"text/csv\",",
"jinja2 must be installed to create reports.\") if not path.endswith(\".html\"): raise WorkflowError(\"Report file",
"for file {}\".format(f)) continue try: job_hash = meta[\"job_hash\"] rule = meta[\"rule\"] rec =",
"now = \"{} {}\".format(datetime.datetime.now().ctime(), time.tzname[0]) results_size = sum(res.size for cat in results.values() for",
"\"\" if dag.workflow.report_text: with open(dag.workflow.report_text) as f: class Snakemake: config = dag.workflow.config text",
"def data_uri_from_file(file, defaultenc=\"utf8\"): \"\"\"Craft a base64 data URI from file with proper encoding",
"mimetype.\"\"\" data = base64.b64encode(data) uri = (\"data:{mime};charset={charset};filename={filename};base64,{data}\" \"\".format(filename=filename, mime=mime, charset=encoding, data=data.decode(\"utf-8\"))) return uri",
"charset=encoding, data=data.decode(\"utf-8\"))) return uri def data_uri_from_file(file, defaultenc=\"utf8\"): \"\"\"Craft a base64 data URI from",
"self._conda_env_raw = base64.b64decode(job_rec.conda_env).decode() self.conda_env = yaml.load(self._conda_env_raw) self.n_jobs = 1 self.output = list(job_rec.output) self.id",
"rec in sorted(records.values(), key=lambda rec: rec.rule)] # prepare per-rule information rules = defaultdict(list)",
"= min(rec.starttime, meta[\"starttime\"]) rec.endtime = max(rec.endtime, meta[\"endtime\"]) rec.conda_env_file = None rec.conda_env = meta[\"conda_env\"]",
"== other.conda_env and self.singularity_img_url == other.singularity_img_url) class JobRecord: def __init__(self): self.rule = None",
"encoding=\"utf-8\") as out: out.write(template.render(results=results, results_size=results_size, text=text, rulegraph_nodes=rulegraph[\"nodes\"], rulegraph_links=rulegraph[\"links\"], rulegraph_width=xmax + 20, rulegraph_height=ymax +",
"self.conda_env == other.conda_env and self.singularity_img_url == other.singularity_img_url) class JobRecord: def __init__(self): self.rule =",
"source = dep.rule.name g.add_edge(source, target) pos = graphviz_layout(g, \"dot\", args=\"-Grankdir=BT\") xmax = max(x",
"in sorted(records.values(), key=lambda rec: rec.rule)] # prepare end times timeline = [{\"rule\": rec.rule,",
"dag.jobs)) for job in dag.jobs: target = job.rule.name for dep in dag.dependencies[job]: source",
"raise WorkflowError(\"Python package jinja2 must be installed to create reports.\") if not path.endswith(\".html\"):",
"attachments.append(''' .. container:: :name: {name} {name}: {links} '''.format(name=name, links=links)) text = definitions +",
"pointing to a filename. class EmbeddedImage(Image, EmbeddedMixin): pass directives.register_directive('embeddedimage', EmbeddedImage) class EmbeddedFigure(Figure, EmbeddedMixin):",
"\"\\n\\n\" + \"\\n\\n\".join(attachments) + metadata overrides = dict() if template is not None:",
"image:: and figure:: directives that use a base64 # data URI instead of",
"reports.\") job = self.job snakemake = Snakemake(job.input, job.output, job.params, job.wildcards, job.threads, job.resources, job.log,",
"EmbeddedMixin): pass directives.register_directive('embeddedimage', EmbeddedImage) class EmbeddedFigure(Figure, EmbeddedMixin): pass directives.register_directive('embeddedfigure', EmbeddedFigure) def data_uri(data, filename,",
"= format(textwrap.dedent(text), stepout=3) attachments = [] if files: attachments = [textwrap.dedent(\"\"\" .. container::",
"== requests.codes.ok: return r.text raise WorkflowError(\"Failed to download resource needed for \" \"report:",
"uuid.uuid4() def add(self, job_rec): self.n_jobs += 1 self.output.extend(job_rec.output) def __eq__(self, other): return (self.name",
"is_img(self): web_safe = {\"image/gif\", \"image/jpeg\", \"image/png\", \"image/svg+xml\", \"application/pdf\"} return self.mime in web_safe @property",
"instead of pointing to a filename. class EmbeddedImage(Image, EmbeddedMixin): pass directives.register_directive('embeddedimage', EmbeddedImage) class",
"meta: logger.warning(\"Missing metadata for file {}\".format(f)) continue try: job_hash = meta[\"job_hash\"] rule =",
"= \"Copyright 2015, <NAME>\" __email__ = \"<EMAIL>\" __license__ = \"MIT\" import os import",
"report output has to be an HTML file.\") definitions = textwrap.dedent(\"\"\" .. role::",
"= env.get_template(\"report.html\") with open(path, \"w\", encoding=\"utf-8\") as out: out.write(template.render(results=results, results_size=results_size, text=text, rulegraph_nodes=rulegraph[\"nodes\"], rulegraph_links=rulegraph[\"links\"],",
"\"<NAME>\" __copyright__ = \"Copyright 2015, <NAME>\" __email__ = \"<EMAIL>\" __license__ = \"MIT\" import",
"as nx from networkx.drawing.nx_agraph import graphviz_layout from networkx.readwrite import json_graph except ImportError as",
"self.mime = data_uri_from_file(path) self.id = uuid.uuid4() self.job = job self.png_uri = None if",
"set() for job in dag.jobs: for f in itertools.chain(job.expanded_output, job.input): if is_flagged(f, \"report\")",
"+ \"\\n\\n\" + \"\\n\\n\".join(attachments) + metadata overrides = dict() if template is not",
"def __init__(self): self.rule = None self.starttime = sys.maxsize self.endtime = 0 self.output =",
"icon(self): if self.is_img: return \"image\" elif self.is_text: return \"file-text\" else: return \"file\" @property",
"import io import uuid import json import time import shutil import subprocess as",
"**files): outmime, _ = mimetypes.guess_type(path) if outmime != \"text/html\": raise ValueError(\"Path to report",
"version. Useful for embedding images/figures in reports. \"\"\" def run(self): \"\"\" Image.run() handles",
"= None class FileRecord: def __init__(self, path, job, caption): self.path = path logger.info(\"Adding",
"\"text/html\": raise ValueError(\"Path to report output has to be an HTML file.\") definitions",
"return \"file\" @property def name(self): return os.path.basename(self.path) @property def size(self): \"\"\"Return size in",
"= [_files] links = [] for file in sorted(_files): data, _ = data_uri_from_file(file)",
"\"image/svg+xml\", \"application/pdf\"} return self.mime in web_safe @property def is_text(self): text = {\"text/csv\", \"text/plain\",",
"= persistence.metadata(f) if not meta: logger.warning(\"Missing metadata for file {}\".format(f)) continue try: job_hash",
"(and register) new image:: and figure:: directives that use a base64 # data",
"break if not merged: rules[rec.rule].append(rule) # rulegraph rulegraph, xmax, ymax = rulegraph_d3_spec(dag) env",
"requests.get(url) if r.status_code == requests.codes.ok: return r.text raise WorkflowError(\"Failed to download resource needed",
"if self.raw_caption is not None: try: from jinja2 import Template except ImportError as",
"rec in records.values(): rule = RuleRecord(job, rec) if rec.rule not in rules: rules[rec.rule].append(rule)",
"}} {% for res in catresults %} .. _{{ res.name }}: #{{ res.id",
"os.path.basename(file), encoding, mime), mime def report(text, path, stylesheet=os.path.join(os.path.dirname(__file__), \"report.css\"), defaultenc=\"utf8\", template=None, metadata=None, **files):",
"{}\".format(url)) def auto_report(dag, path): try: from jinja2 import Template, Environment, PackageLoader except ImportError",
"20, rulegraph_height=ymax + 20, runtimes=runtimes, timeline=timeline, rules=[rec for recs in rules.values() for rec",
"labels ymax = max(y for x, y in pos.values()) def encode_node(node): x, y",
"installed to create reports.\") if not path.endswith(\".html\"): raise WorkflowError(\"Report file does not end",
"WorkflowError(\"Python package jinja2 must be installed to create reports.\") job = self.job snakemake",
"end with .html\") logger.info(\"Creating report...\") persistence = dag.workflow.persistence results = defaultdict(list) records =",
"encoding=\"utf8\", mime=\"text/plain\"): \"\"\"Craft a base64 data URI from file with proper encoding and",
"_files in sorted(files.items()): if not isinstance(_files, list): _files = [_files] links = []",
"sp.CalledProcessError as e: logger.warning(\"Failed to convert image to png with \" \"imagemagick convert:",
"in web_safe @property def is_text(self): text = {\"text/csv\", \"text/plain\", \"text/tab-separated-values\"} return self.mime in",
"= uri except sp.CalledProcessError as e: logger.warning(\"Failed to convert image to png with",
"self.singularity_img_url = job_rec.singularity_img_url self.conda_env = None self._conda_env_raw = None if job_rec.conda_env: self._conda_env_raw =",
"other.singularity_img_url) class JobRecord: def __init__(self): self.rule = None self.starttime = sys.maxsize self.endtime =",
"create reports.\") if not path.endswith(\".html\"): raise WorkflowError(\"Report file does not end with .html\")",
"= job_rec.rule self.singularity_img_url = job_rec.singularity_img_url self.conda_env = None self._conda_env_raw = None if job_rec.conda_env:",
"= None self.singularity_img_url = None class FileRecord: def __init__(self, path, job, caption): self.path",
"ymax def get_resource_as_string(url): r = requests.get(url) if r.status_code == requests.codes.ok: return r.text raise",
"_Statistics: #stats {% for cat, catresults in results|dictsort %} .. _{{ cat }}:",
"cat) # render HTML template = env.get_template(\"report.html\") with open(path, \"w\", encoding=\"utf-8\") as out:",
"= dep.rule.name g.add_edge(source, target) pos = graphviz_layout(g, \"dot\", args=\"-Grankdir=BT\") xmax = max(x for",
"defaultenc=\"utf8\", template=None, metadata=None, **files): outmime, _ = mimetypes.guess_type(path) if outmime != \"text/html\": raise",
"encoding is None: encoding = defaultenc with open(file, \"rb\") as f: return data_uri(f.read(),",
"rules[rec.rule].append(rule) else: merged = False for other in rules[rec.rule]: if rule == other:",
".. _Statistics: #stats {% for cat, catresults in results|dictsort %} .. _{{ cat",
"meta[\"conda_env\"] rec.singularity_img_url = meta[\"singularity_img_url\"] rec.output.append(f) except KeyError as e: print(e) logger.warning(\"Metadata for file",
"rec.rule not in rules: rules[rec.rule].append(rule) else: merged = False for other in rules[rec.rule]:",
"| \" if metadata else \"\", date=datetime.date.today().isoformat()) text = format(textwrap.dedent(text), stepout=3) attachments =",
"self.n_jobs += 1 self.output.extend(job_rec.output) def __eq__(self, other): return (self.name == other.name and self.conda_env",
"\" \"installed to create reports.\", e) g = nx.DiGraph() g.add_nodes_from(sorted(job.rule.name for job in",
"= data_uri_from_file(file) links.append(':raw-html:`<a href=\"{data}\" download=\"{filename}\" draggable=\"true\">{filename}</a>`'.format( data=data, filename=os.path.basename(file))) links = \"\\n\\n \".join(links) attachments.append('''",
"to png with \" \"imagemagick convert: {}\".format(e.stderr)) else: logger.warning(\"Command convert not in $PATH.",
"jinja2 must be installed to create reports.\") job = self.job snakemake = Snakemake(job.input,",
":name: attachments \"\"\")] for name, _files in sorted(files.items()): if not isinstance(_files, list): _files",
"for rec in sorted(records.values(), key=lambda rec: rec.rule)] # prepare per-rule information rules =",
"for u, v in g.edges] return {\"nodes\": nodes, \"links\": links}, xmax, ymax def",
"+ 20, runtimes=runtimes, timeline=timeline, rules=[rec for recs in rules.values() for rec in recs],",
"publish_file(source=io.StringIO(text), destination=html, writer_name=\"html\", settings_overrides=overrides) class RuleRecord: def __init__(self, job, job_rec): import yaml self.name",
"file.\") definitions = textwrap.dedent(\"\"\" .. role:: raw-html(raw) :format: html \"\"\") metadata = textwrap.dedent(\"\"\"",
"+ \" | \" if metadata else \"\", date=datetime.date.today().isoformat()) text = format(textwrap.dedent(text), stepout=3)",
"FileRecord(f, job, report_obj.caption)) recorded_files.add(f) for f in job.expanded_output: meta = persistence.metadata(f) if not",
"Image.run(self) reference = directives.uri(self.arguments[0]) self.options['uri'] = data_uri_from_file(reference)[0] return result # Create (and register)",
"res.name }}: #{{ res.id }} {% endfor %} {% endfor %} .. _",
"res in catresults %} .. _{{ res.name }}: #{{ res.id }} {% endfor",
"subprocess as sp import itertools from collections import namedtuple, defaultdict import requests from",
"e: print(e) logger.warning(\"Metadata for file {} was created with a too \" \"old",
"return uri def data_uri_from_file(file, defaultenc=\"utf8\"): \"\"\"Craft a base64 data URI from file with",
"None rec.conda_env = meta[\"conda_env\"] rec.singularity_img_url = meta[\"singularity_img_url\"] rec.output.append(f) except KeyError as e: print(e)",
"\" if metadata else \"\", date=datetime.date.today().isoformat()) text = format(textwrap.dedent(text), stepout=3) attachments = []",
"open(path, \"w\") publish_file(source=io.StringIO(text), destination=html, writer_name=\"html\", settings_overrides=overrides) class RuleRecord: def __init__(self, job, job_rec): import",
"if os.path.isfile(f): report_obj = get_flag_value(f, \"report\") category = report_obj.category or \" \" results[category].append(",
"metadata for file {}\".format(f)) continue try: job_hash = meta[\"job_hash\"] rule = meta[\"rule\"] rec",
"EmbeddedMixin): pass directives.register_directive('embeddedfigure', EmbeddedFigure) def data_uri(data, filename, encoding=\"utf8\", mime=\"text/plain\"): \"\"\"Craft a base64 data",
"= \"{} {}\".format(datetime.datetime.now().ctime(), time.tzname[0]) results_size = sum(res.size for cat in results.values() for res",
"data_uri_from_file(path) self.id = uuid.uuid4() self.job = job self.png_uri = None if self.is_img: convert",
"base64 import textwrap import datetime import io import uuid import json import time",
"1 self.output = list(job_rec.output) self.id = uuid.uuid4() def add(self, job_rec): self.n_jobs += 1",
"not in recorded_files: if not f.exists: raise WorkflowError(\"File {} marked for report but",
"def data_uri(data, filename, encoding=\"utf8\", mime=\"text/plain\"): \"\"\"Craft a base64 data URI from file with",
"None: overrides[\"stylesheet_path\"] = stylesheet html = open(path, \"w\") publish_file(source=io.StringIO(text), destination=html, writer_name=\"html\", settings_overrides=overrides) class",
"= f.read() + rst_links text = publish_parts(env.from_string(text).render( snakemake=Snakemake, results=results), writer_name=\"html\")[\"body\"] # record time",
"stylesheet html = open(path, \"w\") publish_file(source=io.StringIO(text), destination=html, writer_name=\"html\", settings_overrides=overrides) class RuleRecord: def __init__(self,",
"not f.exists: raise WorkflowError(\"File {} marked for report but does \" \"not exist.\".format(f))",
"results|dictsort %} .. _{{ cat }}: #results-{{ cat|replace(\" \", \"_\") }} {% for",
"__init__(self, job, job_rec): import yaml self.name = job_rec.rule self.singularity_img_url = job_rec.singularity_img_url self.conda_env =",
"dag.jobs: for f in itertools.chain(job.expanded_output, job.input): if is_flagged(f, \"report\") and f not in",
"= dict() if template is not None: overrides[\"template\"] = template if stylesheet is",
"times timeline = [{\"rule\": rec.rule, \"starttime\": datetime.datetime.fromtimestamp(rec.starttime).isoformat(), \"endtime\": datetime.datetime.fromtimestamp(rec.endtime).isoformat()} for rec in sorted(records.values(),",
"for res in cat) # render HTML template = env.get_template(\"report.html\") with open(path, \"w\",",
"new image:: and figure:: directives that use a base64 # data URI instead",
"shutil import subprocess as sp import itertools from collections import namedtuple, defaultdict import",
"image to png with \" \"imagemagick convert: {}\".format(e.stderr)) else: logger.warning(\"Command convert not in",
"import is_flagged, get_flag_value from snakemake.exceptions import WorkflowError from snakemake.script import Snakemake from snakemake",
"a base64 data URI from file with proper encoding and mimetype.\"\"\" mime, encoding",
"defaultdict(JobRecord) recorded_files = set() for job in dag.jobs: for f in itertools.chain(job.expanded_output, job.input):",
"if not isinstance(_files, list): _files = [_files] links = [] for file in",
"= uuid.uuid4() self.job = job self.png_uri = None if self.is_img: convert = shutil.which(\"convert\")",
"rst_links, results): if self.raw_caption is not None: try: from jinja2 import Template except",
"__license__ = \"MIT\" import os import sys import mimetypes import base64 import textwrap",
"= publish_parts(env.from_string(text).render( snakemake=Snakemake, results=results), writer_name=\"html\")[\"body\"] # record time now = \"{} {}\".format(datetime.datetime.now().ctime(), time.tzname[0])",
"= rule rec.starttime = min(rec.starttime, meta[\"starttime\"]) rec.endtime = max(rec.endtime, meta[\"endtime\"]) rec.conda_env_file = None",
"os.path.basename(self.path) + \".png\", mime=\"image/png\") self.png_uri = uri except sp.CalledProcessError as e: logger.warning(\"Failed to",
"import publish_file, publish_parts from snakemake.utils import format from snakemake.logging import logger from snakemake.io",
"text + \"\\n\\n\" + \"\\n\\n\".join(attachments) + metadata overrides = dict() if template is",
"other.add(rec) merged = True break if not merged: rules[rec.rule].append(rule) # rulegraph rulegraph, xmax,",
"self.mime in web_safe @property def is_text(self): text = {\"text/csv\", \"text/plain\", \"text/tab-separated-values\"} return self.mime",
"lstrip_blocks=True) env.filters[\"get_resource_as_string\"] = get_resource_as_string rst_links = textwrap.dedent(\"\"\" .. _Results: #results .. _Rules: #rules",
"not isinstance(_files, list): _files = [_files] links = [] for file in sorted(_files):",
"rec = records[(job_hash, rule)] rec.rule = rule rec.starttime = min(rec.starttime, meta[\"starttime\"]) rec.endtime =",
"file does not end with .html\") logger.info(\"Creating report...\") persistence = dag.workflow.persistence results =",
"{}\".format(f)) continue try: job_hash = meta[\"job_hash\"] rule = meta[\"rule\"] rec = records[(job_hash, rule)]",
"definitions + text + \"\\n\\n\" + \"\\n\\n\".join(attachments) + metadata overrides = dict() if",
"as f: return data_uri(f.read(), os.path.basename(file), encoding, mime), mime def report(text, path, stylesheet=os.path.join(os.path.dirname(__file__), \"report.css\"),",
"path, stylesheet=os.path.join(os.path.dirname(__file__), \"report.css\"), defaultenc=\"utf8\", template=None, metadata=None, **files): outmime, _ = mimetypes.guess_type(path) if outmime",
"in sorted(_files): data, _ = data_uri_from_file(file) links.append(':raw-html:`<a href=\"{data}\" download=\"{filename}\" draggable=\"true\">{filename}</a>`'.format( data=data, filename=os.path.basename(file))) links",
"idx = {node: i for i, node in enumerate(g.nodes)} links = [{\"target\": idx[u],",
"rec.rule, \"runtime\": rec.endtime - rec.starttime} for rec in sorted(records.values(), key=lambda rec: rec.rule)] #",
"self.id = uuid.uuid4() self.job = job self.png_uri = None if self.is_img: convert =",
"recorded_files = set() for job in dag.jobs: for f in itertools.chain(job.expanded_output, job.input): if",
"args=\"-Grankdir=BT\") xmax = max(x for x, y in pos.values()) + 100 # add",
"base64 data URI from file with proper encoding and mimetype.\"\"\" mime, encoding =",
"defaultdict(list) for rec in records.values(): rule = RuleRecord(job, rec) if rec.rule not in",
"False for other in rules[rec.rule]: if rule == other: other.add(rec) merged = True",
"in reports. \"\"\" def run(self): \"\"\" Image.run() handles most of the \"\"\" result",
"catresults: res.render(env, rst_links, results) # global description text = \"\" if dag.workflow.report_text: with",
"needed for \" \"report: {}\".format(url)) def auto_report(dag, path): try: from jinja2 import Template,",
"container:: :name: metadata {metadata}{date} \"\"\").format(metadata=metadata + \" | \" if metadata else \"\",",
"_Results: #results .. _Rules: #rules .. _Statistics: #stats {% for cat, catresults in",
"__email__ = \"<EMAIL>\" __license__ = \"MIT\" import os import sys import mimetypes import",
"resource needed for \" \"report: {}\".format(url)) def auto_report(dag, path): try: from jinja2 import",
"\" \" results[category].append( FileRecord(f, job, report_obj.caption)) recorded_files.add(f) for f in job.expanded_output: meta =",
"meta[\"endtime\"]) rec.conda_env_file = None rec.conda_env = meta[\"conda_env\"] rec.singularity_img_url = meta[\"singularity_img_url\"] rec.output.append(f) except KeyError",
"os.path.basename(self.path) @property def size(self): \"\"\"Return size in Bytes.\"\"\" return os.path.getsize(self.path) def rulegraph_d3_spec(dag): try:",
"file in sorted(_files): data, _ = data_uri_from_file(file) links.append(':raw-html:`<a href=\"{data}\" download=\"{filename}\" draggable=\"true\">{filename}</a>`'.format( data=data, filename=os.path.basename(file)))",
"RuleRecord: def __init__(self, job, job_rec): import yaml self.name = job_rec.rule self.singularity_img_url = job_rec.singularity_img_url",
"= meta[\"singularity_img_url\"] rec.output.append(f) except KeyError as e: print(e) logger.warning(\"Metadata for file {} was",
"prepare runtimes runtimes = [{\"rule\": rec.rule, \"runtime\": rec.endtime - rec.starttime} for rec in",
".html\") logger.info(\"Creating report...\") persistence = dag.workflow.persistence results = defaultdict(list) records = defaultdict(JobRecord) recorded_files",
"+= 1 self.output.extend(job_rec.output) def __eq__(self, other): return (self.name == other.name and self.conda_env ==",
"if self.is_img: convert = shutil.which(\"convert\") if convert is not None: try: png =",
"v in g.edges] return {\"nodes\": nodes, \"links\": links}, xmax, ymax def get_resource_as_string(url): r",
"\"w\") publish_file(source=io.StringIO(text), destination=html, writer_name=\"html\", settings_overrides=overrides) class RuleRecord: def __init__(self, job, job_rec): import yaml",
"\"report\") and f not in recorded_files: if not f.exists: raise WorkflowError(\"File {} marked",
"rst_links text = publish_parts(env.from_string(text).render( snakemake=Snakemake, results=results), writer_name=\"html\")[\"body\"] # record time now = \"{}",
"persistence.metadata(f) if not meta: logger.warning(\"Missing metadata for file {}\".format(f)) continue try: job_hash =",
"of pointing to a filename. class EmbeddedImage(Image, EmbeddedMixin): pass directives.register_directive('embeddedimage', EmbeddedImage) class EmbeddedFigure(Figure,",
"job_rec.conda_env: self._conda_env_raw = base64.b64decode(job_rec.conda_env).decode() self.conda_env = yaml.load(self._conda_env_raw) self.n_jobs = 1 self.output = list(job_rec.output)",
"publish_file, publish_parts from snakemake.utils import format from snakemake.logging import logger from snakemake.io import",
"package jinja2 must be installed to create reports.\") if not path.endswith(\".html\"): raise WorkflowError(\"Report",
"True break if not merged: rules[rec.rule].append(rule) # rulegraph rulegraph, xmax, ymax = rulegraph_d3_spec(dag)",
"as sp import itertools from collections import namedtuple, defaultdict import requests from docutils.parsers.rst.directives.images",
"with proper encoding and mimetype.\"\"\" mime, encoding = mimetypes.guess_type(file) if mime is None:",
"list): _files = [_files] links = [] for file in sorted(_files): data, _",
"to create reports.\") job = self.job snakemake = Snakemake(job.input, job.output, job.params, job.wildcards, job.threads,",
"_Rules: #rules .. _Statistics: #stats {% for cat, catresults in results|dictsort %} ..",
"get_flag_value(f, \"report\") category = report_obj.category or \" \" results[category].append( FileRecord(f, job, report_obj.caption)) recorded_files.add(f)",
"(\"data:{mime};charset={charset};filename={filename};base64,{data}\" \"\".format(filename=filename, mime=mime, charset=encoding, data=data.decode(\"utf-8\"))) return uri def data_uri_from_file(file, defaultenc=\"utf8\"): \"\"\"Craft a base64",
"runtimes=runtimes, timeline=timeline, rules=[rec for recs in rules.values() for rec in recs], version=__version__, now=now))",
"raise WorkflowError(\"Python packages networkx and pygraphviz must be \" \"installed to create reports.\",",
"= defaultdict(list) for rec in records.values(): rule = RuleRecord(job, rec) if rec.rule not",
"= sys.maxsize self.endtime = 0 self.output = [] self.conda_env_file = None self.singularity_img_url =",
"sorted(_files): data, _ = data_uri_from_file(file) links.append(':raw-html:`<a href=\"{data}\" download=\"{filename}\" draggable=\"true\">{filename}</a>`'.format( data=data, filename=os.path.basename(file))) links =",
"\"runtime\": rec.endtime - rec.starttime} for rec in sorted(records.values(), key=lambda rec: rec.rule)] # prepare",
"if not merged: rules[rec.rule].append(rule) # rulegraph rulegraph, xmax, ymax = rulegraph_d3_spec(dag) env =",
"uri = data_uri(png, os.path.basename(self.path) + \".png\", mime=\"image/png\") self.png_uri = uri except sp.CalledProcessError as",
"create reports.\") job = self.job snakemake = Snakemake(job.input, job.output, job.params, job.wildcards, job.threads, job.resources,",
"template is not None: overrides[\"template\"] = template if stylesheet is not None: overrides[\"stylesheet_path\"]",
"import format from snakemake.logging import logger from snakemake.io import is_flagged, get_flag_value from snakemake.exceptions",
"None: overrides[\"template\"] = template if stylesheet is not None: overrides[\"stylesheet_path\"] = stylesheet html",
"writer_name=\"html\")[\"body\"] except Exception as e: raise WorkflowError(\"Error loading caption file of output \"",
"self.output = [] self.conda_env_file = None self.singularity_img_url = None class FileRecord: def __init__(self,",
"self.job = job self.png_uri = None if self.is_img: convert = shutil.which(\"convert\") if convert",
"cat in results.values() for res in cat) # render HTML template = env.get_template(\"report.html\")",
"the URI of a directive with a base64-encoded version. Useful for embedding images/figures",
"for file in sorted(_files): data, _ = data_uri_from_file(file) links.append(':raw-html:`<a href=\"{data}\" download=\"{filename}\" draggable=\"true\">{filename}</a>`'.format( data=data,",
"= 0 self.output = [] self.conda_env_file = None self.singularity_img_url = None class FileRecord:",
"mimetypes import base64 import textwrap import datetime import io import uuid import json",
"ymax = rulegraph_d3_spec(dag) env = Environment(loader=PackageLoader(\"snakemake\", \"report\"), trim_blocks=True, lstrip_blocks=True) env.filters[\"get_resource_as_string\"] = get_resource_as_string rst_links",
"mime), mime def report(text, path, stylesheet=os.path.join(os.path.dirname(__file__), \"report.css\"), defaultenc=\"utf8\", template=None, metadata=None, **files): outmime, _",
"\"\\n\\n\".join(attachments) + metadata overrides = dict() if template is not None: overrides[\"template\"] =",
"raise WorkflowError(\"Error loading caption file of output \" \"marked for report.\", e) @property",
"template = env.get_template(\"report.html\") with open(path, \"w\", encoding=\"utf-8\") as out: out.write(template.render(results=results, results_size=results_size, text=text, rulegraph_nodes=rulegraph[\"nodes\"],",
"if convert is not None: try: png = sp.check_output([\"convert\", \"-density\", \"100\", self.path, \"png:-\"],",
"{metadata}{date} \"\"\").format(metadata=metadata + \" | \" if metadata else \"\", date=datetime.date.today().isoformat()) text =",
"self.n_jobs = 1 self.output = list(job_rec.output) self.id = uuid.uuid4() def add(self, job_rec): self.n_jobs",
"of the \"\"\" result = Image.run(self) reference = directives.uri(self.arguments[0]) self.options['uri'] = data_uri_from_file(reference)[0] return",
"directives.register_directive('embeddedimage', EmbeddedImage) class EmbeddedFigure(Figure, EmbeddedMixin): pass directives.register_directive('embeddedfigure', EmbeddedFigure) def data_uri(data, filename, encoding=\"utf8\", mime=\"text/plain\"):",
"results_size=results_size, text=text, rulegraph_nodes=rulegraph[\"nodes\"], rulegraph_links=rulegraph[\"links\"], rulegraph_width=xmax + 20, rulegraph_height=ymax + 20, runtimes=runtimes, timeline=timeline, rules=[rec",
"of output \" \"marked for report.\", e) @property def is_img(self): web_safe = {\"image/gif\",",
"= get_resource_as_string rst_links = textwrap.dedent(\"\"\" .. _Results: #results .. _Rules: #rules .. _Statistics:",
"None: mime = \"text/plain\" logger.info(\"Could not detect mimetype for {}, assuming \" \"text/plain.\".format(file))",
"and pdfs in the report.\") def render(self, env, rst_links, results): if self.raw_caption is",
"base64 data URI from file with proper encoding and mimetype.\"\"\" data = base64.b64encode(data)",
"f: return data_uri(f.read(), os.path.basename(file), encoding, mime), mime def report(text, path, stylesheet=os.path.join(os.path.dirname(__file__), \"report.css\"), defaultenc=\"utf8\",",
"self.conda_env = yaml.load(self._conda_env_raw) self.n_jobs = 1 self.output = list(job_rec.output) self.id = uuid.uuid4() def",
"[{\"rule\": rec.rule, \"runtime\": rec.endtime - rec.starttime} for rec in sorted(records.values(), key=lambda rec: rec.rule)]",
"out.write(template.render(results=results, results_size=results_size, text=text, rulegraph_nodes=rulegraph[\"nodes\"], rulegraph_links=rulegraph[\"links\"], rulegraph_width=xmax + 20, rulegraph_height=ymax + 20, runtimes=runtimes, timeline=timeline,",
"[_files] links = [] for file in sorted(_files): data, _ = data_uri_from_file(file) links.append(':raw-html:`<a",
"filename. class EmbeddedImage(Image, EmbeddedMixin): pass directives.register_directive('embeddedimage', EmbeddedImage) class EmbeddedFigure(Figure, EmbeddedMixin): pass directives.register_directive('embeddedfigure', EmbeddedFigure)",
"\", \"_\") }} {% for res in catresults %} .. _{{ res.name }}:",
"20, runtimes=runtimes, timeline=timeline, rules=[rec for recs in rules.values() for rec in recs], version=__version__,",
"node in enumerate(g.nodes)} links = [{\"target\": idx[u], \"source\": idx[v], \"value\": 1} for u,",
"to have embedded \" \"images and pdfs in the report.\") def render(self, env,",
"= [textwrap.dedent(\"\"\" .. container:: :name: attachments \"\"\")] for name, _files in sorted(files.items()): if",
"import sys import mimetypes import base64 import textwrap import datetime import io import",
"graphviz_layout from networkx.readwrite import json_graph except ImportError as e: raise WorkflowError(\"Python packages networkx",
"Create (and register) new image:: and figure:: directives that use a base64 #",
"nx from networkx.drawing.nx_agraph import graphviz_layout from networkx.readwrite import json_graph except ImportError as e:",
"xmax, ymax = rulegraph_d3_spec(dag) env = Environment(loader=PackageLoader(\"snakemake\", \"report\"), trim_blocks=True, lstrip_blocks=True) env.filters[\"get_resource_as_string\"] = get_resource_as_string",
"self.id = uuid.uuid4() def add(self, job_rec): self.n_jobs += 1 self.output.extend(job_rec.output) def __eq__(self, other):",
"== other: other.add(rec) merged = True break if not merged: rules[rec.rule].append(rule) # rulegraph",
"= definitions + text + \"\\n\\n\" + \"\\n\\n\".join(attachments) + metadata overrides = dict()",
"= 1 self.output = list(job_rec.output) self.id = uuid.uuid4() def add(self, job_rec): self.n_jobs +=",
"sorted(records.values(), key=lambda rec: rec.rule)] # prepare per-rule information rules = defaultdict(list) for rec",
"a too \" \"old Snakemake version.\".format(f)) for catresults in results.values(): catresults.sort(key=lambda res: res.name)",
"= open(self.raw_caption).read() + rst_links caption = env.from_string(caption).render(snakemake=snakemake, results=results) self.caption = publish_parts(caption, writer_name=\"html\")[\"body\"] except",
"template=None, metadata=None, **files): outmime, _ = mimetypes.guess_type(path) if outmime != \"text/html\": raise ValueError(\"Path",
"self.raw_caption = caption self.data_uri, self.mime = data_uri_from_file(path) self.id = uuid.uuid4() self.job = job",
"encoding, mime), mime def report(text, path, stylesheet=os.path.join(os.path.dirname(__file__), \"report.css\"), defaultenc=\"utf8\", template=None, metadata=None, **files): outmime,",
"= uuid.uuid4() def add(self, job_rec): self.n_jobs += 1 self.output.extend(job_rec.output) def __eq__(self, other): return",
"open(file, \"rb\") as f: return data_uri(f.read(), os.path.basename(file), encoding, mime), mime def report(text, path,",
"snakemake.logging import logger from snakemake.io import is_flagged, get_flag_value from snakemake.exceptions import WorkflowError from",
"def is_img(self): web_safe = {\"image/gif\", \"image/jpeg\", \"image/png\", \"image/svg+xml\", \"application/pdf\"} return self.mime in web_safe",
"mimetypes.guess_type(path) if outmime != \"text/html\": raise ValueError(\"Path to report output has to be",
"attachments = [textwrap.dedent(\"\"\" .. container:: :name: attachments \"\"\")] for name, _files in sorted(files.items()):",
"rulegraph_d3_spec(dag) env = Environment(loader=PackageLoader(\"snakemake\", \"report\"), trim_blocks=True, lstrip_blocks=True) env.filters[\"get_resource_as_string\"] = get_resource_as_string rst_links = textwrap.dedent(\"\"\"",
"'''.format(name=name, links=links)) text = definitions + text + \"\\n\\n\" + \"\\n\\n\".join(attachments) + metadata",
"{% endfor %} .. _ \"\"\") for cat, catresults in results.items(): for res",
"in results.values() for res in cat) # render HTML template = env.get_template(\"report.html\") with",
"= report_obj.category or \" \" results[category].append( FileRecord(f, job, report_obj.caption)) recorded_files.add(f) for f in",
"x, y in pos.values()) def encode_node(node): x, y = pos[node] return {\"rule\": node,",
"\"value\": 1} for u, v in g.edges] return {\"nodes\": nodes, \"links\": links}, xmax,",
"from networkx.readwrite import json_graph except ImportError as e: raise WorkflowError(\"Python packages networkx and",
"= mimetypes.guess_type(path) if outmime != \"text/html\": raise ValueError(\"Path to report output has to",
"to account for labels ymax = max(y for x, y in pos.values()) def",
"= list(map(encode_node, g.nodes)) idx = {node: i for i, node in enumerate(g.nodes)} links",
"job in dag.jobs: for f in itertools.chain(job.expanded_output, job.input): if is_flagged(f, \"report\") and f",
"elif self.is_text: return \"file-text\" else: return \"file\" @property def name(self): return os.path.basename(self.path) @property",
"in cat) # render HTML template = env.get_template(\"report.html\") with open(path, \"w\", encoding=\"utf-8\") as",
"directives.uri(self.arguments[0]) self.options['uri'] = data_uri_from_file(reference)[0] return result # Create (and register) new image:: and",
"pygraphviz must be \" \"installed to create reports.\", e) g = nx.DiGraph() g.add_nodes_from(sorted(job.rule.name",
"\"<EMAIL>\" __license__ = \"MIT\" import os import sys import mimetypes import base64 import",
"e: logger.warning(\"Failed to convert image to png with \" \"imagemagick convert: {}\".format(e.stderr)) else:",
"import Image, Figure from docutils.parsers.rst import directives from docutils.core import publish_file, publish_parts from",
"snakemake.exceptions import WorkflowError from snakemake.script import Snakemake from snakemake import __version__ class EmbeddedMixin(object):",
".. container:: :name: {name} {name}: {links} '''.format(name=name, links=links)) text = definitions + text",
"\"fx\": x, \"fy\": y} nodes = list(map(encode_node, g.nodes)) idx = {node: i for",
"nodes = list(map(encode_node, g.nodes)) idx = {node: i for i, node in enumerate(g.nodes)}",
"catresults in results.items(): for res in catresults: res.render(env, rst_links, results) # global description",
"jinja2 import Template, Environment, PackageLoader except ImportError as e: raise WorkflowError(\"Python package jinja2",
"snakemake=Snakemake, results=results), writer_name=\"html\")[\"body\"] # record time now = \"{} {}\".format(datetime.datetime.now().ctime(), time.tzname[0]) results_size =",
"template if stylesheet is not None: overrides[\"stylesheet_path\"] = stylesheet html = open(path, \"w\")",
"rec in sorted(records.values(), key=lambda rec: rec.rule)] # prepare end times timeline = [{\"rule\":",
"env, rst_links, results): if self.raw_caption is not None: try: from jinja2 import Template",
"}}: #results-{{ cat|replace(\" \", \"_\") }} {% for res in catresults %} ..",
"must be installed to create reports.\") job = self.job snakemake = Snakemake(job.input, job.output,",
"nx.DiGraph() g.add_nodes_from(sorted(job.rule.name for job in dag.jobs)) for job in dag.jobs: target = job.rule.name",
"and figure:: directives that use a base64 # data URI instead of pointing",
"\"image/jpeg\", \"image/png\", \"image/svg+xml\", \"application/pdf\"} return self.mime in web_safe @property def is_text(self): text =",
"x, \"fy\": y} nodes = list(map(encode_node, g.nodes)) idx = {node: i for i,",
"path): try: from jinja2 import Template, Environment, PackageLoader except ImportError as e: raise",
"from docutils.core import publish_file, publish_parts from snakemake.utils import format from snakemake.logging import logger",
"that use a base64 # data URI instead of pointing to a filename.",
"destination=html, writer_name=\"html\", settings_overrides=overrides) class RuleRecord: def __init__(self, job, job_rec): import yaml self.name =",
"was created with a too \" \"old Snakemake version.\".format(f)) for catresults in results.values():",
"g = nx.DiGraph() g.add_nodes_from(sorted(job.rule.name for job in dag.jobs)) for job in dag.jobs: target",
"%} .. _{{ cat }}: #results-{{ cat|replace(\" \", \"_\") }} {% for res",
"is not None: overrides[\"template\"] = template if stylesheet is not None: overrides[\"stylesheet_path\"] =",
"e: raise WorkflowError(\"Python package jinja2 must be installed to create reports.\") job =",
"snakemake.script import Snakemake from snakemake import __version__ class EmbeddedMixin(object): \"\"\" Replaces the URI",
"as e: raise WorkflowError(\"Python package jinja2 must be installed to create reports.\") job",
"\"fy\": y} nodes = list(map(encode_node, g.nodes)) idx = {node: i for i, node",
"output \" \"marked for report.\", e) @property def is_img(self): web_safe = {\"image/gif\", \"image/jpeg\",",
"for name, _files in sorted(files.items()): if not isinstance(_files, list): _files = [_files] links",
"results=results), writer_name=\"html\")[\"body\"] # record time now = \"{} {}\".format(datetime.datetime.now().ctime(), time.tzname[0]) results_size = sum(res.size",
"job.wildcards, job.threads, job.resources, job.log, job.dag.workflow.config, job.rule.name, None) try: caption = open(self.raw_caption).read() + rst_links",
"rec.conda_env = meta[\"conda_env\"] rec.singularity_img_url = meta[\"singularity_img_url\"] rec.output.append(f) except KeyError as e: print(e) logger.warning(\"Metadata",
"#stats {% for cat, catresults in results|dictsort %} .. _{{ cat }}: #results-{{",
"open(self.raw_caption).read() + rst_links caption = env.from_string(caption).render(snakemake=snakemake, results=results) self.caption = publish_parts(caption, writer_name=\"html\")[\"body\"] except Exception",
".. _ \"\"\") for cat, catresults in results.items(): for res in catresults: res.render(env,",
"pos.values()) + 100 # add offset to account for labels ymax = max(y",
"text = definitions + text + \"\\n\\n\" + \"\\n\\n\".join(attachments) + metadata overrides =",
"for res in catresults: res.render(env, rst_links, results) # global description text = \"\"",
"if outmime != \"text/html\": raise ValueError(\"Path to report output has to be an",
"as e: raise WorkflowError(\"Python package jinja2 must be installed to create reports.\") if",
"png = sp.check_output([\"convert\", \"-density\", \"100\", self.path, \"png:-\"], stderr=sp.PIPE) uri = data_uri(png, os.path.basename(self.path) +",
"= max(y for x, y in pos.values()) def encode_node(node): x, y = pos[node]",
"merged = True break if not merged: rules[rec.rule].append(rule) # rulegraph rulegraph, xmax, ymax",
"file with proper encoding and mimetype.\"\"\" data = base64.b64encode(data) uri = (\"data:{mime};charset={charset};filename={filename};base64,{data}\" \"\".format(filename=filename,",
"self.output.extend(job_rec.output) def __eq__(self, other): return (self.name == other.name and self.conda_env == other.conda_env and",
"as e: raise WorkflowError(\"Python packages networkx and pygraphviz must be \" \"installed to",
"_{{ res.name }}: #{{ res.id }} {% endfor %} {% endfor %} ..",
"for \" \"report: {}\".format(url)) def auto_report(dag, path): try: from jinja2 import Template, Environment,",
"results) # global description text = \"\" if dag.workflow.report_text: with open(dag.workflow.report_text) as f:",
"KeyError as e: print(e) logger.warning(\"Metadata for file {} was created with a too",
"\"text/tab-separated-values\"} return self.mime in text @property def icon(self): if self.is_img: return \"image\" elif",
"for f in job.expanded_output: meta = persistence.metadata(f) if not meta: logger.warning(\"Missing metadata for",
"sp import itertools from collections import namedtuple, defaultdict import requests from docutils.parsers.rst.directives.images import",
"\"\"\"Return size in Bytes.\"\"\" return os.path.getsize(self.path) def rulegraph_d3_spec(dag): try: import networkx as nx",
"is None: encoding = defaultenc with open(file, \"rb\") as f: return data_uri(f.read(), os.path.basename(file),",
"RuleRecord(job, rec) if rec.rule not in rules: rules[rec.rule].append(rule) else: merged = False for",
"import Template, Environment, PackageLoader except ImportError as e: raise WorkflowError(\"Python package jinja2 must",
"= records[(job_hash, rule)] rec.rule = rule rec.starttime = min(rec.starttime, meta[\"starttime\"]) rec.endtime = max(rec.endtime,",
"textwrap import datetime import io import uuid import json import time import shutil",
"sys import mimetypes import base64 import textwrap import datetime import io import uuid",
"i for i, node in enumerate(g.nodes)} links = [{\"target\": idx[u], \"source\": idx[v], \"value\":",
"in rules[rec.rule]: if rule == other: other.add(rec) merged = True break if not",
"report.\", e) @property def is_img(self): web_safe = {\"image/gif\", \"image/jpeg\", \"image/png\", \"image/svg+xml\", \"application/pdf\"} return",
"and f not in recorded_files: if not f.exists: raise WorkflowError(\"File {} marked for"
] |
[
"with open('argfile','r') as f: data=pickle.load(f) #data[0].u_rules=['stochastic_lb','Lb','stochastic_lb_double'] data[0].u_rules=['Lb-NN_refined_sto_double','Lb-NN_refined','Lb-NN_refined_sto'] data[0].s_rules=['GS','Random','all'] #data[0].u_rules=['Lb-NN_refined_sto'] #data[0].s_rules=['all'] data[0].loss_names=['lsl1nn_r'] #data[0].L1=[1e-2,1e-5,1e-9] #data[0].L1=[0.01,0.00001,0.000000001]",
"#data[0].L1=[1e-2,1e-5,1e-9] #data[0].L1=[0.01,0.00001,0.000000001] data[0].dataset_names=['log1p.E2006.train'] data[0].L1=[1e2] data[0].blockList=100 data[0].plot_names=['Lb-NN_refined_sto_double:GSMBCD2','Lb-NN_refined_sto:GSMBCD','Lb:GBCD'] data[0].stdout_freq=1 data[0].time_cost=300 #18 data[0].fixed_step=0.0001 data[0].stop_criterion='time' #data[0].L2=10 #data[0].u_rules=['Lb-NN_refined_sto','Lb-NN_refined_sto_double','Lb-NN_refined']",
"f: data=pickle.load(f) #data[0].u_rules=['stochastic_lb','Lb','stochastic_lb_double'] data[0].u_rules=['Lb-NN_refined_sto_double','Lb-NN_refined','Lb-NN_refined_sto'] data[0].s_rules=['GS','Random','all'] #data[0].u_rules=['Lb-NN_refined_sto'] #data[0].s_rules=['all'] data[0].loss_names=['lsl1nn_r'] #data[0].L1=[1e-2,1e-5,1e-9] #data[0].L1=[0.01,0.00001,0.000000001] data[0].dataset_names=['log1p.E2006.train'] data[0].L1=[1e2] data[0].blockList=100",
"#data[0].u_rules=['Lb-NN_refined_sto'] #data[0].s_rules=['all'] data[0].loss_names=['lsl1nn_r'] #data[0].L1=[1e-2,1e-5,1e-9] #data[0].L1=[0.01,0.00001,0.000000001] data[0].dataset_names=['log1p.E2006.train'] data[0].L1=[1e2] data[0].blockList=100 data[0].plot_names=['Lb-NN_refined_sto_double:GSMBCD2','Lb-NN_refined_sto:GSMBCD','Lb:GBCD'] data[0].stdout_freq=1 data[0].time_cost=300 #18 data[0].fixed_step=0.0001",
"<gh_stars>0 import pickle with open('argfile','r') as f: data=pickle.load(f) #data[0].u_rules=['stochastic_lb','Lb','stochastic_lb_double'] data[0].u_rules=['Lb-NN_refined_sto_double','Lb-NN_refined','Lb-NN_refined_sto'] data[0].s_rules=['GS','Random','all'] #data[0].u_rules=['Lb-NN_refined_sto'] #data[0].s_rules=['all']",
"as f: data=pickle.load(f) #data[0].u_rules=['stochastic_lb','Lb','stochastic_lb_double'] data[0].u_rules=['Lb-NN_refined_sto_double','Lb-NN_refined','Lb-NN_refined_sto'] data[0].s_rules=['GS','Random','all'] #data[0].u_rules=['Lb-NN_refined_sto'] #data[0].s_rules=['all'] data[0].loss_names=['lsl1nn_r'] #data[0].L1=[1e-2,1e-5,1e-9] #data[0].L1=[0.01,0.00001,0.000000001] data[0].dataset_names=['log1p.E2006.train'] data[0].L1=[1e2]",
"data[0].s_rules=['GS','Random','all'] #data[0].u_rules=['Lb-NN_refined_sto'] #data[0].s_rules=['all'] data[0].loss_names=['lsl1nn_r'] #data[0].L1=[1e-2,1e-5,1e-9] #data[0].L1=[0.01,0.00001,0.000000001] data[0].dataset_names=['log1p.E2006.train'] data[0].L1=[1e2] data[0].blockList=100 data[0].plot_names=['Lb-NN_refined_sto_double:GSMBCD2','Lb-NN_refined_sto:GSMBCD','Lb:GBCD'] data[0].stdout_freq=1 data[0].time_cost=300 #18",
"open('argfile','r') as f: data=pickle.load(f) #data[0].u_rules=['stochastic_lb','Lb','stochastic_lb_double'] data[0].u_rules=['Lb-NN_refined_sto_double','Lb-NN_refined','Lb-NN_refined_sto'] data[0].s_rules=['GS','Random','all'] #data[0].u_rules=['Lb-NN_refined_sto'] #data[0].s_rules=['all'] data[0].loss_names=['lsl1nn_r'] #data[0].L1=[1e-2,1e-5,1e-9] #data[0].L1=[0.01,0.00001,0.000000001] data[0].dataset_names=['log1p.E2006.train']",
"#data[0].u_rules=['stochastic_lb','Lb','stochastic_lb_double'] data[0].u_rules=['Lb-NN_refined_sto_double','Lb-NN_refined','Lb-NN_refined_sto'] data[0].s_rules=['GS','Random','all'] #data[0].u_rules=['Lb-NN_refined_sto'] #data[0].s_rules=['all'] data[0].loss_names=['lsl1nn_r'] #data[0].L1=[1e-2,1e-5,1e-9] #data[0].L1=[0.01,0.00001,0.000000001] data[0].dataset_names=['log1p.E2006.train'] data[0].L1=[1e2] data[0].blockList=100 data[0].plot_names=['Lb-NN_refined_sto_double:GSMBCD2','Lb-NN_refined_sto:GSMBCD','Lb:GBCD'] data[0].stdout_freq=1",
"data[0].u_rules=['Lb-NN_refined_sto_double','Lb-NN_refined','Lb-NN_refined_sto'] data[0].s_rules=['GS','Random','all'] #data[0].u_rules=['Lb-NN_refined_sto'] #data[0].s_rules=['all'] data[0].loss_names=['lsl1nn_r'] #data[0].L1=[1e-2,1e-5,1e-9] #data[0].L1=[0.01,0.00001,0.000000001] data[0].dataset_names=['log1p.E2006.train'] data[0].L1=[1e2] data[0].blockList=100 data[0].plot_names=['Lb-NN_refined_sto_double:GSMBCD2','Lb-NN_refined_sto:GSMBCD','Lb:GBCD'] data[0].stdout_freq=1 data[0].time_cost=300",
"data[0].loss_names=['lsl1nn_r'] #data[0].L1=[1e-2,1e-5,1e-9] #data[0].L1=[0.01,0.00001,0.000000001] data[0].dataset_names=['log1p.E2006.train'] data[0].L1=[1e2] data[0].blockList=100 data[0].plot_names=['Lb-NN_refined_sto_double:GSMBCD2','Lb-NN_refined_sto:GSMBCD','Lb:GBCD'] data[0].stdout_freq=1 data[0].time_cost=300 #18 data[0].fixed_step=0.0001 data[0].stop_criterion='time' #data[0].L2=10",
"#data[0].s_rules=['all'] data[0].loss_names=['lsl1nn_r'] #data[0].L1=[1e-2,1e-5,1e-9] #data[0].L1=[0.01,0.00001,0.000000001] data[0].dataset_names=['log1p.E2006.train'] data[0].L1=[1e2] data[0].blockList=100 data[0].plot_names=['Lb-NN_refined_sto_double:GSMBCD2','Lb-NN_refined_sto:GSMBCD','Lb:GBCD'] data[0].stdout_freq=1 data[0].time_cost=300 #18 data[0].fixed_step=0.0001 data[0].stop_criterion='time'",
"import pickle with open('argfile','r') as f: data=pickle.load(f) #data[0].u_rules=['stochastic_lb','Lb','stochastic_lb_double'] data[0].u_rules=['Lb-NN_refined_sto_double','Lb-NN_refined','Lb-NN_refined_sto'] data[0].s_rules=['GS','Random','all'] #data[0].u_rules=['Lb-NN_refined_sto'] #data[0].s_rules=['all'] data[0].loss_names=['lsl1nn_r']",
"data=pickle.load(f) #data[0].u_rules=['stochastic_lb','Lb','stochastic_lb_double'] data[0].u_rules=['Lb-NN_refined_sto_double','Lb-NN_refined','Lb-NN_refined_sto'] data[0].s_rules=['GS','Random','all'] #data[0].u_rules=['Lb-NN_refined_sto'] #data[0].s_rules=['all'] data[0].loss_names=['lsl1nn_r'] #data[0].L1=[1e-2,1e-5,1e-9] #data[0].L1=[0.01,0.00001,0.000000001] data[0].dataset_names=['log1p.E2006.train'] data[0].L1=[1e2] data[0].blockList=100 data[0].plot_names=['Lb-NN_refined_sto_double:GSMBCD2','Lb-NN_refined_sto:GSMBCD','Lb:GBCD']",
"pickle with open('argfile','r') as f: data=pickle.load(f) #data[0].u_rules=['stochastic_lb','Lb','stochastic_lb_double'] data[0].u_rules=['Lb-NN_refined_sto_double','Lb-NN_refined','Lb-NN_refined_sto'] data[0].s_rules=['GS','Random','all'] #data[0].u_rules=['Lb-NN_refined_sto'] #data[0].s_rules=['all'] data[0].loss_names=['lsl1nn_r'] #data[0].L1=[1e-2,1e-5,1e-9]"
] |
[
"validate(x, y): if np.shape(x) != np.shape(y): return False else: if x.any() == y.any():",
"#!/usr/bin/env python # coding=utf-8 import numpy as np def validate(x, y): if np.shape(x)",
"coding=utf-8 import numpy as np def validate(x, y): if np.shape(x) != np.shape(y): return",
"y): if np.shape(x) != np.shape(y): return False else: if x.any() == y.any(): print(\"----\")",
"np.shape(y): return False else: if x.any() == y.any(): print(\"----\") return True else: print(\"++++\")",
"False else: if x.any() == y.any(): print(\"----\") return True else: print(\"++++\") return False",
"# coding=utf-8 import numpy as np def validate(x, y): if np.shape(x) != np.shape(y):",
"<filename>utils.py #!/usr/bin/env python # coding=utf-8 import numpy as np def validate(x, y): if",
"as np def validate(x, y): if np.shape(x) != np.shape(y): return False else: if",
"!= np.shape(y): return False else: if x.any() == y.any(): print(\"----\") return True else:",
"numpy as np def validate(x, y): if np.shape(x) != np.shape(y): return False else:",
"python # coding=utf-8 import numpy as np def validate(x, y): if np.shape(x) !=",
"np def validate(x, y): if np.shape(x) != np.shape(y): return False else: if x.any()",
"np.shape(x) != np.shape(y): return False else: if x.any() == y.any(): print(\"----\") return True",
"import numpy as np def validate(x, y): if np.shape(x) != np.shape(y): return False",
"if np.shape(x) != np.shape(y): return False else: if x.any() == y.any(): print(\"----\") return",
"def validate(x, y): if np.shape(x) != np.shape(y): return False else: if x.any() ==",
"return False else: if x.any() == y.any(): print(\"----\") return True else: print(\"++++\") return"
] |
[
"request.files['image'] }) except: return 'Sorry, we\\'re probably over capacity. Please try again later.'",
"request.form['voted'].replace('-', ''), 'data': request.files['image'] }) except: return 'Sorry, we\\'re probably over capacity. Please",
"Strips HTML from a string. \"\"\" return re.compile(r'</?\\S([^=]*=(\\s*\"[^\"]*\"|\\s*\\'[^\\']*\\'|\\S*)|[^>])*?>', re.IGNORECASE).sub('', value) def strip_breaks(value): \"\"\"",
"President,</p><p class='voted' data-vote-type='%s'>%s.</p><p class='message'>%s</p><p class='signature-name'>Signed,<br/>%s from %s</p><p class='footnote'>What do <em>you</em> want President Obama",
") t = Tumblpy( app_key=app_config.TUMBLR_KEY, app_secret=os.environ['TUMBLR_APP_SECRET'], oauth_token=os.environ['TUMBLR_OAUTH_TOKEN'], oauth_token_secret=os.environ['TUMBLR_OAUTH_TOKEN_SECRET']) try: tumblr_post = t.post('post', blog_url=app_config.TUMBLR_URL,",
"\"\"\" return string.replace('-', ' ').replace(\"id \", \"I'd \").replace(\"didnt\", \"didn't\").replace('i ', 'I ') #",
"oauth_token_secret=os.environ['TUMBLR_OAUTH_TOKEN_SECRET']) try: tumblr_post = t.post('post', blog_url=app_config.TUMBLR_URL, params={ 'type': 'photo', 'caption': caption, 'tags': u\"%s\"",
"\"didn't\").replace('i ', 'I ') # Request is a global. Import it down here",
"''), 'data': request.files['image'] }) except: return 'Sorry, we\\'re probably over capacity. Please try",
"want President Obama to remember in his second term? Share your message at",
"flask import Flask, redirect from tumblpy import Tumblpy import app_config app = Flask(app_config.PROJECT_NAME)",
"breaks to <br/>. \"\"\" value = re.sub(r'\\r\\n|\\r|\\n', '\\n', value) return value.replace('\\n', '<br />')",
"' ').replace(\"id \", \"I'd \").replace(\"didnt\", \"didn't\").replace('i ', 'I ') # Request is a",
"return value.replace('\\n', '<br />') caption = u\"<p class='intro'>Dear Mr. President,</p><p class='voted' data-vote-type='%s'>%s.</p><p class='message'>%s</p><p",
"\"\"\" def clean(string): \"\"\" Formats a string all pretty. \"\"\" return string.replace('-', '",
"python import os import re from flask import Flask, redirect from tumblpy import",
"app = Flask(app_config.PROJECT_NAME) app.config['PROPAGATE_EXCEPTIONS'] = True @app.route('/dear-mr-president/', methods=['POST']) def _post_to_tumblr(): \"\"\" Handles the",
"data-vote-type='%s'>%s.</p><p class='message'>%s</p><p class='signature-name'>Signed,<br/>%s from %s</p><p class='footnote'>What do <em>you</em> want President Obama to remember",
"strip_html(request.form['signed_name']), strip_html(request.form['location']) ) t = Tumblpy( app_key=app_config.TUMBLR_KEY, app_secret=os.environ['TUMBLR_APP_SECRET'], oauth_token=os.environ['TUMBLR_OAUTH_TOKEN'], oauth_token_secret=os.environ['TUMBLR_OAUTH_TOKEN_SECRET']) try: tumblr_post =",
"% ( request.form['voted'], clean(request.form['voted']), strip_breaks(strip_html(request.form['message'])), strip_html(request.form['signed_name']), strip_html(request.form['location']) ) t = Tumblpy( app_key=app_config.TUMBLR_KEY, app_secret=os.environ['TUMBLR_APP_SECRET'],",
"\"\"\" value = re.sub(r'\\r\\n|\\r|\\n', '\\n', value) return value.replace('\\n', '<br />') caption = u\"<p",
"from flask import request def strip_html(value): \"\"\" Strips HTML from a string. \"\"\"",
"Formats a string all pretty. \"\"\" return string.replace('-', ' ').replace(\"id \", \"I'd \").replace(\"didnt\",",
"need it. from flask import request def strip_html(value): \"\"\" Strips HTML from a",
"def strip_html(value): \"\"\" Strips HTML from a string. \"\"\" return re.compile(r'</?\\S([^=]*=(\\s*\"[^\"]*\"|\\s*\\'[^\\']*\\'|\\S*)|[^>])*?>', re.IGNORECASE).sub('', value)",
"his second term? Share your message at <a href='http://inauguration2013.tumblr.com/'>NPR's Dear Mr. President</a>.</p>\" %",
"a global. Import it down here where we need it. from flask import",
"Dear Mr. President</a>.</p>\" % ( request.form['voted'], clean(request.form['voted']), strip_breaks(strip_html(request.form['message'])), strip_html(request.form['signed_name']), strip_html(request.form['location']) ) t =",
"President Obama to remember in his second term? Share your message at <a",
"is a global. Import it down here where we need it. from flask",
"\"\"\" return re.compile(r'</?\\S([^=]*=(\\s*\"[^\"]*\"|\\s*\\'[^\\']*\\'|\\S*)|[^>])*?>', re.IGNORECASE).sub('', value) def strip_breaks(value): \"\"\" Converts newlines, returns and other",
"to <br/>. \"\"\" value = re.sub(r'\\r\\n|\\r|\\n', '\\n', value) return value.replace('\\n', '<br />') caption",
"and other breaks to <br/>. \"\"\" value = re.sub(r'\\r\\n|\\r|\\n', '\\n', value) return value.replace('\\n',",
"Flask, redirect from tumblpy import Tumblpy import app_config app = Flask(app_config.PROJECT_NAME) app.config['PROPAGATE_EXCEPTIONS'] =",
"except: return 'Sorry, we\\'re probably over capacity. Please try again later.' return redirect(u\"http://%s/%s#posts\"",
"to Tumblr. \"\"\" def clean(string): \"\"\" Formats a string all pretty. \"\"\" return",
"def _post_to_tumblr(): \"\"\" Handles the POST to Tumblr. \"\"\" def clean(string): \"\"\" Formats",
"_post_to_tumblr(): \"\"\" Handles the POST to Tumblr. \"\"\" def clean(string): \"\"\" Formats a",
"class='footnote'>What do <em>you</em> want President Obama to remember in his second term? Share",
"def strip_breaks(value): \"\"\" Converts newlines, returns and other breaks to <br/>. \"\"\" value",
"over capacity. Please try again later.' return redirect(u\"http://%s/%s#posts\" % (app_config.TUMBLR_URL, tumblr_post['id']), code=301) if",
"re.IGNORECASE).sub('', value) def strip_breaks(value): \"\"\" Converts newlines, returns and other breaks to <br/>.",
"caption, 'tags': u\"%s\" % request.form['voted'].replace('-', ''), 'data': request.files['image'] }) except: return 'Sorry, we\\'re",
"app_key=app_config.TUMBLR_KEY, app_secret=os.environ['TUMBLR_APP_SECRET'], oauth_token=os.environ['TUMBLR_OAUTH_TOKEN'], oauth_token_secret=os.environ['TUMBLR_OAUTH_TOKEN_SECRET']) try: tumblr_post = t.post('post', blog_url=app_config.TUMBLR_URL, params={ 'type': 'photo', 'caption':",
"', 'I ') # Request is a global. Import it down here where",
"methods=['POST']) def _post_to_tumblr(): \"\"\" Handles the POST to Tumblr. \"\"\" def clean(string): \"\"\"",
"'Sorry, we\\'re probably over capacity. Please try again later.' return redirect(u\"http://%s/%s#posts\" % (app_config.TUMBLR_URL,",
"class='signature-name'>Signed,<br/>%s from %s</p><p class='footnote'>What do <em>you</em> want President Obama to remember in his",
"flask import request def strip_html(value): \"\"\" Strips HTML from a string. \"\"\" return",
"clean(request.form['voted']), strip_breaks(strip_html(request.form['message'])), strip_html(request.form['signed_name']), strip_html(request.form['location']) ) t = Tumblpy( app_key=app_config.TUMBLR_KEY, app_secret=os.environ['TUMBLR_APP_SECRET'], oauth_token=os.environ['TUMBLR_OAUTH_TOKEN'], oauth_token_secret=os.environ['TUMBLR_OAUTH_TOKEN_SECRET']) try:",
"import Flask, redirect from tumblpy import Tumblpy import app_config app = Flask(app_config.PROJECT_NAME) app.config['PROPAGATE_EXCEPTIONS']",
"= re.sub(r'\\r\\n|\\r|\\n', '\\n', value) return value.replace('\\n', '<br />') caption = u\"<p class='intro'>Dear Mr.",
"#!/usr/bin/env python import os import re from flask import Flask, redirect from tumblpy",
"value) return value.replace('\\n', '<br />') caption = u\"<p class='intro'>Dear Mr. President,</p><p class='voted' data-vote-type='%s'>%s.</p><p",
"\", \"I'd \").replace(\"didnt\", \"didn't\").replace('i ', 'I ') # Request is a global. Import",
"re.sub(r'\\r\\n|\\r|\\n', '\\n', value) return value.replace('\\n', '<br />') caption = u\"<p class='intro'>Dear Mr. President,</p><p",
"\"\"\" Handles the POST to Tumblr. \"\"\" def clean(string): \"\"\" Formats a string",
"it. from flask import request def strip_html(value): \"\"\" Strips HTML from a string.",
"').replace(\"id \", \"I'd \").replace(\"didnt\", \"didn't\").replace('i ', 'I ') # Request is a global.",
"'\\n', value) return value.replace('\\n', '<br />') caption = u\"<p class='intro'>Dear Mr. President,</p><p class='voted'",
"Import it down here where we need it. from flask import request def",
"do <em>you</em> want President Obama to remember in his second term? Share your",
"try: tumblr_post = t.post('post', blog_url=app_config.TUMBLR_URL, params={ 'type': 'photo', 'caption': caption, 'tags': u\"%s\" %",
"Converts newlines, returns and other breaks to <br/>. \"\"\" value = re.sub(r'\\r\\n|\\r|\\n', '\\n',",
"def clean(string): \"\"\" Formats a string all pretty. \"\"\" return string.replace('-', ' ').replace(\"id",
"return string.replace('-', ' ').replace(\"id \", \"I'd \").replace(\"didnt\", \"didn't\").replace('i ', 'I ') # Request",
"= t.post('post', blog_url=app_config.TUMBLR_URL, params={ 'type': 'photo', 'caption': caption, 'tags': u\"%s\" % request.form['voted'].replace('-', ''),",
"from flask import Flask, redirect from tumblpy import Tumblpy import app_config app =",
"HTML from a string. \"\"\" return re.compile(r'</?\\S([^=]*=(\\s*\"[^\"]*\"|\\s*\\'[^\\']*\\'|\\S*)|[^>])*?>', re.IGNORECASE).sub('', value) def strip_breaks(value): \"\"\" Converts",
"a string all pretty. \"\"\" return string.replace('-', ' ').replace(\"id \", \"I'd \").replace(\"didnt\", \"didn't\").replace('i",
"string all pretty. \"\"\" return string.replace('-', ' ').replace(\"id \", \"I'd \").replace(\"didnt\", \"didn't\").replace('i ',",
"value = re.sub(r'\\r\\n|\\r|\\n', '\\n', value) return value.replace('\\n', '<br />') caption = u\"<p class='intro'>Dear",
"'photo', 'caption': caption, 'tags': u\"%s\" % request.form['voted'].replace('-', ''), 'data': request.files['image'] }) except: return",
"string. \"\"\" return re.compile(r'</?\\S([^=]*=(\\s*\"[^\"]*\"|\\s*\\'[^\\']*\\'|\\S*)|[^>])*?>', re.IGNORECASE).sub('', value) def strip_breaks(value): \"\"\" Converts newlines, returns and",
"'I ') # Request is a global. Import it down here where we",
"newlines, returns and other breaks to <br/>. \"\"\" value = re.sub(r'\\r\\n|\\r|\\n', '\\n', value)",
"in his second term? Share your message at <a href='http://inauguration2013.tumblr.com/'>NPR's Dear Mr. President</a>.</p>\"",
"here where we need it. from flask import request def strip_html(value): \"\"\" Strips",
"remember in his second term? Share your message at <a href='http://inauguration2013.tumblr.com/'>NPR's Dear Mr.",
"return re.compile(r'</?\\S([^=]*=(\\s*\"[^\"]*\"|\\s*\\'[^\\']*\\'|\\S*)|[^>])*?>', re.IGNORECASE).sub('', value) def strip_breaks(value): \"\"\" Converts newlines, returns and other breaks",
"<a href='http://inauguration2013.tumblr.com/'>NPR's Dear Mr. President</a>.</p>\" % ( request.form['voted'], clean(request.form['voted']), strip_breaks(strip_html(request.form['message'])), strip_html(request.form['signed_name']), strip_html(request.form['location']) )",
"the POST to Tumblr. \"\"\" def clean(string): \"\"\" Formats a string all pretty.",
"\").replace(\"didnt\", \"didn't\").replace('i ', 'I ') # Request is a global. Import it down",
"Tumblpy import app_config app = Flask(app_config.PROJECT_NAME) app.config['PROPAGATE_EXCEPTIONS'] = True @app.route('/dear-mr-president/', methods=['POST']) def _post_to_tumblr():",
"to remember in his second term? Share your message at <a href='http://inauguration2013.tumblr.com/'>NPR's Dear",
"import request def strip_html(value): \"\"\" Strips HTML from a string. \"\"\" return re.compile(r'</?\\S([^=]*=(\\s*\"[^\"]*\"|\\s*\\'[^\\']*\\'|\\S*)|[^>])*?>',",
"request def strip_html(value): \"\"\" Strips HTML from a string. \"\"\" return re.compile(r'</?\\S([^=]*=(\\s*\"[^\"]*\"|\\s*\\'[^\\']*\\'|\\S*)|[^>])*?>', re.IGNORECASE).sub('',",
"app.config['PROPAGATE_EXCEPTIONS'] = True @app.route('/dear-mr-president/', methods=['POST']) def _post_to_tumblr(): \"\"\" Handles the POST to Tumblr.",
"( request.form['voted'], clean(request.form['voted']), strip_breaks(strip_html(request.form['message'])), strip_html(request.form['signed_name']), strip_html(request.form['location']) ) t = Tumblpy( app_key=app_config.TUMBLR_KEY, app_secret=os.environ['TUMBLR_APP_SECRET'], oauth_token=os.environ['TUMBLR_OAUTH_TOKEN'],",
"= Tumblpy( app_key=app_config.TUMBLR_KEY, app_secret=os.environ['TUMBLR_APP_SECRET'], oauth_token=os.environ['TUMBLR_OAUTH_TOKEN'], oauth_token_secret=os.environ['TUMBLR_OAUTH_TOKEN_SECRET']) try: tumblr_post = t.post('post', blog_url=app_config.TUMBLR_URL, params={ 'type':",
"') # Request is a global. Import it down here where we need",
"class='voted' data-vote-type='%s'>%s.</p><p class='message'>%s</p><p class='signature-name'>Signed,<br/>%s from %s</p><p class='footnote'>What do <em>you</em> want President Obama to",
"Mr. President</a>.</p>\" % ( request.form['voted'], clean(request.form['voted']), strip_breaks(strip_html(request.form['message'])), strip_html(request.form['signed_name']), strip_html(request.form['location']) ) t = Tumblpy(",
"tumblpy import Tumblpy import app_config app = Flask(app_config.PROJECT_NAME) app.config['PROPAGATE_EXCEPTIONS'] = True @app.route('/dear-mr-president/', methods=['POST'])",
"re from flask import Flask, redirect from tumblpy import Tumblpy import app_config app",
"app_secret=os.environ['TUMBLR_APP_SECRET'], oauth_token=os.environ['TUMBLR_OAUTH_TOKEN'], oauth_token_secret=os.environ['TUMBLR_OAUTH_TOKEN_SECRET']) try: tumblr_post = t.post('post', blog_url=app_config.TUMBLR_URL, params={ 'type': 'photo', 'caption': caption,",
"import re from flask import Flask, redirect from tumblpy import Tumblpy import app_config",
"Tumblr. \"\"\" def clean(string): \"\"\" Formats a string all pretty. \"\"\" return string.replace('-',",
"your message at <a href='http://inauguration2013.tumblr.com/'>NPR's Dear Mr. President</a>.</p>\" % ( request.form['voted'], clean(request.form['voted']), strip_breaks(strip_html(request.form['message'])),",
"'type': 'photo', 'caption': caption, 'tags': u\"%s\" % request.form['voted'].replace('-', ''), 'data': request.files['image'] }) except:",
"a string. \"\"\" return re.compile(r'</?\\S([^=]*=(\\s*\"[^\"]*\"|\\s*\\'[^\\']*\\'|\\S*)|[^>])*?>', re.IGNORECASE).sub('', value) def strip_breaks(value): \"\"\" Converts newlines, returns",
"import os import re from flask import Flask, redirect from tumblpy import Tumblpy",
"'tags': u\"%s\" % request.form['voted'].replace('-', ''), 'data': request.files['image'] }) except: return 'Sorry, we\\'re probably",
"term? Share your message at <a href='http://inauguration2013.tumblr.com/'>NPR's Dear Mr. President</a>.</p>\" % ( request.form['voted'],",
"app_config app = Flask(app_config.PROJECT_NAME) app.config['PROPAGATE_EXCEPTIONS'] = True @app.route('/dear-mr-president/', methods=['POST']) def _post_to_tumblr(): \"\"\" Handles",
"u\"<p class='intro'>Dear Mr. President,</p><p class='voted' data-vote-type='%s'>%s.</p><p class='message'>%s</p><p class='signature-name'>Signed,<br/>%s from %s</p><p class='footnote'>What do <em>you</em>",
"return redirect(u\"http://%s/%s#posts\" % (app_config.TUMBLR_URL, tumblr_post['id']), code=301) if __name__ == '__main__': app.run(host='0.0.0.0', port=8000, debug=app_config.DEBUG)",
"%s</p><p class='footnote'>What do <em>you</em> want President Obama to remember in his second term?",
"try again later.' return redirect(u\"http://%s/%s#posts\" % (app_config.TUMBLR_URL, tumblr_post['id']), code=301) if __name__ == '__main__':",
"\"\"\" Strips HTML from a string. \"\"\" return re.compile(r'</?\\S([^=]*=(\\s*\"[^\"]*\"|\\s*\\'[^\\']*\\'|\\S*)|[^>])*?>', re.IGNORECASE).sub('', value) def strip_breaks(value):",
"\"I'd \").replace(\"didnt\", \"didn't\").replace('i ', 'I ') # Request is a global. Import it",
"we need it. from flask import request def strip_html(value): \"\"\" Strips HTML from",
"/>') caption = u\"<p class='intro'>Dear Mr. President,</p><p class='voted' data-vote-type='%s'>%s.</p><p class='message'>%s</p><p class='signature-name'>Signed,<br/>%s from %s</p><p",
"pretty. \"\"\" return string.replace('-', ' ').replace(\"id \", \"I'd \").replace(\"didnt\", \"didn't\").replace('i ', 'I ')",
"'caption': caption, 'tags': u\"%s\" % request.form['voted'].replace('-', ''), 'data': request.files['image'] }) except: return 'Sorry,",
"blog_url=app_config.TUMBLR_URL, params={ 'type': 'photo', 'caption': caption, 'tags': u\"%s\" % request.form['voted'].replace('-', ''), 'data': request.files['image']",
"t = Tumblpy( app_key=app_config.TUMBLR_KEY, app_secret=os.environ['TUMBLR_APP_SECRET'], oauth_token=os.environ['TUMBLR_OAUTH_TOKEN'], oauth_token_secret=os.environ['TUMBLR_OAUTH_TOKEN_SECRET']) try: tumblr_post = t.post('post', blog_url=app_config.TUMBLR_URL, params={",
"redirect from tumblpy import Tumblpy import app_config app = Flask(app_config.PROJECT_NAME) app.config['PROPAGATE_EXCEPTIONS'] = True",
"t.post('post', blog_url=app_config.TUMBLR_URL, params={ 'type': 'photo', 'caption': caption, 'tags': u\"%s\" % request.form['voted'].replace('-', ''), 'data':",
"import app_config app = Flask(app_config.PROJECT_NAME) app.config['PROPAGATE_EXCEPTIONS'] = True @app.route('/dear-mr-president/', methods=['POST']) def _post_to_tumblr(): \"\"\"",
"other breaks to <br/>. \"\"\" value = re.sub(r'\\r\\n|\\r|\\n', '\\n', value) return value.replace('\\n', '<br",
"all pretty. \"\"\" return string.replace('-', ' ').replace(\"id \", \"I'd \").replace(\"didnt\", \"didn't\").replace('i ', 'I",
"value.replace('\\n', '<br />') caption = u\"<p class='intro'>Dear Mr. President,</p><p class='voted' data-vote-type='%s'>%s.</p><p class='message'>%s</p><p class='signature-name'>Signed,<br/>%s",
"class='intro'>Dear Mr. President,</p><p class='voted' data-vote-type='%s'>%s.</p><p class='message'>%s</p><p class='signature-name'>Signed,<br/>%s from %s</p><p class='footnote'>What do <em>you</em> want",
"from %s</p><p class='footnote'>What do <em>you</em> want President Obama to remember in his second",
"True @app.route('/dear-mr-president/', methods=['POST']) def _post_to_tumblr(): \"\"\" Handles the POST to Tumblr. \"\"\" def",
"down here where we need it. from flask import request def strip_html(value): \"\"\"",
"later.' return redirect(u\"http://%s/%s#posts\" % (app_config.TUMBLR_URL, tumblr_post['id']), code=301) if __name__ == '__main__': app.run(host='0.0.0.0', port=8000,",
"= True @app.route('/dear-mr-president/', methods=['POST']) def _post_to_tumblr(): \"\"\" Handles the POST to Tumblr. \"\"\"",
"probably over capacity. Please try again later.' return redirect(u\"http://%s/%s#posts\" % (app_config.TUMBLR_URL, tumblr_post['id']), code=301)",
"request.form['voted'], clean(request.form['voted']), strip_breaks(strip_html(request.form['message'])), strip_html(request.form['signed_name']), strip_html(request.form['location']) ) t = Tumblpy( app_key=app_config.TUMBLR_KEY, app_secret=os.environ['TUMBLR_APP_SECRET'], oauth_token=os.environ['TUMBLR_OAUTH_TOKEN'], oauth_token_secret=os.environ['TUMBLR_OAUTH_TOKEN_SECRET'])",
"}) except: return 'Sorry, we\\'re probably over capacity. Please try again later.' return",
"href='http://inauguration2013.tumblr.com/'>NPR's Dear Mr. President</a>.</p>\" % ( request.form['voted'], clean(request.form['voted']), strip_breaks(strip_html(request.form['message'])), strip_html(request.form['signed_name']), strip_html(request.form['location']) ) t",
"at <a href='http://inauguration2013.tumblr.com/'>NPR's Dear Mr. President</a>.</p>\" % ( request.form['voted'], clean(request.form['voted']), strip_breaks(strip_html(request.form['message'])), strip_html(request.form['signed_name']), strip_html(request.form['location'])",
"Please try again later.' return redirect(u\"http://%s/%s#posts\" % (app_config.TUMBLR_URL, tumblr_post['id']), code=301) if __name__ ==",
"= u\"<p class='intro'>Dear Mr. President,</p><p class='voted' data-vote-type='%s'>%s.</p><p class='message'>%s</p><p class='signature-name'>Signed,<br/>%s from %s</p><p class='footnote'>What do",
"strip_breaks(value): \"\"\" Converts newlines, returns and other breaks to <br/>. \"\"\" value =",
"strip_html(value): \"\"\" Strips HTML from a string. \"\"\" return re.compile(r'</?\\S([^=]*=(\\s*\"[^\"]*\"|\\s*\\'[^\\']*\\'|\\S*)|[^>])*?>', re.IGNORECASE).sub('', value) def",
"from a string. \"\"\" return re.compile(r'</?\\S([^=]*=(\\s*\"[^\"]*\"|\\s*\\'[^\\']*\\'|\\S*)|[^>])*?>', re.IGNORECASE).sub('', value) def strip_breaks(value): \"\"\" Converts newlines,",
"# Request is a global. Import it down here where we need it.",
"again later.' return redirect(u\"http://%s/%s#posts\" % (app_config.TUMBLR_URL, tumblr_post['id']), code=301) if __name__ == '__main__': app.run(host='0.0.0.0',",
"string.replace('-', ' ').replace(\"id \", \"I'd \").replace(\"didnt\", \"didn't\").replace('i ', 'I ') # Request is",
"Handles the POST to Tumblr. \"\"\" def clean(string): \"\"\" Formats a string all",
"'<br />') caption = u\"<p class='intro'>Dear Mr. President,</p><p class='voted' data-vote-type='%s'>%s.</p><p class='message'>%s</p><p class='signature-name'>Signed,<br/>%s from",
"from tumblpy import Tumblpy import app_config app = Flask(app_config.PROJECT_NAME) app.config['PROPAGATE_EXCEPTIONS'] = True @app.route('/dear-mr-president/',",
"\"\"\" Converts newlines, returns and other breaks to <br/>. \"\"\" value = re.sub(r'\\r\\n|\\r|\\n',",
"\"\"\" Formats a string all pretty. \"\"\" return string.replace('-', ' ').replace(\"id \", \"I'd",
"we\\'re probably over capacity. Please try again later.' return redirect(u\"http://%s/%s#posts\" % (app_config.TUMBLR_URL, tumblr_post['id']),",
"Tumblpy( app_key=app_config.TUMBLR_KEY, app_secret=os.environ['TUMBLR_APP_SECRET'], oauth_token=os.environ['TUMBLR_OAUTH_TOKEN'], oauth_token_secret=os.environ['TUMBLR_OAUTH_TOKEN_SECRET']) try: tumblr_post = t.post('post', blog_url=app_config.TUMBLR_URL, params={ 'type': 'photo',",
"strip_breaks(strip_html(request.form['message'])), strip_html(request.form['signed_name']), strip_html(request.form['location']) ) t = Tumblpy( app_key=app_config.TUMBLR_KEY, app_secret=os.environ['TUMBLR_APP_SECRET'], oauth_token=os.environ['TUMBLR_OAUTH_TOKEN'], oauth_token_secret=os.environ['TUMBLR_OAUTH_TOKEN_SECRET']) try: tumblr_post",
"President</a>.</p>\" % ( request.form['voted'], clean(request.form['voted']), strip_breaks(strip_html(request.form['message'])), strip_html(request.form['signed_name']), strip_html(request.form['location']) ) t = Tumblpy( app_key=app_config.TUMBLR_KEY,",
"global. Import it down here where we need it. from flask import request",
"os import re from flask import Flask, redirect from tumblpy import Tumblpy import",
"caption = u\"<p class='intro'>Dear Mr. President,</p><p class='voted' data-vote-type='%s'>%s.</p><p class='message'>%s</p><p class='signature-name'>Signed,<br/>%s from %s</p><p class='footnote'>What",
"@app.route('/dear-mr-president/', methods=['POST']) def _post_to_tumblr(): \"\"\" Handles the POST to Tumblr. \"\"\" def clean(string):",
"it down here where we need it. from flask import request def strip_html(value):",
"return 'Sorry, we\\'re probably over capacity. Please try again later.' return redirect(u\"http://%s/%s#posts\" %",
"clean(string): \"\"\" Formats a string all pretty. \"\"\" return string.replace('-', ' ').replace(\"id \",",
"capacity. Please try again later.' return redirect(u\"http://%s/%s#posts\" % (app_config.TUMBLR_URL, tumblr_post['id']), code=301) if __name__",
"where we need it. from flask import request def strip_html(value): \"\"\" Strips HTML",
"tumblr_post = t.post('post', blog_url=app_config.TUMBLR_URL, params={ 'type': 'photo', 'caption': caption, 'tags': u\"%s\" % request.form['voted'].replace('-',",
"returns and other breaks to <br/>. \"\"\" value = re.sub(r'\\r\\n|\\r|\\n', '\\n', value) return",
"Mr. President,</p><p class='voted' data-vote-type='%s'>%s.</p><p class='message'>%s</p><p class='signature-name'>Signed,<br/>%s from %s</p><p class='footnote'>What do <em>you</em> want President",
"<em>you</em> want President Obama to remember in his second term? Share your message",
"Flask(app_config.PROJECT_NAME) app.config['PROPAGATE_EXCEPTIONS'] = True @app.route('/dear-mr-president/', methods=['POST']) def _post_to_tumblr(): \"\"\" Handles the POST to",
"params={ 'type': 'photo', 'caption': caption, 'tags': u\"%s\" % request.form['voted'].replace('-', ''), 'data': request.files['image'] })",
"import Tumblpy import app_config app = Flask(app_config.PROJECT_NAME) app.config['PROPAGATE_EXCEPTIONS'] = True @app.route('/dear-mr-president/', methods=['POST']) def",
"Obama to remember in his second term? Share your message at <a href='http://inauguration2013.tumblr.com/'>NPR's",
"strip_html(request.form['location']) ) t = Tumblpy( app_key=app_config.TUMBLR_KEY, app_secret=os.environ['TUMBLR_APP_SECRET'], oauth_token=os.environ['TUMBLR_OAUTH_TOKEN'], oauth_token_secret=os.environ['TUMBLR_OAUTH_TOKEN_SECRET']) try: tumblr_post = t.post('post',",
"% request.form['voted'].replace('-', ''), 'data': request.files['image'] }) except: return 'Sorry, we\\'re probably over capacity.",
"Share your message at <a href='http://inauguration2013.tumblr.com/'>NPR's Dear Mr. President</a>.</p>\" % ( request.form['voted'], clean(request.form['voted']),",
"'data': request.files['image'] }) except: return 'Sorry, we\\'re probably over capacity. Please try again",
"u\"%s\" % request.form['voted'].replace('-', ''), 'data': request.files['image'] }) except: return 'Sorry, we\\'re probably over",
"re.compile(r'</?\\S([^=]*=(\\s*\"[^\"]*\"|\\s*\\'[^\\']*\\'|\\S*)|[^>])*?>', re.IGNORECASE).sub('', value) def strip_breaks(value): \"\"\" Converts newlines, returns and other breaks to",
"POST to Tumblr. \"\"\" def clean(string): \"\"\" Formats a string all pretty. \"\"\"",
"Request is a global. Import it down here where we need it. from",
"second term? Share your message at <a href='http://inauguration2013.tumblr.com/'>NPR's Dear Mr. President</a>.</p>\" % (",
"oauth_token=os.environ['TUMBLR_OAUTH_TOKEN'], oauth_token_secret=os.environ['TUMBLR_OAUTH_TOKEN_SECRET']) try: tumblr_post = t.post('post', blog_url=app_config.TUMBLR_URL, params={ 'type': 'photo', 'caption': caption, 'tags':",
"value) def strip_breaks(value): \"\"\" Converts newlines, returns and other breaks to <br/>. \"\"\"",
"<br/>. \"\"\" value = re.sub(r'\\r\\n|\\r|\\n', '\\n', value) return value.replace('\\n', '<br />') caption =",
"= Flask(app_config.PROJECT_NAME) app.config['PROPAGATE_EXCEPTIONS'] = True @app.route('/dear-mr-president/', methods=['POST']) def _post_to_tumblr(): \"\"\" Handles the POST",
"class='message'>%s</p><p class='signature-name'>Signed,<br/>%s from %s</p><p class='footnote'>What do <em>you</em> want President Obama to remember in",
"message at <a href='http://inauguration2013.tumblr.com/'>NPR's Dear Mr. President</a>.</p>\" % ( request.form['voted'], clean(request.form['voted']), strip_breaks(strip_html(request.form['message'])), strip_html(request.form['signed_name']),"
] |
[
"Aran-Fey https://chat.stackoverflow.com/transcript/message/47258396#47258396 def circle_octant(r): r2 = r ** 2 y = 0 while",
"\"white\") draw = ImageDraw.Draw(img) if r <= 0.5: logical_circle((0, 0), r, outline=\"black\") else:",
"int(x), y-1 else: yield int(x)+1, y x = int(x) yield x, y if",
"SIZE screen_r = r * SIZE screen_circle((screen_x, screen_y), screen_r, **style) img = Image.new(\"RGB\",",
"tiles: logical_circle((x,y), r, outline=\"black\") return img def frange(start, stop, steps): for i in",
"* SIZE screen_y = (logical_y + 0.5) * SIZE screen_r = r *",
"0.5: x += 1 else: # If we moved left, find out which",
"range(-r, r+1): yield dx+x, dy+y from PIL import Image, ImageDraw SIZE = 500",
"we moved left, find out which adjacent pixel # the circle moved through",
"2 y = 0 while y <= r: x = sqrt(r2 - y**2)",
"= int(x) yield x, y if x <= r//2: break y += 1",
"x, y if x <= r//2: break y += 1 #Courtesy of Aran-Fey",
"y, r): for h, v in circle_octant(r): yield x+h, y+v yield x-h, y+v",
"(y-0.5)**2) if x2 < int(x)+0.5: yield int(x), y-1 else: yield int(x)+1, y x",
"x-v, y+h yield x+v, y-h yield x-v, y-h def brush(g, r): \"\"\" draws",
"2)) for x,y in tiles: logical_circle((x,y), r, outline=\"black\") return img def frange(start, stop,",
"# left or the one above (or neither?). # To do this, we",
"x,y in g: for dx in range(-r, r+1): for dy in range(-r, r+1):",
"yield int(x)+1, y x = int(x) yield x, y if x <= r//2:",
"using a square \"brush\" of side length 1+2*r \"\"\" for x,y in g:",
"import animation max_radius = 8 frames_per_radius = 64 frames = [] for f",
"out which adjacent pixel # the circle moved through - either the one",
"= center draw.chord((x-r,y-r, x+r,y+r), 0, 359, **style) def logical_circle(center, r, **style): logical_x, logical_y",
"outline=\"black\") return img def frange(start, stop, steps): for i in range(steps+1): f =",
"in g: for dx in range(-r, r+1): for dy in range(-r, r+1): yield",
"frange(start, stop, steps): for i in range(steps+1): f = i / float(steps) yield",
"r <= 0.5: logical_circle((0, 0), r, outline=\"black\") else: tiles = set(brush(circle_coords(0,0,r), 2)) for",
"#Courtesy of Aran-Fey https://chat.stackoverflow.com/transcript/message/47258396#47258396 def circle_octant(r): r2 = r ** 2 y =",
"either the one to the # left or the one above (or neither?).",
"in the # center between the current pixel and the one below. x2",
"int(x)+0.5: yield int(x), y-1 else: yield int(x)+1, y x = int(x) yield x,",
"for dy in range(-r, r+1): yield dx+x, dy+y from PIL import Image, ImageDraw",
"side length 1+2*r \"\"\" for x,y in g: for dx in range(-r, r+1):",
"+ 0.5) * SIZE screen_r = r * SIZE screen_circle((screen_x, screen_y), screen_r, **style)",
"y-h def brush(g, r): \"\"\" draws over an iterable of coordinates using a",
"in range(-r, r+1): for dy in range(-r, r+1): yield dx+x, dy+y from PIL",
"else: yield int(x)+1, y x = int(x) yield x, y if x <=",
"screen_r, **style) img = Image.new(\"RGB\", (SIZE, SIZE), \"white\") draw = ImageDraw.Draw(img) if r",
"dx+x, dy+y from PIL import Image, ImageDraw SIZE = 500 def render_echo_chamber(r): def",
"0.5) * SIZE screen_r = r * SIZE screen_circle((screen_x, screen_y), screen_r, **style) img",
"= 8 frames_per_radius = 64 frames = [] for f in frange(0, max_radius,",
"of Aran-Fey https://chat.stackoverflow.com/transcript/message/47258396#47258396 def circle_coords(x, y, r): for h, v in circle_octant(r): yield",
"Image, ImageDraw SIZE = 500 def render_echo_chamber(r): def screen_circle(center, r, **style): x,y =",
"x+v, y-h yield x-v, y-h def brush(g, r): \"\"\" draws over an iterable",
"**style) img = Image.new(\"RGB\", (SIZE, SIZE), \"white\") draw = ImageDraw.Draw(img) if r <=",
"for i in range(steps+1): f = i / float(steps) yield start+(f * (stop-start))",
"of Aran-Fey https://chat.stackoverflow.com/transcript/message/47258396#47258396 def circle_octant(r): r2 = r ** 2 y = 0",
"y = 0 while y <= r: x = sqrt(r2 - y**2) if",
"logical_circle((x,y), r, outline=\"black\") return img def frange(start, stop, steps): for i in range(steps+1):",
"tiles = set(brush(circle_coords(0,0,r), 2)) for x,y in tiles: logical_circle((x,y), r, outline=\"black\") return img",
"current pixel and the one below. x2 = sqrt(r2 - (y-0.5)**2) if x2",
"SIZE screen_circle((screen_x, screen_y), screen_r, **style) img = Image.new(\"RGB\", (SIZE, SIZE), \"white\") draw =",
"if x <= r//2: break y += 1 #Courtesy of Aran-Fey https://chat.stackoverflow.com/transcript/message/47258396#47258396 def",
"= r * SIZE screen_circle((screen_x, screen_y), screen_r, **style) img = Image.new(\"RGB\", (SIZE, SIZE),",
"frames = [] for f in frange(0, max_radius, frames_per_radius*max_radius): print(f) frames.append(render_echo_chamber(f)) animation.make_gif(frames, delay=8,",
"8 frames_per_radius = 64 frames = [] for f in frange(0, max_radius, frames_per_radius*max_radius):",
"moved left, find out which adjacent pixel # the circle moved through -",
"else: # If we moved left, find out which adjacent pixel # the",
"x = sqrt(r2 - y**2) if x-int(x) >= 0.5: x += 1 else:",
"def brush(g, r): \"\"\" draws over an iterable of coordinates using a square",
"y-h yield x-v, y-h def brush(g, r): \"\"\" draws over an iterable of",
"v in circle_octant(r): yield x+h, y+v yield x-h, y+v yield x+h, y-v yield",
"the one above (or neither?). # To do this, we calculate the x",
"y+h yield x+v, y-h yield x-v, y-h def brush(g, r): \"\"\" draws over",
"and the one below. x2 = sqrt(r2 - (y-0.5)**2) if x2 < int(x)+0.5:",
"yield x-v, y-h def brush(g, r): \"\"\" draws over an iterable of coordinates",
"sqrt(r2 - y**2) if x-int(x) >= 0.5: x += 1 else: # If",
"\"\"\" draws over an iterable of coordinates using a square \"brush\" of side",
"of side length 1+2*r \"\"\" for x,y in g: for dx in range(-r,",
"r+1): yield dx+x, dy+y from PIL import Image, ImageDraw SIZE = 500 def",
"ImageDraw SIZE = 500 def render_echo_chamber(r): def screen_circle(center, r, **style): x,y = center",
"yield int(x), y-1 else: yield int(x)+1, y x = int(x) yield x, y",
"r2 = r ** 2 y = 0 while y <= r: x",
"while y <= r: x = sqrt(r2 - y**2) if x-int(x) >= 0.5:",
"x2 = sqrt(r2 - (y-0.5)**2) if x2 < int(x)+0.5: yield int(x), y-1 else:",
"yield x+v, y+h yield x-v, y+h yield x+v, y-h yield x-v, y-h def",
"import Image, ImageDraw SIZE = 500 def render_echo_chamber(r): def screen_circle(center, r, **style): x,y",
"in range(steps+1): f = i / float(steps) yield start+(f * (stop-start)) import animation",
"outline=\"black\") else: tiles = set(brush(circle_coords(0,0,r), 2)) for x,y in tiles: logical_circle((x,y), r, outline=\"black\")",
"y+v yield x+h, y-v yield x-h, y-v yield x+v, y+h yield x-v, y+h",
"coordinates using a square \"brush\" of side length 1+2*r \"\"\" for x,y in",
"int(x)+1, y x = int(x) yield x, y if x <= r//2: break",
"- either the one to the # left or the one above (or",
"- (y-0.5)**2) if x2 < int(x)+0.5: yield int(x), y-1 else: yield int(x)+1, y",
"return img def frange(start, stop, steps): for i in range(steps+1): f = i",
"yield x-h, y+v yield x+h, y-v yield x-h, y-v yield x+v, y+h yield",
"else: tiles = set(brush(circle_coords(0,0,r), 2)) for x,y in tiles: logical_circle((x,y), r, outline=\"black\") return",
"yield start+(f * (stop-start)) import animation max_radius = 8 frames_per_radius = 64 frames",
"y <= r: x = sqrt(r2 - y**2) if x-int(x) >= 0.5: x",
"left or the one above (or neither?). # To do this, we calculate",
"for h, v in circle_octant(r): yield x+h, y+v yield x-h, y+v yield x+h,",
"y x = int(x) yield x, y if x <= r//2: break y",
"= ImageDraw.Draw(img) if r <= 0.5: logical_circle((0, 0), r, outline=\"black\") else: tiles =",
"pixel # the circle moved through - either the one to the #",
"y += 1 #Courtesy of Aran-Fey https://chat.stackoverflow.com/transcript/message/47258396#47258396 def circle_coords(x, y, r): for h,",
"x-h, y-v yield x+v, y+h yield x-v, y+h yield x+v, y-h yield x-v,",
"+= 1 else: # If we moved left, find out which adjacent pixel",
"set(brush(circle_coords(0,0,r), 2)) for x,y in tiles: logical_circle((x,y), r, outline=\"black\") return img def frange(start,",
"= (logical_y + 0.5) * SIZE screen_r = r * SIZE screen_circle((screen_x, screen_y),",
"from PIL import Image, ImageDraw SIZE = 500 def render_echo_chamber(r): def screen_circle(center, r,",
"r * SIZE screen_circle((screen_x, screen_y), screen_r, **style) img = Image.new(\"RGB\", (SIZE, SIZE), \"white\")",
"**style) def logical_circle(center, r, **style): logical_x, logical_y = center screen_x = (logical_x +",
"0), r, outline=\"black\") else: tiles = set(brush(circle_coords(0,0,r), 2)) for x,y in tiles: logical_circle((x,y),",
"y if x <= r//2: break y += 1 #Courtesy of Aran-Fey https://chat.stackoverflow.com/transcript/message/47258396#47258396",
"left, find out which adjacent pixel # the circle moved through - either",
"float(steps) yield start+(f * (stop-start)) import animation max_radius = 8 frames_per_radius = 64",
"draw = ImageDraw.Draw(img) if r <= 0.5: logical_circle((0, 0), r, outline=\"black\") else: tiles",
"r, outline=\"black\") return img def frange(start, stop, steps): for i in range(steps+1): f",
"y-v yield x-h, y-v yield x+v, y+h yield x-v, y+h yield x+v, y-h",
"iterable of coordinates using a square \"brush\" of side length 1+2*r \"\"\" for",
"r): \"\"\" draws over an iterable of coordinates using a square \"brush\" of",
"above (or neither?). # To do this, we calculate the x coordinate in",
"i / float(steps) yield start+(f * (stop-start)) import animation max_radius = 8 frames_per_radius",
"center screen_x = (logical_x + 0.5) * SIZE screen_y = (logical_y + 0.5)",
"over an iterable of coordinates using a square \"brush\" of side length 1+2*r",
"yield x, y if x <= r//2: break y += 1 #Courtesy of",
"0.5) * SIZE screen_y = (logical_y + 0.5) * SIZE screen_r = r",
"one below. x2 = sqrt(r2 - (y-0.5)**2) if x2 < int(x)+0.5: yield int(x),",
"screen_y), screen_r, **style) img = Image.new(\"RGB\", (SIZE, SIZE), \"white\") draw = ImageDraw.Draw(img) if",
"between the current pixel and the one below. x2 = sqrt(r2 - (y-0.5)**2)",
"below. x2 = sqrt(r2 - (y-0.5)**2) if x2 < int(x)+0.5: yield int(x), y-1",
"= [] for f in frange(0, max_radius, frames_per_radius*max_radius): print(f) frames.append(render_echo_chamber(f)) animation.make_gif(frames, delay=8, delete_temp_files=True)",
"x += 1 else: # If we moved left, find out which adjacent",
"of coordinates using a square \"brush\" of side length 1+2*r \"\"\" for x,y",
"= set(brush(circle_coords(0,0,r), 2)) for x,y in tiles: logical_circle((x,y), r, outline=\"black\") return img def",
"= i / float(steps) yield start+(f * (stop-start)) import animation max_radius = 8",
"https://chat.stackoverflow.com/transcript/message/47258396#47258396 def circle_octant(r): r2 = r ** 2 y = 0 while y",
"r+1): for dy in range(-r, r+1): yield dx+x, dy+y from PIL import Image,",
"moved through - either the one to the # left or the one",
"r): for h, v in circle_octant(r): yield x+h, y+v yield x-h, y+v yield",
"\"brush\" of side length 1+2*r \"\"\" for x,y in g: for dx in",
"pixel and the one below. x2 = sqrt(r2 - (y-0.5)**2) if x2 <",
"circle moved through - either the one to the # left or the",
"circle_coords(x, y, r): for h, v in circle_octant(r): yield x+h, y+v yield x-h,",
"the # center between the current pixel and the one below. x2 =",
"yield x+h, y+v yield x-h, y+v yield x+h, y-v yield x-h, y-v yield",
"* SIZE screen_circle((screen_x, screen_y), screen_r, **style) img = Image.new(\"RGB\", (SIZE, SIZE), \"white\") draw",
"r ** 2 y = 0 while y <= r: x = sqrt(r2",
"0, 359, **style) def logical_circle(center, r, **style): logical_x, logical_y = center screen_x =",
"(or neither?). # To do this, we calculate the x coordinate in the",
"screen_circle(center, r, **style): x,y = center draw.chord((x-r,y-r, x+r,y+r), 0, 359, **style) def logical_circle(center,",
"h, v in circle_octant(r): yield x+h, y+v yield x-h, y+v yield x+h, y-v",
"yield x+v, y-h yield x-v, y-h def brush(g, r): \"\"\" draws over an",
"square \"brush\" of side length 1+2*r \"\"\" for x,y in g: for dx",
"adjacent pixel # the circle moved through - either the one to the",
"\"\"\" for x,y in g: for dx in range(-r, r+1): for dy in",
"Image.new(\"RGB\", (SIZE, SIZE), \"white\") draw = ImageDraw.Draw(img) if r <= 0.5: logical_circle((0, 0),",
"the one to the # left or the one above (or neither?). #",
"sqrt(r2 - (y-0.5)**2) if x2 < int(x)+0.5: yield int(x), y-1 else: yield int(x)+1,",
"one to the # left or the one above (or neither?). # To",
"one above (or neither?). # To do this, we calculate the x coordinate",
"= sqrt(r2 - (y-0.5)**2) if x2 < int(x)+0.5: yield int(x), y-1 else: yield",
"screen_x = (logical_x + 0.5) * SIZE screen_y = (logical_y + 0.5) *",
"= center screen_x = (logical_x + 0.5) * SIZE screen_y = (logical_y +",
"y-1 else: yield int(x)+1, y x = int(x) yield x, y if x",
"the one below. x2 = sqrt(r2 - (y-0.5)**2) if x2 < int(x)+0.5: yield",
"0 while y <= r: x = sqrt(r2 - y**2) if x-int(x) >=",
"r: x = sqrt(r2 - y**2) if x-int(x) >= 0.5: x += 1",
"x+h, y+v yield x-h, y+v yield x+h, y-v yield x-h, y-v yield x+v,",
"circle_octant(r): yield x+h, y+v yield x-h, y+v yield x+h, y-v yield x-h, y-v",
"= 64 frames = [] for f in frange(0, max_radius, frames_per_radius*max_radius): print(f) frames.append(render_echo_chamber(f))",
"(logical_x + 0.5) * SIZE screen_y = (logical_y + 0.5) * SIZE screen_r",
"an iterable of coordinates using a square \"brush\" of side length 1+2*r \"\"\"",
"def render_echo_chamber(r): def screen_circle(center, r, **style): x,y = center draw.chord((x-r,y-r, x+r,y+r), 0, 359,",
"f = i / float(steps) yield start+(f * (stop-start)) import animation max_radius =",
"yield x-v, y+h yield x+v, y-h yield x-v, y-h def brush(g, r): \"\"\"",
"through - either the one to the # left or the one above",
"sqrt #Courtesy of Aran-Fey https://chat.stackoverflow.com/transcript/message/47258396#47258396 def circle_octant(r): r2 = r ** 2 y",
"y-v yield x+v, y+h yield x-v, y+h yield x+v, y-h yield x-v, y-h",
"0.5: logical_circle((0, 0), r, outline=\"black\") else: tiles = set(brush(circle_coords(0,0,r), 2)) for x,y in",
"* SIZE screen_r = r * SIZE screen_circle((screen_x, screen_y), screen_r, **style) img =",
"range(-r, r+1): for dy in range(-r, r+1): yield dx+x, dy+y from PIL import",
"ImageDraw.Draw(img) if r <= 0.5: logical_circle((0, 0), r, outline=\"black\") else: tiles = set(brush(circle_coords(0,0,r),",
"render_echo_chamber(r): def screen_circle(center, r, **style): x,y = center draw.chord((x-r,y-r, x+r,y+r), 0, 359, **style)",
"dy+y from PIL import Image, ImageDraw SIZE = 500 def render_echo_chamber(r): def screen_circle(center,",
"500 def render_echo_chamber(r): def screen_circle(center, r, **style): x,y = center draw.chord((x-r,y-r, x+r,y+r), 0,",
"r, **style): logical_x, logical_y = center screen_x = (logical_x + 0.5) * SIZE",
"logical_y = center screen_x = (logical_x + 0.5) * SIZE screen_y = (logical_y",
"<= 0.5: logical_circle((0, 0), r, outline=\"black\") else: tiles = set(brush(circle_coords(0,0,r), 2)) for x,y",
"* (stop-start)) import animation max_radius = 8 frames_per_radius = 64 frames = []",
"coordinate in the # center between the current pixel and the one below.",
"#Courtesy of Aran-Fey https://chat.stackoverflow.com/transcript/message/47258396#47258396 def circle_coords(x, y, r): for h, v in circle_octant(r):",
"y+v yield x-h, y+v yield x+h, y-v yield x-h, y-v yield x+v, y+h",
"a square \"brush\" of side length 1+2*r \"\"\" for x,y in g: for",
"stop, steps): for i in range(steps+1): f = i / float(steps) yield start+(f",
"x = int(x) yield x, y if x <= r//2: break y +=",
"for x,y in g: for dx in range(-r, r+1): for dy in range(-r,",
"r, outline=\"black\") else: tiles = set(brush(circle_coords(0,0,r), 2)) for x,y in tiles: logical_circle((x,y), r,",
"**style): x,y = center draw.chord((x-r,y-r, x+r,y+r), 0, 359, **style) def logical_circle(center, r, **style):",
"def screen_circle(center, r, **style): x,y = center draw.chord((x-r,y-r, x+r,y+r), 0, 359, **style) def",
"= 500 def render_echo_chamber(r): def screen_circle(center, r, **style): x,y = center draw.chord((x-r,y-r, x+r,y+r),",
"**style): logical_x, logical_y = center screen_x = (logical_x + 0.5) * SIZE screen_y",
"** 2 y = 0 while y <= r: x = sqrt(r2 -",
"img = Image.new(\"RGB\", (SIZE, SIZE), \"white\") draw = ImageDraw.Draw(img) if r <= 0.5:",
"def circle_coords(x, y, r): for h, v in circle_octant(r): yield x+h, y+v yield",
"SIZE screen_y = (logical_y + 0.5) * SIZE screen_r = r * SIZE",
"x-int(x) >= 0.5: x += 1 else: # If we moved left, find",
"steps): for i in range(steps+1): f = i / float(steps) yield start+(f *",
"or the one above (or neither?). # To do this, we calculate the",
"yield x+h, y-v yield x-h, y-v yield x+v, y+h yield x-v, y+h yield",
"int(x) yield x, y if x <= r//2: break y += 1 #Courtesy",
"= Image.new(\"RGB\", (SIZE, SIZE), \"white\") draw = ImageDraw.Draw(img) if r <= 0.5: logical_circle((0,",
"dx in range(-r, r+1): for dy in range(-r, r+1): yield dx+x, dy+y from",
"for x,y in tiles: logical_circle((x,y), r, outline=\"black\") return img def frange(start, stop, steps):",
"range(steps+1): f = i / float(steps) yield start+(f * (stop-start)) import animation max_radius",
"SIZE = 500 def render_echo_chamber(r): def screen_circle(center, r, **style): x,y = center draw.chord((x-r,y-r,",
"neither?). # To do this, we calculate the x coordinate in the #",
"which adjacent pixel # the circle moved through - either the one to",
"<= r//2: break y += 1 #Courtesy of Aran-Fey https://chat.stackoverflow.com/transcript/message/47258396#47258396 def circle_coords(x, y,",
"draws over an iterable of coordinates using a square \"brush\" of side length",
"screen_y = (logical_y + 0.5) * SIZE screen_r = r * SIZE screen_circle((screen_x,",
"in circle_octant(r): yield x+h, y+v yield x-h, y+v yield x+h, y-v yield x-h,",
"+ 0.5) * SIZE screen_y = (logical_y + 0.5) * SIZE screen_r =",
"start+(f * (stop-start)) import animation max_radius = 8 frames_per_radius = 64 frames =",
"64 frames = [] for f in frange(0, max_radius, frames_per_radius*max_radius): print(f) frames.append(render_echo_chamber(f)) animation.make_gif(frames,",
"x-v, y-h def brush(g, r): \"\"\" draws over an iterable of coordinates using",
"logical_circle(center, r, **style): logical_x, logical_y = center screen_x = (logical_x + 0.5) *",
"screen_circle((screen_x, screen_y), screen_r, **style) img = Image.new(\"RGB\", (SIZE, SIZE), \"white\") draw = ImageDraw.Draw(img)",
"SIZE), \"white\") draw = ImageDraw.Draw(img) if r <= 0.5: logical_circle((0, 0), r, outline=\"black\")",
"x-h, y+v yield x+h, y-v yield x-h, y-v yield x+v, y+h yield x-v,",
"length 1+2*r \"\"\" for x,y in g: for dx in range(-r, r+1): for",
"Aran-Fey https://chat.stackoverflow.com/transcript/message/47258396#47258396 def circle_coords(x, y, r): for h, v in circle_octant(r): yield x+h,",
"to the # left or the one above (or neither?). # To do",
"359, **style) def logical_circle(center, r, **style): logical_x, logical_y = center screen_x = (logical_x",
"import sqrt #Courtesy of Aran-Fey https://chat.stackoverflow.com/transcript/message/47258396#47258396 def circle_octant(r): r2 = r ** 2",
"the x coordinate in the # center between the current pixel and the",
"def logical_circle(center, r, **style): logical_x, logical_y = center screen_x = (logical_x + 0.5)",
"def circle_octant(r): r2 = r ** 2 y = 0 while y <=",
"in tiles: logical_circle((x,y), r, outline=\"black\") return img def frange(start, stop, steps): for i",
"<= r: x = sqrt(r2 - y**2) if x-int(x) >= 0.5: x +=",
"find out which adjacent pixel # the circle moved through - either the",
"x <= r//2: break y += 1 #Courtesy of Aran-Fey https://chat.stackoverflow.com/transcript/message/47258396#47258396 def circle_coords(x,",
"frames_per_radius = 64 frames = [] for f in frange(0, max_radius, frames_per_radius*max_radius): print(f)",
"from math import sqrt #Courtesy of Aran-Fey https://chat.stackoverflow.com/transcript/message/47258396#47258396 def circle_octant(r): r2 = r",
"the # left or the one above (or neither?). # To do this,",
"we calculate the x coordinate in the # center between the current pixel",
"x+h, y-v yield x-h, y-v yield x+v, y+h yield x-v, y+h yield x+v,",
"center draw.chord((x-r,y-r, x+r,y+r), 0, 359, **style) def logical_circle(center, r, **style): logical_x, logical_y =",
"if x2 < int(x)+0.5: yield int(x), y-1 else: yield int(x)+1, y x =",
"# the circle moved through - either the one to the # left",
"r, **style): x,y = center draw.chord((x-r,y-r, x+r,y+r), 0, 359, **style) def logical_circle(center, r,",
"draw.chord((x-r,y-r, x+r,y+r), 0, 359, **style) def logical_circle(center, r, **style): logical_x, logical_y = center",
"# center between the current pixel and the one below. x2 = sqrt(r2",
"y+h yield x-v, y+h yield x+v, y-h yield x-v, y-h def brush(g, r):",
"x+r,y+r), 0, 359, **style) def logical_circle(center, r, **style): logical_x, logical_y = center screen_x",
"animation max_radius = 8 frames_per_radius = 64 frames = [] for f in",
"1 #Courtesy of Aran-Fey https://chat.stackoverflow.com/transcript/message/47258396#47258396 def circle_coords(x, y, r): for h, v in",
"1+2*r \"\"\" for x,y in g: for dx in range(-r, r+1): for dy",
"math import sqrt #Courtesy of Aran-Fey https://chat.stackoverflow.com/transcript/message/47258396#47258396 def circle_octant(r): r2 = r **",
"for dx in range(-r, r+1): for dy in range(-r, r+1): yield dx+x, dy+y",
"yield dx+x, dy+y from PIL import Image, ImageDraw SIZE = 500 def render_echo_chamber(r):",
"x,y = center draw.chord((x-r,y-r, x+r,y+r), 0, 359, **style) def logical_circle(center, r, **style): logical_x,",
"1 else: # If we moved left, find out which adjacent pixel #",
"# To do this, we calculate the x coordinate in the # center",
"calculate the x coordinate in the # center between the current pixel and",
"x+v, y+h yield x-v, y+h yield x+v, y-h yield x-v, y-h def brush(g,",
"in range(-r, r+1): yield dx+x, dy+y from PIL import Image, ImageDraw SIZE =",
"x2 < int(x)+0.5: yield int(x), y-1 else: yield int(x)+1, y x = int(x)",
"- y**2) if x-int(x) >= 0.5: x += 1 else: # If we",
"screen_r = r * SIZE screen_circle((screen_x, screen_y), screen_r, **style) img = Image.new(\"RGB\", (SIZE,",
"max_radius = 8 frames_per_radius = 64 frames = [] for f in frange(0,",
"do this, we calculate the x coordinate in the # center between the",
"dy in range(-r, r+1): yield dx+x, dy+y from PIL import Image, ImageDraw SIZE",
"the circle moved through - either the one to the # left or",
"logical_x, logical_y = center screen_x = (logical_x + 0.5) * SIZE screen_y =",
"center between the current pixel and the one below. x2 = sqrt(r2 -",
"(SIZE, SIZE), \"white\") draw = ImageDraw.Draw(img) if r <= 0.5: logical_circle((0, 0), r,",
"i in range(steps+1): f = i / float(steps) yield start+(f * (stop-start)) import",
"def frange(start, stop, steps): for i in range(steps+1): f = i / float(steps)",
"logical_circle((0, 0), r, outline=\"black\") else: tiles = set(brush(circle_coords(0,0,r), 2)) for x,y in tiles:",
"x coordinate in the # center between the current pixel and the one",
"https://chat.stackoverflow.com/transcript/message/47258396#47258396 def circle_coords(x, y, r): for h, v in circle_octant(r): yield x+h, y+v",
"To do this, we calculate the x coordinate in the # center between",
"< int(x)+0.5: yield int(x), y-1 else: yield int(x)+1, y x = int(x) yield",
"this, we calculate the x coordinate in the # center between the current",
"/ float(steps) yield start+(f * (stop-start)) import animation max_radius = 8 frames_per_radius =",
"yield x-h, y-v yield x+v, y+h yield x-v, y+h yield x+v, y-h yield",
"the current pixel and the one below. x2 = sqrt(r2 - (y-0.5)**2) if",
"= (logical_x + 0.5) * SIZE screen_y = (logical_y + 0.5) * SIZE",
"+= 1 #Courtesy of Aran-Fey https://chat.stackoverflow.com/transcript/message/47258396#47258396 def circle_coords(x, y, r): for h, v",
"PIL import Image, ImageDraw SIZE = 500 def render_echo_chamber(r): def screen_circle(center, r, **style):",
"if x-int(x) >= 0.5: x += 1 else: # If we moved left,",
"# If we moved left, find out which adjacent pixel # the circle",
"(stop-start)) import animation max_radius = 8 frames_per_radius = 64 frames = [] for",
"brush(g, r): \"\"\" draws over an iterable of coordinates using a square \"brush\"",
"img def frange(start, stop, steps): for i in range(steps+1): f = i /",
"r//2: break y += 1 #Courtesy of Aran-Fey https://chat.stackoverflow.com/transcript/message/47258396#47258396 def circle_coords(x, y, r):",
"(logical_y + 0.5) * SIZE screen_r = r * SIZE screen_circle((screen_x, screen_y), screen_r,",
"break y += 1 #Courtesy of Aran-Fey https://chat.stackoverflow.com/transcript/message/47258396#47258396 def circle_coords(x, y, r): for",
">= 0.5: x += 1 else: # If we moved left, find out",
"g: for dx in range(-r, r+1): for dy in range(-r, r+1): yield dx+x,",
"= r ** 2 y = 0 while y <= r: x =",
"= 0 while y <= r: x = sqrt(r2 - y**2) if x-int(x)",
"= sqrt(r2 - y**2) if x-int(x) >= 0.5: x += 1 else: #",
"if r <= 0.5: logical_circle((0, 0), r, outline=\"black\") else: tiles = set(brush(circle_coords(0,0,r), 2))",
"y**2) if x-int(x) >= 0.5: x += 1 else: # If we moved",
"x,y in tiles: logical_circle((x,y), r, outline=\"black\") return img def frange(start, stop, steps): for",
"circle_octant(r): r2 = r ** 2 y = 0 while y <= r:",
"If we moved left, find out which adjacent pixel # the circle moved"
] |
[
"import pyOcean_cpu as ocean s = ocean.cdouble(3+4j) print(s) print(s.asPython()) print(s.imag.asPython()) print(s.real.asPython()) print(int(s.real)) print(float(s.real))"
] |
[
". import factory def create_app(settings_override=None): # Returns the app API application instance app",
"create_app(settings_override=None): # Returns the app API application instance app = factory.create_app(__name__, __path__, settings_override)",
"Returns the app API application instance app = factory.create_app(__name__, __path__, settings_override) return app",
"# Returns the app API application instance app = factory.create_app(__name__, __path__, settings_override) return",
"factory def create_app(settings_override=None): # Returns the app API application instance app = factory.create_app(__name__,",
"from . import factory def create_app(settings_override=None): # Returns the app API application instance",
"def create_app(settings_override=None): # Returns the app API application instance app = factory.create_app(__name__, __path__,",
"import factory def create_app(settings_override=None): # Returns the app API application instance app ="
] |
[
"FastAPI, Body app = FastAPI() @app.get(\"/\") def read_root(): return {\"Hello\": \"World\"} @app.get(\"/items/{item_id}\") def",
"else: def create_application(): from typing import Optional from fastapi import FastAPI, Body app",
"create_application(): from typing import Optional from fastapi import FastAPI, Body app = FastAPI()",
"asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) # 启动服务 server( __file__ + \":app\", port=8080, # port=8443, worker_nums=1, # enable_https=True,",
"# encoding=utf-8 if __name__ == \"__main__\": import asyncio import os import uvloop from",
"\":app\", port=8080, # port=8443, worker_nums=1, # enable_https=True, certfile=os.path.join(os.path.dirname(__file__), \"test.crt\"), keyfile=os.path.join(os.path.dirname(__file__), \"test.key\"), ) else:",
"# 设置 uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) # 启动服务 server( __file__ + \":app\", port=8080, # port=8443,",
"def create_application(): from typing import Optional from fastapi import FastAPI, Body app =",
"import FastAPI, Body app = FastAPI() @app.get(\"/\") def read_root(): return {\"Hello\": \"World\"} @app.get(\"/items/{item_id}\")",
"import Optional from fastapi import FastAPI, Body app = FastAPI() @app.get(\"/\") def read_root():",
"def read_root(): return {\"Hello\": \"World\"} @app.get(\"/items/{item_id}\") def read_item(item_id: int, q: Optional[str] = None):",
"from fastapi import FastAPI, Body app = FastAPI() @app.get(\"/\") def read_root(): return {\"Hello\":",
"Optional[str] = None): return {\"item_id\": item_id, \"q\": q} @app.post(\"/post\") def read_body(body=Body(...)): return body",
"import asyncio import os import uvloop from ahserver.application.asgi import server # 设置 uvloop",
"server # 设置 uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) # 启动服务 server( __file__ + \":app\", port=8080, #",
"os import uvloop from ahserver.application.asgi import server # 设置 uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) # 启动服务",
"# enable_https=True, certfile=os.path.join(os.path.dirname(__file__), \"test.crt\"), keyfile=os.path.join(os.path.dirname(__file__), \"test.key\"), ) else: def create_application(): from typing import",
"certfile=os.path.join(os.path.dirname(__file__), \"test.crt\"), keyfile=os.path.join(os.path.dirname(__file__), \"test.key\"), ) else: def create_application(): from typing import Optional from",
"item_id, \"q\": q} @app.post(\"/post\") def read_body(body=Body(...)): return body return app app = create_application()",
"asyncio import os import uvloop from ahserver.application.asgi import server # 设置 uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())",
"\"test.key\"), ) else: def create_application(): from typing import Optional from fastapi import FastAPI,",
"app = FastAPI() @app.get(\"/\") def read_root(): return {\"Hello\": \"World\"} @app.get(\"/items/{item_id}\") def read_item(item_id: int,",
"\"test.crt\"), keyfile=os.path.join(os.path.dirname(__file__), \"test.key\"), ) else: def create_application(): from typing import Optional from fastapi",
"typing import Optional from fastapi import FastAPI, Body app = FastAPI() @app.get(\"/\") def",
"@app.get(\"/items/{item_id}\") def read_item(item_id: int, q: Optional[str] = None): return {\"item_id\": item_id, \"q\": q}",
"port=8080, # port=8443, worker_nums=1, # enable_https=True, certfile=os.path.join(os.path.dirname(__file__), \"test.crt\"), keyfile=os.path.join(os.path.dirname(__file__), \"test.key\"), ) else: def",
"# 启动服务 server( __file__ + \":app\", port=8080, # port=8443, worker_nums=1, # enable_https=True, certfile=os.path.join(os.path.dirname(__file__),",
"read_root(): return {\"Hello\": \"World\"} @app.get(\"/items/{item_id}\") def read_item(item_id: int, q: Optional[str] = None): return",
"encoding=utf-8 if __name__ == \"__main__\": import asyncio import os import uvloop from ahserver.application.asgi",
"Body app = FastAPI() @app.get(\"/\") def read_root(): return {\"Hello\": \"World\"} @app.get(\"/items/{item_id}\") def read_item(item_id:",
"= None): return {\"item_id\": item_id, \"q\": q} @app.post(\"/post\") def read_body(body=Body(...)): return body return",
"server( __file__ + \":app\", port=8080, # port=8443, worker_nums=1, # enable_https=True, certfile=os.path.join(os.path.dirname(__file__), \"test.crt\"), keyfile=os.path.join(os.path.dirname(__file__),",
") else: def create_application(): from typing import Optional from fastapi import FastAPI, Body",
"+ \":app\", port=8080, # port=8443, worker_nums=1, # enable_https=True, certfile=os.path.join(os.path.dirname(__file__), \"test.crt\"), keyfile=os.path.join(os.path.dirname(__file__), \"test.key\"), )",
"None): return {\"item_id\": item_id, \"q\": q} @app.post(\"/post\") def read_body(body=Body(...)): return body return app",
"from typing import Optional from fastapi import FastAPI, Body app = FastAPI() @app.get(\"/\")",
"__file__ + \":app\", port=8080, # port=8443, worker_nums=1, # enable_https=True, certfile=os.path.join(os.path.dirname(__file__), \"test.crt\"), keyfile=os.path.join(os.path.dirname(__file__), \"test.key\"),",
"{\"Hello\": \"World\"} @app.get(\"/items/{item_id}\") def read_item(item_id: int, q: Optional[str] = None): return {\"item_id\": item_id,",
"keyfile=os.path.join(os.path.dirname(__file__), \"test.key\"), ) else: def create_application(): from typing import Optional from fastapi import",
"return {\"Hello\": \"World\"} @app.get(\"/items/{item_id}\") def read_item(item_id: int, q: Optional[str] = None): return {\"item_id\":",
"设置 uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) # 启动服务 server( __file__ + \":app\", port=8080, # port=8443, worker_nums=1,",
"import uvloop from ahserver.application.asgi import server # 设置 uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) # 启动服务 server(",
"q: Optional[str] = None): return {\"item_id\": item_id, \"q\": q} @app.post(\"/post\") def read_body(body=Body(...)): return",
"import server # 设置 uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) # 启动服务 server( __file__ + \":app\", port=8080,",
"def read_item(item_id: int, q: Optional[str] = None): return {\"item_id\": item_id, \"q\": q} @app.post(\"/post\")",
"int, q: Optional[str] = None): return {\"item_id\": item_id, \"q\": q} @app.post(\"/post\") def read_body(body=Body(...)):",
"ahserver.application.asgi import server # 设置 uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) # 启动服务 server( __file__ + \":app\",",
"== \"__main__\": import asyncio import os import uvloop from ahserver.application.asgi import server #",
"<filename>example/hello_fastapi.py # encoding=utf-8 if __name__ == \"__main__\": import asyncio import os import uvloop",
"uvloop from ahserver.application.asgi import server # 设置 uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) # 启动服务 server( __file__",
"\"World\"} @app.get(\"/items/{item_id}\") def read_item(item_id: int, q: Optional[str] = None): return {\"item_id\": item_id, \"q\":",
"Optional from fastapi import FastAPI, Body app = FastAPI() @app.get(\"/\") def read_root(): return",
"enable_https=True, certfile=os.path.join(os.path.dirname(__file__), \"test.crt\"), keyfile=os.path.join(os.path.dirname(__file__), \"test.key\"), ) else: def create_application(): from typing import Optional",
"# port=8443, worker_nums=1, # enable_https=True, certfile=os.path.join(os.path.dirname(__file__), \"test.crt\"), keyfile=os.path.join(os.path.dirname(__file__), \"test.key\"), ) else: def create_application():",
"return {\"item_id\": item_id, \"q\": q} @app.post(\"/post\") def read_body(body=Body(...)): return body return app app",
"from ahserver.application.asgi import server # 设置 uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) # 启动服务 server( __file__ +",
"fastapi import FastAPI, Body app = FastAPI() @app.get(\"/\") def read_root(): return {\"Hello\": \"World\"}",
"read_item(item_id: int, q: Optional[str] = None): return {\"item_id\": item_id, \"q\": q} @app.post(\"/post\") def",
"worker_nums=1, # enable_https=True, certfile=os.path.join(os.path.dirname(__file__), \"test.crt\"), keyfile=os.path.join(os.path.dirname(__file__), \"test.key\"), ) else: def create_application(): from typing",
"port=8443, worker_nums=1, # enable_https=True, certfile=os.path.join(os.path.dirname(__file__), \"test.crt\"), keyfile=os.path.join(os.path.dirname(__file__), \"test.key\"), ) else: def create_application(): from",
"uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) # 启动服务 server( __file__ + \":app\", port=8080, # port=8443, worker_nums=1, #",
"@app.get(\"/\") def read_root(): return {\"Hello\": \"World\"} @app.get(\"/items/{item_id}\") def read_item(item_id: int, q: Optional[str] =",
"__name__ == \"__main__\": import asyncio import os import uvloop from ahserver.application.asgi import server",
"import os import uvloop from ahserver.application.asgi import server # 设置 uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) #",
"if __name__ == \"__main__\": import asyncio import os import uvloop from ahserver.application.asgi import",
"{\"item_id\": item_id, \"q\": q} @app.post(\"/post\") def read_body(body=Body(...)): return body return app app =",
"\"__main__\": import asyncio import os import uvloop from ahserver.application.asgi import server # 设置",
"启动服务 server( __file__ + \":app\", port=8080, # port=8443, worker_nums=1, # enable_https=True, certfile=os.path.join(os.path.dirname(__file__), \"test.crt\"),",
"= FastAPI() @app.get(\"/\") def read_root(): return {\"Hello\": \"World\"} @app.get(\"/items/{item_id}\") def read_item(item_id: int, q:",
"FastAPI() @app.get(\"/\") def read_root(): return {\"Hello\": \"World\"} @app.get(\"/items/{item_id}\") def read_item(item_id: int, q: Optional[str]"
] |
[
"self.r[self.ip] if self.hacked and self.i == 1 and max(self.r) > 5: self.r[0] =",
"int(d)] for a, b, c, d in lines] return ip, lines funcs =",
"= hacked self.ip = ip self.i = 0 self.d = d self.r =",
"self.d[self.i] op = funcs[opname] self.r[self.ip] = self.i op(self.r, a, b, c) self.r[self.ip] +=",
"def parsed(data): lines = data.splitlines() ip = int(lines.pop(0).split()[1]) lines = [s.split() for s",
"int(c), int(d)] for a, b, c, d in lines] return ip, lines funcs",
"1 and max(self.r) > 5: self.r[0] = sum(divisors(max(self.r))) [][0] def compute(data, r0=0, hack=False):",
"[s.split() for s in lines] lines = [[a, int(b), int(c), int(d)] for a,",
"d, r0, hacked): self.hacked = hacked self.ip = ip self.i = 0 self.d",
"= data.splitlines() ip = int(lines.pop(0).split()[1]) lines = [s.split() for s in lines] lines",
"data from aoc_wim.aoc2018.q16 import all_ops def parsed(data): lines = data.splitlines() ip = int(lines.pop(0).split()[1])",
"self.r[self.ip] = self.i op(self.r, a, b, c) self.r[self.ip] += 1 self.i = self.r[self.ip]",
"while True: try: comp.step() except IndexError: break return comp.r[0] def divisors(n): divs =",
"__init__(self, ip, d, r0, hacked): self.hacked = hacked self.ip = ip self.i =",
"The Flow --- https://adventofcode.com/2018/day/19 \"\"\" import math from aocd import data from aoc_wim.aoc2018.q16",
"and max(self.r) > 5: self.r[0] = sum(divisors(max(self.r))) [][0] def compute(data, r0=0, hack=False): ip,",
"[0] * 6 self.r[0] = r0 def step(self): opname, a, b, c =",
"lines] return ip, lines funcs = all_ops() class Comp: def __init__(self, ip, d,",
"c, d in lines] return ip, lines funcs = all_ops() class Comp: def",
"i} return divs print(\"part a:\", compute(data, r0=0, hack=True)) print(\"part b:\", compute(data, r0=1, hack=True))",
"= [[a, int(b), int(c), int(d)] for a, b, c, d in lines] return",
"in lines] return ip, lines funcs = all_ops() class Comp: def __init__(self, ip,",
"break return comp.r[0] def divisors(n): divs = {1, n} for i in range(2,",
"r0 def step(self): opname, a, b, c = self.d[self.i] op = funcs[opname] self.r[self.ip]",
"n % i: divs |= {i, n // i} return divs print(\"part a:\",",
"c = self.d[self.i] op = funcs[opname] self.r[self.ip] = self.i op(self.r, a, b, c)",
"i: divs |= {i, n // i} return divs print(\"part a:\", compute(data, r0=0,",
"\"\"\" import math from aocd import data from aoc_wim.aoc2018.q16 import all_ops def parsed(data):",
"b, c = self.d[self.i] op = funcs[opname] self.r[self.ip] = self.i op(self.r, a, b,",
"Flow --- https://adventofcode.com/2018/day/19 \"\"\" import math from aocd import data from aoc_wim.aoc2018.q16 import",
"ip, lines funcs = all_ops() class Comp: def __init__(self, ip, d, r0, hacked):",
"ip self.i = 0 self.d = d self.r = [0] * 6 self.r[0]",
"= all_ops() class Comp: def __init__(self, ip, d, r0, hacked): self.hacked = hacked",
"[][0] def compute(data, r0=0, hack=False): ip, lines = parsed(data) comp = Comp(ip, lines,",
"aocd import data from aoc_wim.aoc2018.q16 import all_ops def parsed(data): lines = data.splitlines() ip",
"self.hacked and self.i == 1 and max(self.r) > 5: self.r[0] = sum(divisors(max(self.r))) [][0]",
"= Comp(ip, lines, r0=r0, hacked=hack) while True: try: comp.step() except IndexError: break return",
"from aocd import data from aoc_wim.aoc2018.q16 import all_ops def parsed(data): lines = data.splitlines()",
"s in lines] lines = [[a, int(b), int(c), int(d)] for a, b, c,",
"https://adventofcode.com/2018/day/19 \"\"\" import math from aocd import data from aoc_wim.aoc2018.q16 import all_ops def",
"opname, a, b, c = self.d[self.i] op = funcs[opname] self.r[self.ip] = self.i op(self.r,",
"def divisors(n): divs = {1, n} for i in range(2, int(math.sqrt(n)) + 1):",
"d in lines] return ip, lines funcs = all_ops() class Comp: def __init__(self,",
"and self.i == 1 and max(self.r) > 5: self.r[0] = sum(divisors(max(self.r))) [][0] def",
"self.i = self.r[self.ip] if self.hacked and self.i == 1 and max(self.r) > 5:",
"// i} return divs print(\"part a:\", compute(data, r0=0, hack=True)) print(\"part b:\", compute(data, r0=1,",
"b, c) self.r[self.ip] += 1 self.i = self.r[self.ip] if self.hacked and self.i ==",
"comp = Comp(ip, lines, r0=r0, hacked=hack) while True: try: comp.step() except IndexError: break",
"divs = {1, n} for i in range(2, int(math.sqrt(n)) + 1): if not",
"comp.r[0] def divisors(n): divs = {1, n} for i in range(2, int(math.sqrt(n)) +",
"= self.i op(self.r, a, b, c) self.r[self.ip] += 1 self.i = self.r[self.ip] if",
"IndexError: break return comp.r[0] def divisors(n): divs = {1, n} for i in",
"compute(data, r0=0, hack=False): ip, lines = parsed(data) comp = Comp(ip, lines, r0=r0, hacked=hack)",
"lines] lines = [[a, int(b), int(c), int(d)] for a, b, c, d in",
"i in range(2, int(math.sqrt(n)) + 1): if not n % i: divs |=",
"0 self.d = d self.r = [0] * 6 self.r[0] = r0 def",
"if not n % i: divs |= {i, n // i} return divs",
"math from aocd import data from aoc_wim.aoc2018.q16 import all_ops def parsed(data): lines =",
"Comp: def __init__(self, ip, d, r0, hacked): self.hacked = hacked self.ip = ip",
"import all_ops def parsed(data): lines = data.splitlines() ip = int(lines.pop(0).split()[1]) lines = [s.split()",
"lines = [[a, int(b), int(c), int(d)] for a, b, c, d in lines]",
"b, c, d in lines] return ip, lines funcs = all_ops() class Comp:",
"return comp.r[0] def divisors(n): divs = {1, n} for i in range(2, int(math.sqrt(n))",
"divisors(n): divs = {1, n} for i in range(2, int(math.sqrt(n)) + 1): if",
"= funcs[opname] self.r[self.ip] = self.i op(self.r, a, b, c) self.r[self.ip] += 1 self.i",
"all_ops def parsed(data): lines = data.splitlines() ip = int(lines.pop(0).split()[1]) lines = [s.split() for",
"import data from aoc_wim.aoc2018.q16 import all_ops def parsed(data): lines = data.splitlines() ip =",
"= parsed(data) comp = Comp(ip, lines, r0=r0, hacked=hack) while True: try: comp.step() except",
"Day 19: Go With The Flow --- https://adventofcode.com/2018/day/19 \"\"\" import math from aocd",
"comp.step() except IndexError: break return comp.r[0] def divisors(n): divs = {1, n} for",
"max(self.r) > 5: self.r[0] = sum(divisors(max(self.r))) [][0] def compute(data, r0=0, hack=False): ip, lines",
"n // i} return divs print(\"part a:\", compute(data, r0=0, hack=True)) print(\"part b:\", compute(data,",
"def __init__(self, ip, d, r0, hacked): self.hacked = hacked self.ip = ip self.i",
"= int(lines.pop(0).split()[1]) lines = [s.split() for s in lines] lines = [[a, int(b),",
"lines = parsed(data) comp = Comp(ip, lines, r0=r0, hacked=hack) while True: try: comp.step()",
"hacked=hack) while True: try: comp.step() except IndexError: break return comp.r[0] def divisors(n): divs",
"--- Day 19: Go With The Flow --- https://adventofcode.com/2018/day/19 \"\"\" import math from",
"for a, b, c, d in lines] return ip, lines funcs = all_ops()",
"= {1, n} for i in range(2, int(math.sqrt(n)) + 1): if not n",
"r0=r0, hacked=hack) while True: try: comp.step() except IndexError: break return comp.r[0] def divisors(n):",
"import math from aocd import data from aoc_wim.aoc2018.q16 import all_ops def parsed(data): lines",
"all_ops() class Comp: def __init__(self, ip, d, r0, hacked): self.hacked = hacked self.ip",
"self.hacked = hacked self.ip = ip self.i = 0 self.d = d self.r",
"class Comp: def __init__(self, ip, d, r0, hacked): self.hacked = hacked self.ip =",
"== 1 and max(self.r) > 5: self.r[0] = sum(divisors(max(self.r))) [][0] def compute(data, r0=0,",
"return ip, lines funcs = all_ops() class Comp: def __init__(self, ip, d, r0,",
"= 0 self.d = d self.r = [0] * 6 self.r[0] = r0",
"except IndexError: break return comp.r[0] def divisors(n): divs = {1, n} for i",
"in range(2, int(math.sqrt(n)) + 1): if not n % i: divs |= {i,",
"lines = [s.split() for s in lines] lines = [[a, int(b), int(c), int(d)]",
"self.r[0] = r0 def step(self): opname, a, b, c = self.d[self.i] op =",
"5: self.r[0] = sum(divisors(max(self.r))) [][0] def compute(data, r0=0, hack=False): ip, lines = parsed(data)",
"from aoc_wim.aoc2018.q16 import all_ops def parsed(data): lines = data.splitlines() ip = int(lines.pop(0).split()[1]) lines",
"19: Go With The Flow --- https://adventofcode.com/2018/day/19 \"\"\" import math from aocd import",
"lines = data.splitlines() ip = int(lines.pop(0).split()[1]) lines = [s.split() for s in lines]",
"= sum(divisors(max(self.r))) [][0] def compute(data, r0=0, hack=False): ip, lines = parsed(data) comp =",
"* 6 self.r[0] = r0 def step(self): opname, a, b, c = self.d[self.i]",
"True: try: comp.step() except IndexError: break return comp.r[0] def divisors(n): divs = {1,",
"ip, lines = parsed(data) comp = Comp(ip, lines, r0=r0, hacked=hack) while True: try:",
"sum(divisors(max(self.r))) [][0] def compute(data, r0=0, hack=False): ip, lines = parsed(data) comp = Comp(ip,",
"try: comp.step() except IndexError: break return comp.r[0] def divisors(n): divs = {1, n}",
"> 5: self.r[0] = sum(divisors(max(self.r))) [][0] def compute(data, r0=0, hack=False): ip, lines =",
"= self.r[self.ip] if self.hacked and self.i == 1 and max(self.r) > 5: self.r[0]",
"self.i = 0 self.d = d self.r = [0] * 6 self.r[0] =",
"for s in lines] lines = [[a, int(b), int(c), int(d)] for a, b,",
"in lines] lines = [[a, int(b), int(c), int(d)] for a, b, c, d",
"self.d = d self.r = [0] * 6 self.r[0] = r0 def step(self):",
"parsed(data): lines = data.splitlines() ip = int(lines.pop(0).split()[1]) lines = [s.split() for s in",
"ip = int(lines.pop(0).split()[1]) lines = [s.split() for s in lines] lines = [[a,",
"Go With The Flow --- https://adventofcode.com/2018/day/19 \"\"\" import math from aocd import data",
"int(lines.pop(0).split()[1]) lines = [s.split() for s in lines] lines = [[a, int(b), int(c),",
"int(b), int(c), int(d)] for a, b, c, d in lines] return ip, lines",
"<filename>aoc_wim/aoc2018/q19.py \"\"\" --- Day 19: Go With The Flow --- https://adventofcode.com/2018/day/19 \"\"\" import",
"{1, n} for i in range(2, int(math.sqrt(n)) + 1): if not n %",
"self.r[0] = sum(divisors(max(self.r))) [][0] def compute(data, r0=0, hack=False): ip, lines = parsed(data) comp",
"op = funcs[opname] self.r[self.ip] = self.i op(self.r, a, b, c) self.r[self.ip] += 1",
"= [0] * 6 self.r[0] = r0 def step(self): opname, a, b, c",
"int(math.sqrt(n)) + 1): if not n % i: divs |= {i, n //",
"data.splitlines() ip = int(lines.pop(0).split()[1]) lines = [s.split() for s in lines] lines =",
"lines, r0=r0, hacked=hack) while True: try: comp.step() except IndexError: break return comp.r[0] def",
"hacked): self.hacked = hacked self.ip = ip self.i = 0 self.d = d",
"6 self.r[0] = r0 def step(self): opname, a, b, c = self.d[self.i] op",
"for i in range(2, int(math.sqrt(n)) + 1): if not n % i: divs",
"--- https://adventofcode.com/2018/day/19 \"\"\" import math from aocd import data from aoc_wim.aoc2018.q16 import all_ops",
"hack=False): ip, lines = parsed(data) comp = Comp(ip, lines, r0=r0, hacked=hack) while True:",
"if self.hacked and self.i == 1 and max(self.r) > 5: self.r[0] = sum(divisors(max(self.r)))",
"= d self.r = [0] * 6 self.r[0] = r0 def step(self): opname,",
"self.r = [0] * 6 self.r[0] = r0 def step(self): opname, a, b,",
"{i, n // i} return divs print(\"part a:\", compute(data, r0=0, hack=True)) print(\"part b:\",",
"Comp(ip, lines, r0=r0, hacked=hack) while True: try: comp.step() except IndexError: break return comp.r[0]",
"parsed(data) comp = Comp(ip, lines, r0=r0, hacked=hack) while True: try: comp.step() except IndexError:",
"funcs = all_ops() class Comp: def __init__(self, ip, d, r0, hacked): self.hacked =",
"aoc_wim.aoc2018.q16 import all_ops def parsed(data): lines = data.splitlines() ip = int(lines.pop(0).split()[1]) lines =",
"+ 1): if not n % i: divs |= {i, n // i}",
"|= {i, n // i} return divs print(\"part a:\", compute(data, r0=0, hack=True)) print(\"part",
"d self.r = [0] * 6 self.r[0] = r0 def step(self): opname, a,",
"lines funcs = all_ops() class Comp: def __init__(self, ip, d, r0, hacked): self.hacked",
"% i: divs |= {i, n // i} return divs print(\"part a:\", compute(data,",
"1 self.i = self.r[self.ip] if self.hacked and self.i == 1 and max(self.r) >",
"[[a, int(b), int(c), int(d)] for a, b, c, d in lines] return ip,",
"a, b, c) self.r[self.ip] += 1 self.i = self.r[self.ip] if self.hacked and self.i",
"= [s.split() for s in lines] lines = [[a, int(b), int(c), int(d)] for",
"funcs[opname] self.r[self.ip] = self.i op(self.r, a, b, c) self.r[self.ip] += 1 self.i =",
"= ip self.i = 0 self.d = d self.r = [0] * 6",
"op(self.r, a, b, c) self.r[self.ip] += 1 self.i = self.r[self.ip] if self.hacked and",
"def step(self): opname, a, b, c = self.d[self.i] op = funcs[opname] self.r[self.ip] =",
"a, b, c, d in lines] return ip, lines funcs = all_ops() class",
"\"\"\" --- Day 19: Go With The Flow --- https://adventofcode.com/2018/day/19 \"\"\" import math",
"self.i == 1 and max(self.r) > 5: self.r[0] = sum(divisors(max(self.r))) [][0] def compute(data,",
"n} for i in range(2, int(math.sqrt(n)) + 1): if not n % i:",
"range(2, int(math.sqrt(n)) + 1): if not n % i: divs |= {i, n",
"a, b, c = self.d[self.i] op = funcs[opname] self.r[self.ip] = self.i op(self.r, a,",
"1): if not n % i: divs |= {i, n // i} return",
"r0=0, hack=False): ip, lines = parsed(data) comp = Comp(ip, lines, r0=r0, hacked=hack) while",
"divs |= {i, n // i} return divs print(\"part a:\", compute(data, r0=0, hack=True))",
"c) self.r[self.ip] += 1 self.i = self.r[self.ip] if self.hacked and self.i == 1",
"= self.d[self.i] op = funcs[opname] self.r[self.ip] = self.i op(self.r, a, b, c) self.r[self.ip]",
"self.r[self.ip] += 1 self.i = self.r[self.ip] if self.hacked and self.i == 1 and",
"With The Flow --- https://adventofcode.com/2018/day/19 \"\"\" import math from aocd import data from",
"def compute(data, r0=0, hack=False): ip, lines = parsed(data) comp = Comp(ip, lines, r0=r0,",
"self.i op(self.r, a, b, c) self.r[self.ip] += 1 self.i = self.r[self.ip] if self.hacked",
"+= 1 self.i = self.r[self.ip] if self.hacked and self.i == 1 and max(self.r)",
"r0, hacked): self.hacked = hacked self.ip = ip self.i = 0 self.d =",
"ip, d, r0, hacked): self.hacked = hacked self.ip = ip self.i = 0",
"hacked self.ip = ip self.i = 0 self.d = d self.r = [0]",
"= r0 def step(self): opname, a, b, c = self.d[self.i] op = funcs[opname]",
"step(self): opname, a, b, c = self.d[self.i] op = funcs[opname] self.r[self.ip] = self.i",
"self.ip = ip self.i = 0 self.d = d self.r = [0] *",
"not n % i: divs |= {i, n // i} return divs print(\"part"
] |
[
"'verbose_name_plural': 'Carta de Juegos', }, ), migrations.AddField( model_name='board', name='game', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='game.Game'), ), ]",
"'verbose_name': 'Tablero', 'verbose_name_plural': 'Tableros', }, ), migrations.CreateModel( name='Game', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,",
"models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], options={ 'verbose_name': 'Juego', 'verbose_name_plural': 'Juegos', }, ), migrations.CreateModel(",
"django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('deck', '0001_initial'), ] operations",
"fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], options={ 'verbose_name': 'Juego', 'verbose_name_plural': 'Juegos', },",
"serialize=False, verbose_name='ID')), ('position', models.IntegerField(verbose_name='posicion')), ('board', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='cards', to='game.Board')), ('card', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='deck.Card')), ], options={",
"verbose_name='jugador')), ], options={ 'verbose_name': 'Tablero', 'verbose_name_plural': 'Tableros', }, ), migrations.CreateModel( name='Game', fields=[ ('id',",
"options={ 'verbose_name': 'Juego', 'verbose_name_plural': 'Juegos', }, ), migrations.CreateModel( name='GameCard', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True,",
"'verbose_name_plural': 'Juegos', }, ), migrations.CreateModel( name='GameCard', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('position',",
"2019-09-11 03:40 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial =",
"'Carta de Juego', 'verbose_name_plural': 'Carta de Juegos', }, ), migrations.AddField( model_name='board', name='game', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,",
"= [ migrations.CreateModel( name='Board', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('player', models.CharField(max_length=50, verbose_name='jugador')),",
"] operations = [ migrations.CreateModel( name='Board', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('player',",
"models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='deck.Card')), ], options={ 'verbose_name': 'Carta de Juego', 'verbose_name_plural': 'Carta de Juegos', },",
"}, ), migrations.CreateModel( name='Game', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], options={ 'verbose_name':",
"to='game.Board')), ('card', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='deck.Card')), ], options={ 'verbose_name': 'Carta de Juego', 'verbose_name_plural': 'Carta de",
"('card', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='deck.Card')), ], options={ 'verbose_name': 'Carta de Juego', 'verbose_name_plural': 'Carta de Juegos',",
"serialize=False, verbose_name='ID')), ('player', models.CharField(max_length=50, verbose_name='jugador')), ], options={ 'verbose_name': 'Tablero', 'verbose_name_plural': 'Tableros', }, ),",
"= [ ('deck', '0001_initial'), ] operations = [ migrations.CreateModel( name='Board', fields=[ ('id', models.AutoField(auto_created=True,",
"models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('player', models.CharField(max_length=50, verbose_name='jugador')), ], options={ 'verbose_name': 'Tablero', 'verbose_name_plural': 'Tableros',",
"options={ 'verbose_name': 'Carta de Juego', 'verbose_name_plural': 'Carta de Juegos', }, ), migrations.AddField( model_name='board',",
"models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('deck', '0001_initial'),",
"migrations.CreateModel( name='Board', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('player', models.CharField(max_length=50, verbose_name='jugador')), ], options={",
"Juego', 'verbose_name_plural': 'Carta de Juegos', }, ), migrations.AddField( model_name='board', name='game', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='game.Game'), ),",
"('board', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='cards', to='game.Board')), ('card', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='deck.Card')), ], options={ 'verbose_name': 'Carta de Juego',",
"models.CharField(max_length=50, verbose_name='jugador')), ], options={ 'verbose_name': 'Tablero', 'verbose_name_plural': 'Tableros', }, ), migrations.CreateModel( name='Game', fields=[",
"'0001_initial'), ] operations = [ migrations.CreateModel( name='Board', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),",
"'verbose_name': 'Carta de Juego', 'verbose_name_plural': 'Carta de Juegos', }, ), migrations.AddField( model_name='board', name='game',",
"options={ 'verbose_name': 'Tablero', 'verbose_name_plural': 'Tableros', }, ), migrations.CreateModel( name='Game', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True,",
"'Tablero', 'verbose_name_plural': 'Tableros', }, ), migrations.CreateModel( name='Game', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),",
"fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('player', models.CharField(max_length=50, verbose_name='jugador')), ], options={ 'verbose_name': 'Tablero',",
"migrations.CreateModel( name='GameCard', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('position', models.IntegerField(verbose_name='posicion')), ('board', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='cards',",
"import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('deck', '0001_initial'), ]",
"migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('deck',",
"03:40 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True",
"= True dependencies = [ ('deck', '0001_initial'), ] operations = [ migrations.CreateModel( name='Board',",
"dependencies = [ ('deck', '0001_initial'), ] operations = [ migrations.CreateModel( name='Board', fields=[ ('id',",
"'Tableros', }, ), migrations.CreateModel( name='Game', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], options={",
"], options={ 'verbose_name': 'Juego', 'verbose_name_plural': 'Juegos', }, ), migrations.CreateModel( name='GameCard', fields=[ ('id', models.AutoField(auto_created=True,",
"migrations.CreateModel( name='Game', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], options={ 'verbose_name': 'Juego', 'verbose_name_plural':",
"name='Game', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], options={ 'verbose_name': 'Juego', 'verbose_name_plural': 'Juegos',",
"models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='cards', to='game.Board')), ('card', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='deck.Card')), ], options={ 'verbose_name': 'Carta de Juego', 'verbose_name_plural':",
"], options={ 'verbose_name': 'Carta de Juego', 'verbose_name_plural': 'Carta de Juegos', }, ), migrations.AddField(",
"by Django 2.2.4 on 2019-09-11 03:40 from django.db import migrations, models import django.db.models.deletion",
"from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies",
"fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('position', models.IntegerField(verbose_name='posicion')), ('board', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='cards', to='game.Board')), ('card',",
"'verbose_name_plural': 'Tableros', }, ), migrations.CreateModel( name='Game', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ],",
"), migrations.CreateModel( name='GameCard', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('position', models.IntegerField(verbose_name='posicion')), ('board', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,",
"# Generated by Django 2.2.4 on 2019-09-11 03:40 from django.db import migrations, models",
"[ ('deck', '0001_initial'), ] operations = [ migrations.CreateModel( name='Board', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True,",
"('position', models.IntegerField(verbose_name='posicion')), ('board', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='cards', to='game.Board')), ('card', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='deck.Card')), ], options={ 'verbose_name': 'Carta",
"'Juego', 'verbose_name_plural': 'Juegos', }, ), migrations.CreateModel( name='GameCard', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),",
"import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [",
"primary_key=True, serialize=False, verbose_name='ID')), ('position', models.IntegerField(verbose_name='posicion')), ('board', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='cards', to='game.Board')), ('card', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='deck.Card')), ],",
"2.2.4 on 2019-09-11 03:40 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):",
"initial = True dependencies = [ ('deck', '0001_initial'), ] operations = [ migrations.CreateModel(",
"django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies =",
"primary_key=True, serialize=False, verbose_name='ID')), ], options={ 'verbose_name': 'Juego', 'verbose_name_plural': 'Juegos', }, ), migrations.CreateModel( name='GameCard',",
"Migration(migrations.Migration): initial = True dependencies = [ ('deck', '0001_initial'), ] operations = [",
"to='deck.Card')), ], options={ 'verbose_name': 'Carta de Juego', 'verbose_name_plural': 'Carta de Juegos', }, ),",
"name='Board', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('player', models.CharField(max_length=50, verbose_name='jugador')), ], options={ 'verbose_name':",
"('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('position', models.IntegerField(verbose_name='posicion')), ('board', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='cards', to='game.Board')), ('card', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,",
"name='GameCard', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('position', models.IntegerField(verbose_name='posicion')), ('board', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='cards', to='game.Board')),",
"[ migrations.CreateModel( name='Board', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('player', models.CharField(max_length=50, verbose_name='jugador')), ],",
"serialize=False, verbose_name='ID')), ], options={ 'verbose_name': 'Juego', 'verbose_name_plural': 'Juegos', }, ), migrations.CreateModel( name='GameCard', fields=[",
"models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('position', models.IntegerField(verbose_name='posicion')), ('board', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='cards', to='game.Board')), ('card', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='deck.Card')),",
"True dependencies = [ ('deck', '0001_initial'), ] operations = [ migrations.CreateModel( name='Board', fields=[",
"), migrations.CreateModel( name='Game', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], options={ 'verbose_name': 'Juego',",
"models.IntegerField(verbose_name='posicion')), ('board', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='cards', to='game.Board')), ('card', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='deck.Card')), ], options={ 'verbose_name': 'Carta de",
"on 2019-09-11 03:40 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial",
"('deck', '0001_initial'), ] operations = [ migrations.CreateModel( name='Board', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,",
"related_name='cards', to='game.Board')), ('card', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='deck.Card')), ], options={ 'verbose_name': 'Carta de Juego', 'verbose_name_plural': 'Carta",
"de Juego', 'verbose_name_plural': 'Carta de Juegos', }, ), migrations.AddField( model_name='board', name='game', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='game.Game'),",
"verbose_name='ID')), ('player', models.CharField(max_length=50, verbose_name='jugador')), ], options={ 'verbose_name': 'Tablero', 'verbose_name_plural': 'Tableros', }, ), migrations.CreateModel(",
"Django 2.2.4 on 2019-09-11 03:40 from django.db import migrations, models import django.db.models.deletion class",
"verbose_name='ID')), ('position', models.IntegerField(verbose_name='posicion')), ('board', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='cards', to='game.Board')), ('card', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='deck.Card')), ], options={ 'verbose_name':",
"class Migration(migrations.Migration): initial = True dependencies = [ ('deck', '0001_initial'), ] operations =",
"verbose_name='ID')), ], options={ 'verbose_name': 'Juego', 'verbose_name_plural': 'Juegos', }, ), migrations.CreateModel( name='GameCard', fields=[ ('id',",
"('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], options={ 'verbose_name': 'Juego', 'verbose_name_plural': 'Juegos', }, ),",
"('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('player', models.CharField(max_length=50, verbose_name='jugador')), ], options={ 'verbose_name': 'Tablero', 'verbose_name_plural':",
"], options={ 'verbose_name': 'Tablero', 'verbose_name_plural': 'Tableros', }, ), migrations.CreateModel( name='Game', fields=[ ('id', models.AutoField(auto_created=True,",
"primary_key=True, serialize=False, verbose_name='ID')), ('player', models.CharField(max_length=50, verbose_name='jugador')), ], options={ 'verbose_name': 'Tablero', 'verbose_name_plural': 'Tableros', },",
"('player', models.CharField(max_length=50, verbose_name='jugador')), ], options={ 'verbose_name': 'Tablero', 'verbose_name_plural': 'Tableros', }, ), migrations.CreateModel( name='Game',",
"'Juegos', }, ), migrations.CreateModel( name='GameCard', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('position', models.IntegerField(verbose_name='posicion')),",
"Generated by Django 2.2.4 on 2019-09-11 03:40 from django.db import migrations, models import",
"}, ), migrations.CreateModel( name='GameCard', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('position', models.IntegerField(verbose_name='posicion')), ('board',",
"'verbose_name': 'Juego', 'verbose_name_plural': 'Juegos', }, ), migrations.CreateModel( name='GameCard', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,",
"operations = [ migrations.CreateModel( name='Board', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('player', models.CharField(max_length=50,"
] |
[
"<filename>BasicRead.py<gh_stars>0 from arduino import grove_si114x import time SI1145 = grove_si114x() while True: print('Visible",
"arduino import grove_si114x import time SI1145 = grove_si114x() while True: print('Visible %03d UV",
"= grove_si114x() while True: print('Visible %03d UV %.2f IR %03d' % (SI1145.Visible ,",
"%03d UV %.2f IR %03d' % (SI1145.Visible , SI1145.UV/100 , SI1145.IR),end=\" \") print('\\r',",
"grove_si114x() while True: print('Visible %03d UV %.2f IR %03d' % (SI1145.Visible , SI1145.UV/100",
"import time SI1145 = grove_si114x() while True: print('Visible %03d UV %.2f IR %03d'",
"time SI1145 = grove_si114x() while True: print('Visible %03d UV %.2f IR %03d' %",
"UV %.2f IR %03d' % (SI1145.Visible , SI1145.UV/100 , SI1145.IR),end=\" \") print('\\r', end='')",
"while True: print('Visible %03d UV %.2f IR %03d' % (SI1145.Visible , SI1145.UV/100 ,",
"import grove_si114x import time SI1145 = grove_si114x() while True: print('Visible %03d UV %.2f",
"SI1145 = grove_si114x() while True: print('Visible %03d UV %.2f IR %03d' % (SI1145.Visible",
"%.2f IR %03d' % (SI1145.Visible , SI1145.UV/100 , SI1145.IR),end=\" \") print('\\r', end='') time.sleep(0.5)",
"True: print('Visible %03d UV %.2f IR %03d' % (SI1145.Visible , SI1145.UV/100 , SI1145.IR),end=\"",
"from arduino import grove_si114x import time SI1145 = grove_si114x() while True: print('Visible %03d",
"grove_si114x import time SI1145 = grove_si114x() while True: print('Visible %03d UV %.2f IR",
"print('Visible %03d UV %.2f IR %03d' % (SI1145.Visible , SI1145.UV/100 , SI1145.IR),end=\" \")"
] |
[
"tof.ranging_mode = RANGING_MODE_AUTONOMOUS tof.integration_time_ms = 10 tof.start_ranging((DATA_DISTANCE_MM, DATA_TARGET_STATUS)) for _ in range(10): lightsleep()",
"from vl53l5cx import RESOLUTION_4X4, RANGING_MODE_AUTONOMOUS, POWER_MODE_SLEEP def main(): wake_on_ext1([Pin(13, Pin.IN)], WAKEUP_ALL_LOW) trigger =",
"vl53l5cx import RESOLUTION_4X4, RANGING_MODE_AUTONOMOUS, POWER_MODE_SLEEP def main(): wake_on_ext1([Pin(13, Pin.IN)], WAKEUP_ALL_LOW) trigger = Pin(2,",
"# print(ticks_ms()) tof.power_mode = POWER_MODE_WAKEUP lightsleep(1000) # print(ticks_ms()) trigger.value(0) # print(\"done:\", tof.is_alive()) main()",
"from vl53l5cx import DATA_TARGET_STATUS, DATA_DISTANCE_MM, POWER_MODE_WAKEUP from vl53l5cx import RESOLUTION_4X4, RANGING_MODE_AUTONOMOUS, POWER_MODE_SLEEP def",
"Pin.OUT, value=0) bl = Pin(4, Pin.OUT, value=0) button = Pin(0) # while button.value():",
"DATA_TARGET_STATUS, DATA_DISTANCE_MM, POWER_MODE_WAKEUP from vl53l5cx import RESOLUTION_4X4, RANGING_MODE_AUTONOMOUS, POWER_MODE_SLEEP def main(): wake_on_ext1([Pin(13, Pin.IN)],",
"import RESOLUTION_4X4, RANGING_MODE_AUTONOMOUS, POWER_MODE_SLEEP def main(): wake_on_ext1([Pin(13, Pin.IN)], WAKEUP_ALL_LOW) trigger = Pin(2, Pin.OUT,",
"button.value(): # pass trigger.value(1) tof = make_sensor() tof.reset() tof.init() tof.resolution = RESOLUTION_4X4 tof.ranging_freq",
"tof.start_ranging((DATA_DISTANCE_MM, DATA_TARGET_STATUS)) for _ in range(10): lightsleep() results = tof.get_ranging_data() # print(len(results.distance_mm)) tof.integration_time_ms",
"from sensor import make_sensor from vl53l5cx import DATA_TARGET_STATUS, DATA_DISTANCE_MM, POWER_MODE_WAKEUP from vl53l5cx import",
"lightsleep(1000) # print(ticks_ms()) tof.power_mode = POWER_MODE_WAKEUP lightsleep(1000) # print(ticks_ms()) trigger.value(0) # print(\"done:\", tof.is_alive())",
"DATA_DISTANCE_MM, POWER_MODE_WAKEUP from vl53l5cx import RESOLUTION_4X4, RANGING_MODE_AUTONOMOUS, POWER_MODE_SLEEP def main(): wake_on_ext1([Pin(13, Pin.IN)], WAKEUP_ALL_LOW)",
"sleep, ticks_ms from esp32 import wake_on_ext1, WAKEUP_ALL_LOW from sensor import make_sensor from vl53l5cx",
"RESOLUTION_4X4 tof.ranging_freq = 15 tof.ranging_mode = RANGING_MODE_AUTONOMOUS tof.integration_time_ms = 10 tof.start_ranging((DATA_DISTANCE_MM, DATA_TARGET_STATUS)) for",
"lightsleep() results = tof.get_ranging_data() # print(len(results.distance_mm)) tof.integration_time_ms = 25 for _ in range(10):",
"for _ in range(10): lightsleep() results = tof.get_ranging_data() # print(len(results.distance_mm)) tof.stop_ranging() # print(ticks_ms())",
"time import sleep, ticks_ms from esp32 import wake_on_ext1, WAKEUP_ALL_LOW from sensor import make_sensor",
"range(10): lightsleep() results = tof.get_ranging_data() # print(len(results.distance_mm)) tof.stop_ranging() # print(ticks_ms()) lightsleep(100) tof.power_mode =",
"# print(len(results.distance_mm)) tof.integration_time_ms = 25 for _ in range(10): lightsleep() results = tof.get_ranging_data()",
"= tof.get_ranging_data() # print(len(results.distance_mm)) tof.stop_ranging() # print(ticks_ms()) lightsleep(100) tof.power_mode = POWER_MODE_SLEEP lightsleep(1000) #",
"print(ticks_ms()) lightsleep(100) tof.power_mode = POWER_MODE_SLEEP lightsleep(1000) # print(ticks_ms()) tof.power_mode = POWER_MODE_WAKEUP lightsleep(1000) #",
"= tof.get_ranging_data() # print(len(results.distance_mm)) tof.integration_time_ms = 25 for _ in range(10): lightsleep() results",
"= POWER_MODE_SLEEP lightsleep(1000) # print(ticks_ms()) tof.power_mode = POWER_MODE_WAKEUP lightsleep(1000) # print(ticks_ms()) trigger.value(0) #",
"ticks_ms from esp32 import wake_on_ext1, WAKEUP_ALL_LOW from sensor import make_sensor from vl53l5cx import",
"POWER_MODE_SLEEP def main(): wake_on_ext1([Pin(13, Pin.IN)], WAKEUP_ALL_LOW) trigger = Pin(2, Pin.OUT, value=0) bl =",
"in range(10): lightsleep() results = tof.get_ranging_data() # print(len(results.distance_mm)) tof.integration_time_ms = 25 for _",
"tof.power_mode = POWER_MODE_SLEEP lightsleep(1000) # print(ticks_ms()) tof.power_mode = POWER_MODE_WAKEUP lightsleep(1000) # print(ticks_ms()) trigger.value(0)",
"Pin(4, Pin.OUT, value=0) button = Pin(0) # while button.value(): # pass trigger.value(1) tof",
"25 for _ in range(10): lightsleep() results = tof.get_ranging_data() # print(len(results.distance_mm)) tof.stop_ranging() #",
"tof.reset() tof.init() tof.resolution = RESOLUTION_4X4 tof.ranging_freq = 15 tof.ranging_mode = RANGING_MODE_AUTONOMOUS tof.integration_time_ms =",
"# MicroPython from machine import lightsleep, Pin from time import sleep, ticks_ms from",
"POWER_MODE_SLEEP lightsleep(1000) # print(ticks_ms()) tof.power_mode = POWER_MODE_WAKEUP lightsleep(1000) # print(ticks_ms()) trigger.value(0) # print(\"done:\",",
"10 tof.start_ranging((DATA_DISTANCE_MM, DATA_TARGET_STATUS)) for _ in range(10): lightsleep() results = tof.get_ranging_data() # print(len(results.distance_mm))",
"lightsleep, Pin from time import sleep, ticks_ms from esp32 import wake_on_ext1, WAKEUP_ALL_LOW from",
"tof.ranging_freq = 15 tof.ranging_mode = RANGING_MODE_AUTONOMOUS tof.integration_time_ms = 10 tof.start_ranging((DATA_DISTANCE_MM, DATA_TARGET_STATUS)) for _",
"= RANGING_MODE_AUTONOMOUS tof.integration_time_ms = 10 tof.start_ranging((DATA_DISTANCE_MM, DATA_TARGET_STATUS)) for _ in range(10): lightsleep() results",
"tof.get_ranging_data() # print(len(results.distance_mm)) tof.stop_ranging() # print(ticks_ms()) lightsleep(100) tof.power_mode = POWER_MODE_SLEEP lightsleep(1000) # print(ticks_ms())",
"lightsleep() results = tof.get_ranging_data() # print(len(results.distance_mm)) tof.stop_ranging() # print(ticks_ms()) lightsleep(100) tof.power_mode = POWER_MODE_SLEEP",
"results = tof.get_ranging_data() # print(len(results.distance_mm)) tof.integration_time_ms = 25 for _ in range(10): lightsleep()",
"tof.integration_time_ms = 25 for _ in range(10): lightsleep() results = tof.get_ranging_data() # print(len(results.distance_mm))",
"# pass trigger.value(1) tof = make_sensor() tof.reset() tof.init() tof.resolution = RESOLUTION_4X4 tof.ranging_freq =",
"bl = Pin(4, Pin.OUT, value=0) button = Pin(0) # while button.value(): # pass",
"WAKEUP_ALL_LOW from sensor import make_sensor from vl53l5cx import DATA_TARGET_STATUS, DATA_DISTANCE_MM, POWER_MODE_WAKEUP from vl53l5cx",
"_ in range(10): lightsleep() results = tof.get_ranging_data() # print(len(results.distance_mm)) tof.integration_time_ms = 25 for",
"# print(len(results.distance_mm)) tof.stop_ranging() # print(ticks_ms()) lightsleep(100) tof.power_mode = POWER_MODE_SLEEP lightsleep(1000) # print(ticks_ms()) tof.power_mode",
"make_sensor() tof.reset() tof.init() tof.resolution = RESOLUTION_4X4 tof.ranging_freq = 15 tof.ranging_mode = RANGING_MODE_AUTONOMOUS tof.integration_time_ms",
"import make_sensor from vl53l5cx import DATA_TARGET_STATUS, DATA_DISTANCE_MM, POWER_MODE_WAKEUP from vl53l5cx import RESOLUTION_4X4, RANGING_MODE_AUTONOMOUS,",
"value=0) bl = Pin(4, Pin.OUT, value=0) button = Pin(0) # while button.value(): #",
"= Pin(4, Pin.OUT, value=0) button = Pin(0) # while button.value(): # pass trigger.value(1)",
"esp32 import wake_on_ext1, WAKEUP_ALL_LOW from sensor import make_sensor from vl53l5cx import DATA_TARGET_STATUS, DATA_DISTANCE_MM,",
"wake_on_ext1, WAKEUP_ALL_LOW from sensor import make_sensor from vl53l5cx import DATA_TARGET_STATUS, DATA_DISTANCE_MM, POWER_MODE_WAKEUP from",
"pass trigger.value(1) tof = make_sensor() tof.reset() tof.init() tof.resolution = RESOLUTION_4X4 tof.ranging_freq = 15",
"for _ in range(10): lightsleep() results = tof.get_ranging_data() # print(len(results.distance_mm)) tof.integration_time_ms = 25",
"= RESOLUTION_4X4 tof.ranging_freq = 15 tof.ranging_mode = RANGING_MODE_AUTONOMOUS tof.integration_time_ms = 10 tof.start_ranging((DATA_DISTANCE_MM, DATA_TARGET_STATUS))",
"Pin from time import sleep, ticks_ms from esp32 import wake_on_ext1, WAKEUP_ALL_LOW from sensor",
"= 25 for _ in range(10): lightsleep() results = tof.get_ranging_data() # print(len(results.distance_mm)) tof.stop_ranging()",
"Pin(2, Pin.OUT, value=0) bl = Pin(4, Pin.OUT, value=0) button = Pin(0) # while",
"= Pin(2, Pin.OUT, value=0) bl = Pin(4, Pin.OUT, value=0) button = Pin(0) #",
"value=0) button = Pin(0) # while button.value(): # pass trigger.value(1) tof = make_sensor()",
"import sleep, ticks_ms from esp32 import wake_on_ext1, WAKEUP_ALL_LOW from sensor import make_sensor from",
"import DATA_TARGET_STATUS, DATA_DISTANCE_MM, POWER_MODE_WAKEUP from vl53l5cx import RESOLUTION_4X4, RANGING_MODE_AUTONOMOUS, POWER_MODE_SLEEP def main(): wake_on_ext1([Pin(13,",
"RANGING_MODE_AUTONOMOUS tof.integration_time_ms = 10 tof.start_ranging((DATA_DISTANCE_MM, DATA_TARGET_STATUS)) for _ in range(10): lightsleep() results =",
"15 tof.ranging_mode = RANGING_MODE_AUTONOMOUS tof.integration_time_ms = 10 tof.start_ranging((DATA_DISTANCE_MM, DATA_TARGET_STATUS)) for _ in range(10):",
"make_sensor from vl53l5cx import DATA_TARGET_STATUS, DATA_DISTANCE_MM, POWER_MODE_WAKEUP from vl53l5cx import RESOLUTION_4X4, RANGING_MODE_AUTONOMOUS, POWER_MODE_SLEEP",
"tof.resolution = RESOLUTION_4X4 tof.ranging_freq = 15 tof.ranging_mode = RANGING_MODE_AUTONOMOUS tof.integration_time_ms = 10 tof.start_ranging((DATA_DISTANCE_MM,",
"_ in range(10): lightsleep() results = tof.get_ranging_data() # print(len(results.distance_mm)) tof.stop_ranging() # print(ticks_ms()) lightsleep(100)",
"# print(ticks_ms()) lightsleep(100) tof.power_mode = POWER_MODE_SLEEP lightsleep(1000) # print(ticks_ms()) tof.power_mode = POWER_MODE_WAKEUP lightsleep(1000)",
"= make_sensor() tof.reset() tof.init() tof.resolution = RESOLUTION_4X4 tof.ranging_freq = 15 tof.ranging_mode = RANGING_MODE_AUTONOMOUS",
"range(10): lightsleep() results = tof.get_ranging_data() # print(len(results.distance_mm)) tof.integration_time_ms = 25 for _ in",
"RESOLUTION_4X4, RANGING_MODE_AUTONOMOUS, POWER_MODE_SLEEP def main(): wake_on_ext1([Pin(13, Pin.IN)], WAKEUP_ALL_LOW) trigger = Pin(2, Pin.OUT, value=0)",
"trigger = Pin(2, Pin.OUT, value=0) bl = Pin(4, Pin.OUT, value=0) button = Pin(0)",
"WAKEUP_ALL_LOW) trigger = Pin(2, Pin.OUT, value=0) bl = Pin(4, Pin.OUT, value=0) button =",
"from machine import lightsleep, Pin from time import sleep, ticks_ms from esp32 import",
"tof.stop_ranging() # print(ticks_ms()) lightsleep(100) tof.power_mode = POWER_MODE_SLEEP lightsleep(1000) # print(ticks_ms()) tof.power_mode = POWER_MODE_WAKEUP",
"Pin(0) # while button.value(): # pass trigger.value(1) tof = make_sensor() tof.reset() tof.init() tof.resolution",
"tof.integration_time_ms = 10 tof.start_ranging((DATA_DISTANCE_MM, DATA_TARGET_STATUS)) for _ in range(10): lightsleep() results = tof.get_ranging_data()",
"wake_on_ext1([Pin(13, Pin.IN)], WAKEUP_ALL_LOW) trigger = Pin(2, Pin.OUT, value=0) bl = Pin(4, Pin.OUT, value=0)",
"trigger.value(1) tof = make_sensor() tof.reset() tof.init() tof.resolution = RESOLUTION_4X4 tof.ranging_freq = 15 tof.ranging_mode",
"<gh_stars>1-10 # MicroPython from machine import lightsleep, Pin from time import sleep, ticks_ms",
"tof.init() tof.resolution = RESOLUTION_4X4 tof.ranging_freq = 15 tof.ranging_mode = RANGING_MODE_AUTONOMOUS tof.integration_time_ms = 10",
"main(): wake_on_ext1([Pin(13, Pin.IN)], WAKEUP_ALL_LOW) trigger = Pin(2, Pin.OUT, value=0) bl = Pin(4, Pin.OUT,",
"sensor import make_sensor from vl53l5cx import DATA_TARGET_STATUS, DATA_DISTANCE_MM, POWER_MODE_WAKEUP from vl53l5cx import RESOLUTION_4X4,",
"RANGING_MODE_AUTONOMOUS, POWER_MODE_SLEEP def main(): wake_on_ext1([Pin(13, Pin.IN)], WAKEUP_ALL_LOW) trigger = Pin(2, Pin.OUT, value=0) bl",
"Pin.IN)], WAKEUP_ALL_LOW) trigger = Pin(2, Pin.OUT, value=0) bl = Pin(4, Pin.OUT, value=0) button",
"def main(): wake_on_ext1([Pin(13, Pin.IN)], WAKEUP_ALL_LOW) trigger = Pin(2, Pin.OUT, value=0) bl = Pin(4,",
"= 15 tof.ranging_mode = RANGING_MODE_AUTONOMOUS tof.integration_time_ms = 10 tof.start_ranging((DATA_DISTANCE_MM, DATA_TARGET_STATUS)) for _ in",
"import lightsleep, Pin from time import sleep, ticks_ms from esp32 import wake_on_ext1, WAKEUP_ALL_LOW",
"results = tof.get_ranging_data() # print(len(results.distance_mm)) tof.stop_ranging() # print(ticks_ms()) lightsleep(100) tof.power_mode = POWER_MODE_SLEEP lightsleep(1000)",
"= Pin(0) # while button.value(): # pass trigger.value(1) tof = make_sensor() tof.reset() tof.init()",
"while button.value(): # pass trigger.value(1) tof = make_sensor() tof.reset() tof.init() tof.resolution = RESOLUTION_4X4",
"= 10 tof.start_ranging((DATA_DISTANCE_MM, DATA_TARGET_STATUS)) for _ in range(10): lightsleep() results = tof.get_ranging_data() #",
"in range(10): lightsleep() results = tof.get_ranging_data() # print(len(results.distance_mm)) tof.stop_ranging() # print(ticks_ms()) lightsleep(100) tof.power_mode",
"print(len(results.distance_mm)) tof.integration_time_ms = 25 for _ in range(10): lightsleep() results = tof.get_ranging_data() #",
"from time import sleep, ticks_ms from esp32 import wake_on_ext1, WAKEUP_ALL_LOW from sensor import",
"Pin.OUT, value=0) button = Pin(0) # while button.value(): # pass trigger.value(1) tof =",
"lightsleep(100) tof.power_mode = POWER_MODE_SLEEP lightsleep(1000) # print(ticks_ms()) tof.power_mode = POWER_MODE_WAKEUP lightsleep(1000) # print(ticks_ms())",
"MicroPython from machine import lightsleep, Pin from time import sleep, ticks_ms from esp32",
"from esp32 import wake_on_ext1, WAKEUP_ALL_LOW from sensor import make_sensor from vl53l5cx import DATA_TARGET_STATUS,",
"import wake_on_ext1, WAKEUP_ALL_LOW from sensor import make_sensor from vl53l5cx import DATA_TARGET_STATUS, DATA_DISTANCE_MM, POWER_MODE_WAKEUP",
"# while button.value(): # pass trigger.value(1) tof = make_sensor() tof.reset() tof.init() tof.resolution =",
"print(len(results.distance_mm)) tof.stop_ranging() # print(ticks_ms()) lightsleep(100) tof.power_mode = POWER_MODE_SLEEP lightsleep(1000) # print(ticks_ms()) tof.power_mode =",
"vl53l5cx import DATA_TARGET_STATUS, DATA_DISTANCE_MM, POWER_MODE_WAKEUP from vl53l5cx import RESOLUTION_4X4, RANGING_MODE_AUTONOMOUS, POWER_MODE_SLEEP def main():",
"tof.get_ranging_data() # print(len(results.distance_mm)) tof.integration_time_ms = 25 for _ in range(10): lightsleep() results =",
"machine import lightsleep, Pin from time import sleep, ticks_ms from esp32 import wake_on_ext1,",
"tof = make_sensor() tof.reset() tof.init() tof.resolution = RESOLUTION_4X4 tof.ranging_freq = 15 tof.ranging_mode =",
"DATA_TARGET_STATUS)) for _ in range(10): lightsleep() results = tof.get_ranging_data() # print(len(results.distance_mm)) tof.integration_time_ms =",
"button = Pin(0) # while button.value(): # pass trigger.value(1) tof = make_sensor() tof.reset()",
"POWER_MODE_WAKEUP from vl53l5cx import RESOLUTION_4X4, RANGING_MODE_AUTONOMOUS, POWER_MODE_SLEEP def main(): wake_on_ext1([Pin(13, Pin.IN)], WAKEUP_ALL_LOW) trigger"
] |
[
"template is compiled once and read from # memory instead of reading from",
"from # memory instead of reading from disk on each load. TEMPLATE_LOADERS =",
"reading from disk on each load. TEMPLATE_LOADERS = ( ('django.template.loaders.cached.Loader', ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader',",
"CONTACTS = { 'support_email': 'GlucoseTracker.net <<EMAIL>>', 'admin_email': '<EMAIL>', 'info_email': 'GlucoseTracker.net <<EMAIL>>', } #",
"SECRET_KEY = os.environ['DJANGO_SECRET_KEY'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'glucosetracker', 'USER':",
"{ 'support_email': 'GlucoseTracker.net <<EMAIL>>', 'admin_email': '<EMAIL>', 'info_email': 'GlucoseTracker.net <<EMAIL>>', } # Subscribers app",
"os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] AWS_STORAGE_BUCKET_NAME = 'glucosetracker-assets' AWS_QUERYSTRING_AUTH = False MEDIA_URL = '//%s.s3.amazonaws.com/%s/'",
"'glucosetracker', 'USER': os.environ['DATABASE_USER'], 'PASSWORD': os.environ['DATABASE_PASSWORD'], 'HOST': 'localhost', 'PORT': '', } } # 3rd-party",
"= os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] AWS_STORAGE_BUCKET_NAME = 'glucosetracker-assets' AWS_QUERYSTRING_AUTH = False MEDIA_URL =",
"# memory instead of reading from disk on each load. TEMPLATE_LOADERS = (",
"= 'ra-52fffdf9456ec7d2' # The 'From:' header of admin-related emails. DEFAULT_FROM_EMAIL = '<EMAIL>' ADMINS",
"Make this unique, and don't share it with anybody. SECRET_KEY = os.environ['DJANGO_SECRET_KEY'] DATABASES",
"names that are valid for this site; required if DEBUG is False #",
"it with anybody. SECRET_KEY = os.environ['DJANGO_SECRET_KEY'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2',",
"'localhost', 'PORT': '', } } # 3rd-party apps tracking IDs. INTERCOM_APP_ID = 'a6d0326564469dfd7f7d9b1bfc909ee3815a85a8'",
"('Local Admin', '<EMAIL>'), ) MANAGERS = ADMINS CONTACTS = { 'support_email': 'GlucoseTracker.net <<EMAIL>>',",
"app settings SEND_SUBSCRIBERS_EMAIL_CONFIRMATION = True # Django-storages settings DEFAULT_FILE_STORAGE = 'core.s3utils.MediaRootS3BotoStorage' AWS_ACCESS_KEY_ID =",
"is compiled once and read from # memory instead of reading from disk",
"} # Subscribers app settings SEND_SUBSCRIBERS_EMAIL_CONFIRMATION = True # Django-storages settings DEFAULT_FILE_STORAGE =",
"TEMPLATE_DEBUG = DEBUG # Use the cached template loader so template is compiled",
"'ra-52fffdf9456ec7d2' # The 'From:' header of admin-related emails. DEFAULT_FROM_EMAIL = '<EMAIL>' ADMINS =",
"instead of reading from disk on each load. TEMPLATE_LOADERS = ( ('django.template.loaders.cached.Loader', (",
"Hosts/domain names that are valid for this site; required if DEBUG is False",
"'admin_email': '<EMAIL>', 'info_email': 'GlucoseTracker.net <<EMAIL>>', } # Subscribers app settings SEND_SUBSCRIBERS_EMAIL_CONFIRMATION = True",
"'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', )), ) # Hosts/domain names that are valid for this site;",
".base import * DEBUG = False TEMPLATE_DEBUG = DEBUG # Use the cached",
"settings SEND_SUBSCRIBERS_EMAIL_CONFIRMATION = True # Django-storages settings DEFAULT_FILE_STORAGE = 'core.s3utils.MediaRootS3BotoStorage' AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID']",
"Subscribers app settings SEND_SUBSCRIBERS_EMAIL_CONFIRMATION = True # Django-storages settings DEFAULT_FILE_STORAGE = 'core.s3utils.MediaRootS3BotoStorage' AWS_ACCESS_KEY_ID",
"header of admin-related emails. DEFAULT_FROM_EMAIL = '<EMAIL>' ADMINS = ( ('Local Admin', '<EMAIL>'),",
"this unique, and don't share it with anybody. SECRET_KEY = os.environ['DJANGO_SECRET_KEY'] DATABASES =",
"= ( ('Local Admin', '<EMAIL>'), ) MANAGERS = ADMINS CONTACTS = { 'support_email':",
"'<EMAIL>'), ) MANAGERS = ADMINS CONTACTS = { 'support_email': 'GlucoseTracker.net <<EMAIL>>', 'admin_email': '<EMAIL>',",
"if DEBUG is False # See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts ALLOWED_HOSTS = ['.glucosetracker.net'] # Make this",
"and don't share it with anybody. SECRET_KEY = os.environ['DJANGO_SECRET_KEY'] DATABASES = { 'default':",
"'a6d0326564469dfd7f7d9b1bfc909ee3815a85a8' GOOGLE_ANALYTICS_TRACKING_ID = 'UA-45698014-1' ADDTHIS_PUBLISHER_ID = 'ra-52fffdf9456ec7d2' # The 'From:' header of admin-related",
"os.environ['AWS_SECRET_ACCESS_KEY'] AWS_STORAGE_BUCKET_NAME = 'glucosetracker-assets' AWS_QUERYSTRING_AUTH = False MEDIA_URL = '//%s.s3.amazonaws.com/%s/' % (AWS_STORAGE_BUCKET_NAME, MEDIA_ROOT)",
"See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts ALLOWED_HOSTS = ['.glucosetracker.net'] # Make this unique, and don't share it",
"site; required if DEBUG is False # See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts ALLOWED_HOSTS = ['.glucosetracker.net'] #",
"so template is compiled once and read from # memory instead of reading",
"tracking IDs. INTERCOM_APP_ID = 'a6d0326564469dfd7f7d9b1bfc909ee3815a85a8' GOOGLE_ANALYTICS_TRACKING_ID = 'UA-45698014-1' ADDTHIS_PUBLISHER_ID = 'ra-52fffdf9456ec7d2' # The",
"AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] AWS_STORAGE_BUCKET_NAME = 'glucosetracker-assets' AWS_QUERYSTRING_AUTH = False MEDIA_URL",
"# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts ALLOWED_HOSTS = ['.glucosetracker.net'] # Make this unique, and don't share",
"'HOST': 'localhost', 'PORT': '', } } # 3rd-party apps tracking IDs. INTERCOM_APP_ID =",
"DEFAULT_FILE_STORAGE = 'core.s3utils.MediaRootS3BotoStorage' AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] AWS_STORAGE_BUCKET_NAME = 'glucosetracker-assets' AWS_QUERYSTRING_AUTH",
"GOOGLE_ANALYTICS_TRACKING_ID = 'UA-45698014-1' ADDTHIS_PUBLISHER_ID = 'ra-52fffdf9456ec7d2' # The 'From:' header of admin-related emails.",
"<<EMAIL>>', 'admin_email': '<EMAIL>', 'info_email': 'GlucoseTracker.net <<EMAIL>>', } # Subscribers app settings SEND_SUBSCRIBERS_EMAIL_CONFIRMATION =",
"DEBUG # Use the cached template loader so template is compiled once and",
"are valid for this site; required if DEBUG is False # See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts",
"False # See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts ALLOWED_HOSTS = ['.glucosetracker.net'] # Make this unique, and don't",
"'PASSWORD': os.environ['DATABASE_PASSWORD'], 'HOST': 'localhost', 'PORT': '', } } # 3rd-party apps tracking IDs.",
"True # Django-storages settings DEFAULT_FILE_STORAGE = 'core.s3utils.MediaRootS3BotoStorage' AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY']",
"= True # Django-storages settings DEFAULT_FILE_STORAGE = 'core.s3utils.MediaRootS3BotoStorage' AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY =",
"The 'From:' header of admin-related emails. DEFAULT_FROM_EMAIL = '<EMAIL>' ADMINS = ( ('Local",
"'NAME': 'glucosetracker', 'USER': os.environ['DATABASE_USER'], 'PASSWORD': os.environ['DATABASE_PASSWORD'], 'HOST': 'localhost', 'PORT': '', } } #",
"'UA-45698014-1' ADDTHIS_PUBLISHER_ID = 'ra-52fffdf9456ec7d2' # The 'From:' header of admin-related emails. DEFAULT_FROM_EMAIL =",
"os.environ['DATABASE_PASSWORD'], 'HOST': 'localhost', 'PORT': '', } } # 3rd-party apps tracking IDs. INTERCOM_APP_ID",
"'', } } # 3rd-party apps tracking IDs. INTERCOM_APP_ID = 'a6d0326564469dfd7f7d9b1bfc909ee3815a85a8' GOOGLE_ANALYTICS_TRACKING_ID =",
"IDs. INTERCOM_APP_ID = 'a6d0326564469dfd7f7d9b1bfc909ee3815a85a8' GOOGLE_ANALYTICS_TRACKING_ID = 'UA-45698014-1' ADDTHIS_PUBLISHER_ID = 'ra-52fffdf9456ec7d2' # The 'From:'",
"'USER': os.environ['DATABASE_USER'], 'PASSWORD': os.environ['DATABASE_PASSWORD'], 'HOST': 'localhost', 'PORT': '', } } # 3rd-party apps",
"template loader so template is compiled once and read from # memory instead",
"disk on each load. TEMPLATE_LOADERS = ( ('django.template.loaders.cached.Loader', ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', )), )",
"don't share it with anybody. SECRET_KEY = os.environ['DJANGO_SECRET_KEY'] DATABASES = { 'default': {",
"read from # memory instead of reading from disk on each load. TEMPLATE_LOADERS",
"'info_email': 'GlucoseTracker.net <<EMAIL>>', } # Subscribers app settings SEND_SUBSCRIBERS_EMAIL_CONFIRMATION = True # Django-storages",
"'GlucoseTracker.net <<EMAIL>>', 'admin_email': '<EMAIL>', 'info_email': 'GlucoseTracker.net <<EMAIL>>', } # Subscribers app settings SEND_SUBSCRIBERS_EMAIL_CONFIRMATION",
"= ( ('django.template.loaders.cached.Loader', ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', )), ) # Hosts/domain names that are",
"'GlucoseTracker.net <<EMAIL>>', } # Subscribers app settings SEND_SUBSCRIBERS_EMAIL_CONFIRMATION = True # Django-storages settings",
"ALLOWED_HOSTS = ['.glucosetracker.net'] # Make this unique, and don't share it with anybody.",
"'PORT': '', } } # 3rd-party apps tracking IDs. INTERCOM_APP_ID = 'a6d0326564469dfd7f7d9b1bfc909ee3815a85a8' GOOGLE_ANALYTICS_TRACKING_ID",
"'From:' header of admin-related emails. DEFAULT_FROM_EMAIL = '<EMAIL>' ADMINS = ( ('Local Admin',",
"SEND_SUBSCRIBERS_EMAIL_CONFIRMATION = True # Django-storages settings DEFAULT_FILE_STORAGE = 'core.s3utils.MediaRootS3BotoStorage' AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY",
"and read from # memory instead of reading from disk on each load.",
"* DEBUG = False TEMPLATE_DEBUG = DEBUG # Use the cached template loader",
") # Hosts/domain names that are valid for this site; required if DEBUG",
"<<EMAIL>>', } # Subscribers app settings SEND_SUBSCRIBERS_EMAIL_CONFIRMATION = True # Django-storages settings DEFAULT_FILE_STORAGE",
"each load. TEMPLATE_LOADERS = ( ('django.template.loaders.cached.Loader', ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', )), ) # Hosts/domain",
"= False TEMPLATE_DEBUG = DEBUG # Use the cached template loader so template",
"# 3rd-party apps tracking IDs. INTERCOM_APP_ID = 'a6d0326564469dfd7f7d9b1bfc909ee3815a85a8' GOOGLE_ANALYTICS_TRACKING_ID = 'UA-45698014-1' ADDTHIS_PUBLISHER_ID =",
"apps tracking IDs. INTERCOM_APP_ID = 'a6d0326564469dfd7f7d9b1bfc909ee3815a85a8' GOOGLE_ANALYTICS_TRACKING_ID = 'UA-45698014-1' ADDTHIS_PUBLISHER_ID = 'ra-52fffdf9456ec7d2' #",
"# Make this unique, and don't share it with anybody. SECRET_KEY = os.environ['DJANGO_SECRET_KEY']",
"ADMINS = ( ('Local Admin', '<EMAIL>'), ) MANAGERS = ADMINS CONTACTS = {",
"Admin', '<EMAIL>'), ) MANAGERS = ADMINS CONTACTS = { 'support_email': 'GlucoseTracker.net <<EMAIL>>', 'admin_email':",
"DEBUG = False TEMPLATE_DEBUG = DEBUG # Use the cached template loader so",
"= { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'glucosetracker', 'USER': os.environ['DATABASE_USER'], 'PASSWORD': os.environ['DATABASE_PASSWORD'], 'HOST':",
"from .base import * DEBUG = False TEMPLATE_DEBUG = DEBUG # Use the",
"anybody. SECRET_KEY = os.environ['DJANGO_SECRET_KEY'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'glucosetracker',",
"['.glucosetracker.net'] # Make this unique, and don't share it with anybody. SECRET_KEY =",
"# Use the cached template loader so template is compiled once and read",
"of reading from disk on each load. TEMPLATE_LOADERS = ( ('django.template.loaders.cached.Loader', ( 'django.template.loaders.filesystem.Loader',",
"once and read from # memory instead of reading from disk on each",
"( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', )), ) # Hosts/domain names that are valid for this",
"= { 'support_email': 'GlucoseTracker.net <<EMAIL>>', 'admin_email': '<EMAIL>', 'info_email': 'GlucoseTracker.net <<EMAIL>>', } # Subscribers",
"os.environ['DATABASE_USER'], 'PASSWORD': os.environ['DATABASE_PASSWORD'], 'HOST': 'localhost', 'PORT': '', } } # 3rd-party apps tracking",
"'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'glucosetracker', 'USER': os.environ['DATABASE_USER'], 'PASSWORD': os.environ['DATABASE_PASSWORD'], 'HOST': 'localhost', 'PORT': '', }",
"} # 3rd-party apps tracking IDs. INTERCOM_APP_ID = 'a6d0326564469dfd7f7d9b1bfc909ee3815a85a8' GOOGLE_ANALYTICS_TRACKING_ID = 'UA-45698014-1' ADDTHIS_PUBLISHER_ID",
"memory instead of reading from disk on each load. TEMPLATE_LOADERS = ( ('django.template.loaders.cached.Loader',",
"on each load. TEMPLATE_LOADERS = ( ('django.template.loaders.cached.Loader', ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', )), ) #",
"{ 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'glucosetracker', 'USER': os.environ['DATABASE_USER'], 'PASSWORD': os.environ['DATABASE_PASSWORD'], 'HOST': 'localhost',",
"from disk on each load. TEMPLATE_LOADERS = ( ('django.template.loaders.cached.Loader', ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', )),",
"import * DEBUG = False TEMPLATE_DEBUG = DEBUG # Use the cached template",
")), ) # Hosts/domain names that are valid for this site; required if",
"AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] AWS_STORAGE_BUCKET_NAME = 'glucosetracker-assets' AWS_QUERYSTRING_AUTH = False MEDIA_URL = '//%s.s3.amazonaws.com/%s/' %",
"settings DEFAULT_FILE_STORAGE = 'core.s3utils.MediaRootS3BotoStorage' AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] AWS_STORAGE_BUCKET_NAME = 'glucosetracker-assets'",
"DEBUG is False # See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts ALLOWED_HOSTS = ['.glucosetracker.net'] # Make this unique,",
"valid for this site; required if DEBUG is False # See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts ALLOWED_HOSTS",
"= 'a6d0326564469dfd7f7d9b1bfc909ee3815a85a8' GOOGLE_ANALYTICS_TRACKING_ID = 'UA-45698014-1' ADDTHIS_PUBLISHER_ID = 'ra-52fffdf9456ec7d2' # The 'From:' header of",
"{ 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'glucosetracker', 'USER': os.environ['DATABASE_USER'], 'PASSWORD': os.environ['DATABASE_PASSWORD'], 'HOST': 'localhost', 'PORT': '',",
"'django.db.backends.postgresql_psycopg2', 'NAME': 'glucosetracker', 'USER': os.environ['DATABASE_USER'], 'PASSWORD': os.environ['DATABASE_PASSWORD'], 'HOST': 'localhost', 'PORT': '', } }",
"= ['.glucosetracker.net'] # Make this unique, and don't share it with anybody. SECRET_KEY",
"TEMPLATE_LOADERS = ( ('django.template.loaders.cached.Loader', ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', )), ) # Hosts/domain names that",
"of admin-related emails. DEFAULT_FROM_EMAIL = '<EMAIL>' ADMINS = ( ('Local Admin', '<EMAIL>'), )",
"MANAGERS = ADMINS CONTACTS = { 'support_email': 'GlucoseTracker.net <<EMAIL>>', 'admin_email': '<EMAIL>', 'info_email': 'GlucoseTracker.net",
"( ('Local Admin', '<EMAIL>'), ) MANAGERS = ADMINS CONTACTS = { 'support_email': 'GlucoseTracker.net",
"os.environ['DJANGO_SECRET_KEY'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'glucosetracker', 'USER': os.environ['DATABASE_USER'], 'PASSWORD':",
"'support_email': 'GlucoseTracker.net <<EMAIL>>', 'admin_email': '<EMAIL>', 'info_email': 'GlucoseTracker.net <<EMAIL>>', } # Subscribers app settings",
"'<EMAIL>' ADMINS = ( ('Local Admin', '<EMAIL>'), ) MANAGERS = ADMINS CONTACTS =",
"admin-related emails. DEFAULT_FROM_EMAIL = '<EMAIL>' ADMINS = ( ('Local Admin', '<EMAIL>'), ) MANAGERS",
"= ADMINS CONTACTS = { 'support_email': 'GlucoseTracker.net <<EMAIL>>', 'admin_email': '<EMAIL>', 'info_email': 'GlucoseTracker.net <<EMAIL>>',",
"('django.template.loaders.cached.Loader', ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', )), ) # Hosts/domain names that are valid for",
"share it with anybody. SECRET_KEY = os.environ['DJANGO_SECRET_KEY'] DATABASES = { 'default': { 'ENGINE':",
"cached template loader so template is compiled once and read from # memory",
"} } # 3rd-party apps tracking IDs. INTERCOM_APP_ID = 'a6d0326564469dfd7f7d9b1bfc909ee3815a85a8' GOOGLE_ANALYTICS_TRACKING_ID = 'UA-45698014-1'",
"with anybody. SECRET_KEY = os.environ['DJANGO_SECRET_KEY'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME':",
"= DEBUG # Use the cached template loader so template is compiled once",
") MANAGERS = ADMINS CONTACTS = { 'support_email': 'GlucoseTracker.net <<EMAIL>>', 'admin_email': '<EMAIL>', 'info_email':",
"https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts ALLOWED_HOSTS = ['.glucosetracker.net'] # Make this unique, and don't share it with",
"# Subscribers app settings SEND_SUBSCRIBERS_EMAIL_CONFIRMATION = True # Django-storages settings DEFAULT_FILE_STORAGE = 'core.s3utils.MediaRootS3BotoStorage'",
"required if DEBUG is False # See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts ALLOWED_HOSTS = ['.glucosetracker.net'] # Make",
"= '<EMAIL>' ADMINS = ( ('Local Admin', '<EMAIL>'), ) MANAGERS = ADMINS CONTACTS",
"# Hosts/domain names that are valid for this site; required if DEBUG is",
"for this site; required if DEBUG is False # See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts ALLOWED_HOSTS =",
"that are valid for this site; required if DEBUG is False # See",
"'<EMAIL>', 'info_email': 'GlucoseTracker.net <<EMAIL>>', } # Subscribers app settings SEND_SUBSCRIBERS_EMAIL_CONFIRMATION = True #",
"Use the cached template loader so template is compiled once and read from",
"load. TEMPLATE_LOADERS = ( ('django.template.loaders.cached.Loader', ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', )), ) # Hosts/domain names",
"= 'core.s3utils.MediaRootS3BotoStorage' AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] AWS_STORAGE_BUCKET_NAME = 'glucosetracker-assets' AWS_QUERYSTRING_AUTH =",
"loader so template is compiled once and read from # memory instead of",
"is False # See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts ALLOWED_HOSTS = ['.glucosetracker.net'] # Make this unique, and",
"DEFAULT_FROM_EMAIL = '<EMAIL>' ADMINS = ( ('Local Admin', '<EMAIL>'), ) MANAGERS = ADMINS",
"= os.environ['AWS_SECRET_ACCESS_KEY'] AWS_STORAGE_BUCKET_NAME = 'glucosetracker-assets' AWS_QUERYSTRING_AUTH = False MEDIA_URL = '//%s.s3.amazonaws.com/%s/' % (AWS_STORAGE_BUCKET_NAME,",
"unique, and don't share it with anybody. SECRET_KEY = os.environ['DJANGO_SECRET_KEY'] DATABASES = {",
"ADDTHIS_PUBLISHER_ID = 'ra-52fffdf9456ec7d2' # The 'From:' header of admin-related emails. DEFAULT_FROM_EMAIL = '<EMAIL>'",
"emails. DEFAULT_FROM_EMAIL = '<EMAIL>' ADMINS = ( ('Local Admin', '<EMAIL>'), ) MANAGERS =",
"the cached template loader so template is compiled once and read from #",
"ADMINS CONTACTS = { 'support_email': 'GlucoseTracker.net <<EMAIL>>', 'admin_email': '<EMAIL>', 'info_email': 'GlucoseTracker.net <<EMAIL>>', }",
"= 'UA-45698014-1' ADDTHIS_PUBLISHER_ID = 'ra-52fffdf9456ec7d2' # The 'From:' header of admin-related emails. DEFAULT_FROM_EMAIL",
"'core.s3utils.MediaRootS3BotoStorage' AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] AWS_STORAGE_BUCKET_NAME = 'glucosetracker-assets' AWS_QUERYSTRING_AUTH = False",
"# Django-storages settings DEFAULT_FILE_STORAGE = 'core.s3utils.MediaRootS3BotoStorage' AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] AWS_STORAGE_BUCKET_NAME",
"= os.environ['DJANGO_SECRET_KEY'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'glucosetracker', 'USER': os.environ['DATABASE_USER'],",
"Django-storages settings DEFAULT_FILE_STORAGE = 'core.s3utils.MediaRootS3BotoStorage' AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] AWS_STORAGE_BUCKET_NAME =",
"3rd-party apps tracking IDs. INTERCOM_APP_ID = 'a6d0326564469dfd7f7d9b1bfc909ee3815a85a8' GOOGLE_ANALYTICS_TRACKING_ID = 'UA-45698014-1' ADDTHIS_PUBLISHER_ID = 'ra-52fffdf9456ec7d2'",
"compiled once and read from # memory instead of reading from disk on",
"this site; required if DEBUG is False # See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts ALLOWED_HOSTS = ['.glucosetracker.net']",
"'django.template.loaders.app_directories.Loader', )), ) # Hosts/domain names that are valid for this site; required",
"False TEMPLATE_DEBUG = DEBUG # Use the cached template loader so template is",
"# The 'From:' header of admin-related emails. DEFAULT_FROM_EMAIL = '<EMAIL>' ADMINS = (",
"'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'glucosetracker', 'USER': os.environ['DATABASE_USER'], 'PASSWORD': os.environ['DATABASE_PASSWORD'], 'HOST': 'localhost', 'PORT':",
"INTERCOM_APP_ID = 'a6d0326564469dfd7f7d9b1bfc909ee3815a85a8' GOOGLE_ANALYTICS_TRACKING_ID = 'UA-45698014-1' ADDTHIS_PUBLISHER_ID = 'ra-52fffdf9456ec7d2' # The 'From:' header",
"DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'glucosetracker', 'USER': os.environ['DATABASE_USER'], 'PASSWORD': os.environ['DATABASE_PASSWORD'],",
"( ('django.template.loaders.cached.Loader', ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', )), ) # Hosts/domain names that are valid"
] |
[
"pi from IPython.display import display from pyvlm import LatticeResult, LatticeOptimum from pyvlm import",
"the lifting surface. lopt1 = LatticeOptimum('Unconstrained Optimised', lsys)#, sym=False) lopt1.set_state() lopt1.add_constraint('L', L) lopt1.add_record('l',",
"Elliptical. # Note: You have to consider root moment for both sides of",
"for both sides of the lifting surface. lopt1 = LatticeOptimum('Unconstrained Optimised', lsys)#, sym=False)",
"3.0 # degrees beta = 0.0 # degrees lres_org = LatticeResult('Baseline', lsys) lres_org.set_state(alpha=alpha,",
"lopt1.record[0].value*0.75 mspec = lopt1.record[1].value*0.75 lopt2 = LatticeOptimum('Constrained Optimised', lsys)#, sym=False) lopt2.set_state() lopt2.add_constraint('L', L)",
"print(f'CL_ell = {lopt_ell.trres.CL:.3f}') print(f'CL_opt1 = {lopt1.trres.CL:.3f}') print(f'CL_opt2 = {lopt2.trres.CL:.3f}') print('') print(f'CDi_org_theory = {CDi_org_theory:.7f}')",
"= lres_org.trres.CL**2/pi/lsys.ar/lres_org.trres.e CDi_ell_theory = lres_org.trres.CL**2/pi/lsys.ar print(f'CL_org = {lres_org.trres.CL:.3f}') print(f'CL_ell = {lopt_ell.trres.CL:.3f}') print(f'CL_opt1 =",
"#%% Load Dependencies from math import pi from IPython.display import display from pyvlm",
"Lattice System jsonfilepath = '../files/Straight_Wing_Cosine_100.json' lsys = latticesystem_from_json(jsonfilepath) display(lsys) #%% Original Case alpha",
"pyvlm import LatticeResult, LatticeOptimum from pyvlm import latticesystem_from_json from pyvlm.tools import elliptical_lift_force_distribution #%%",
"Dependencies from math import pi from IPython.display import display from pyvlm import LatticeResult,",
"# degrees lres_org = LatticeResult('Baseline', lsys) lres_org.set_state(alpha=alpha, beta=beta) display(lres_org) #%% Equivalent Elliptical Lift",
"degrees lres_org = LatticeResult('Baseline', lsys) lres_org.set_state(alpha=alpha, beta=beta) display(lres_org) #%% Equivalent Elliptical Lift L",
"_ = axl.set_xlabel('Span Position') #%% Print Results CDi_org_theory = lres_org.trres.CL**2/pi/lsys.ar/lres_org.trres.e CDi_ell_theory = lres_org.trres.CL**2/pi/lsys.ar",
"lres_org.trres.CL**2/pi/lsys.ar print(f'CL_org = {lres_org.trres.CL:.3f}') print(f'CL_ell = {lopt_ell.trres.CL:.3f}') print(f'CL_opt1 = {lopt1.trres.CL:.3f}') print(f'CL_opt2 = {lopt2.trres.CL:.3f}')",
"L) lopt_ell = LatticeOptimum('Equivalent Elliptical', lsys) lopt_ell.set_state(alpha=alpha) lopt_ell.set_target_lift_force_distribution(lell, rho=1.0, speed=1.0) display(lopt_ell) #%% Calculate",
"= LatticeOptimum('Unconstrained Optimised', lsys)#, sym=False) lopt1.set_state() lopt1.add_constraint('L', L) lopt1.add_record('l', strplst=lsys.lstrpi) lopt1.add_record('l', strplst=lsys.mstrpi) phi1,",
"= lopt2.plot_trefftz_lift_force_distribution(ax=axl) _ = axl.set_ylabel('Lift Distribution') _ = axl.set_xlabel('Span Position') #%% Print Results",
"{CDi_org_theory:.7f}') print(f'CDi_org = {lres_org.trres.CDi:.7f}') print(f'CDi_ell_theory = {CDi_ell_theory:.7f}') print(f'CDi_ell = {lopt_ell.trres.CDi:.7f}') print(f'CDi_opt1 = {lopt1.trres.CDi:.7f}')",
"latticesystem_from_json from pyvlm.tools import elliptical_lift_force_distribution #%% Create Lattice System jsonfilepath = '../files/Straight_Wing_Cosine_100.json' lsys",
"print('') print(f'CDi_org_theory = {CDi_org_theory:.7f}') print(f'CDi_org = {lres_org.trres.CDi:.7f}') print(f'CDi_ell_theory = {CDi_ell_theory:.7f}') print(f'CDi_ell = {lopt_ell.trres.CDi:.7f}')",
"# Note: You have to consider root moment for both sides of the",
"display(lsys) #%% Original Case alpha = 3.0 # degrees beta = 0.0 #",
"= {lopt2.trres.CL:.3f}') print('') print(f'CDi_org_theory = {CDi_org_theory:.7f}') print(f'CDi_org = {lres_org.trres.CDi:.7f}') print(f'CDi_ell_theory = {CDi_ell_theory:.7f}') print(f'CDi_ell",
"Root Bending Moment (Rolling Moment) to 75% of the Elliptical Optimimum. # Note:",
"LatticeOptimum('Equivalent Elliptical', lsys) lopt_ell.set_state(alpha=alpha) lopt_ell.set_target_lift_force_distribution(lell, rho=1.0, speed=1.0) display(lopt_ell) #%% Calculate Unconstrained Optimum #",
"Optimised', lsys)#, sym=False) lopt1.set_state() lopt1.add_constraint('L', L) lopt1.add_record('l', strplst=lsys.lstrpi) lopt1.add_record('l', strplst=lsys.mstrpi) phi1, lam1 =",
"(Rolling Moment) to 75% of the Elliptical Optimimum. # Note: You have to",
"from pyvlm import LatticeResult, LatticeOptimum from pyvlm import latticesystem_from_json from pyvlm.tools import elliptical_lift_force_distribution",
"Moment (Rolling Moment) to 75% of the Elliptical Optimimum. # Note: You have",
"jsonfilepath = '../files/Straight_Wing_Cosine_100.json' lsys = latticesystem_from_json(jsonfilepath) display(lsys) #%% Original Case alpha = 3.0",
"lsys.bref, L) lopt_ell = LatticeOptimum('Equivalent Elliptical', lsys) lopt_ell.set_state(alpha=alpha) lopt_ell.set_target_lift_force_distribution(lell, rho=1.0, speed=1.0) display(lopt_ell) #%%",
"of the Elliptical Optimimum. # Note: You have to consider both sides of",
"= axl.set_ylabel('Lift Distribution') _ = axl.set_xlabel('Span Position') #%% Print Results CDi_org_theory = lres_org.trres.CL**2/pi/lsys.ar/lres_org.trres.e",
"axl.set_xlabel('Span Position') #%% Print Results CDi_org_theory = lres_org.trres.CL**2/pi/lsys.ar/lres_org.trres.e CDi_ell_theory = lres_org.trres.CL**2/pi/lsys.ar print(f'CL_org =",
"# degrees beta = 0.0 # degrees lres_org = LatticeResult('Baseline', lsys) lres_org.set_state(alpha=alpha, beta=beta)",
"is Elliptical. # Note: You have to consider root moment for both sides",
"to 75% of the Elliptical Optimimum. # Note: You have to consider both",
"{lres_org.trres.CL:.3f}') print(f'CL_ell = {lopt_ell.trres.CL:.3f}') print(f'CL_opt1 = {lopt1.trres.CL:.3f}') print(f'CL_opt2 = {lopt2.trres.CL:.3f}') print('') print(f'CDi_org_theory =",
"have to consider both sides of the lifting surface. lspec = lopt1.record[0].value*0.75 mspec",
"= {lopt_ell.trres.CL:.3f}') print(f'CL_opt1 = {lopt1.trres.CL:.3f}') print(f'CL_opt2 = {lopt2.trres.CL:.3f}') print('') print(f'CDi_org_theory = {CDi_org_theory:.7f}') print(f'CDi_org",
"= lopt1.record[0].value*0.75 mspec = lopt1.record[1].value*0.75 lopt2 = LatticeOptimum('Constrained Optimised', lsys)#, sym=False) lopt2.set_state() lopt2.add_constraint('L',",
"display(lopt1) #%% Calculate Constrained Optimum # Constrain Root Bending Moment (Rolling Moment) to",
"Distribution') _ = axl.set_xlabel('Span Position') #%% Print Results CDi_org_theory = lres_org.trres.CL**2/pi/lsys.ar/lres_org.trres.e CDi_ell_theory =",
"lopt1.add_record('l', strplst=lsys.mstrpi) phi1, lam1 = lopt1.optimum_lift_force_distribution() display(lopt1) #%% Calculate Constrained Optimum # Constrain",
"alpha = 3.0 # degrees beta = 0.0 # degrees lres_org = LatticeResult('Baseline',",
"lopt1 = LatticeOptimum('Unconstrained Optimised', lsys)#, sym=False) lopt1.set_state() lopt1.add_constraint('L', L) lopt1.add_record('l', strplst=lsys.lstrpi) lopt1.add_record('l', strplst=lsys.mstrpi)",
"print(f'CDi_org = {lres_org.trres.CDi:.7f}') print(f'CDi_ell_theory = {CDi_ell_theory:.7f}') print(f'CDi_ell = {lopt_ell.trres.CDi:.7f}') print(f'CDi_opt1 = {lopt1.trres.CDi:.7f}') print(f'CDi_opt2",
"{lopt_ell.trres.CL:.3f}') print(f'CL_opt1 = {lopt1.trres.CL:.3f}') print(f'CL_opt2 = {lopt2.trres.CL:.3f}') print('') print(f'CDi_org_theory = {CDi_org_theory:.7f}') print(f'CDi_org =",
"# Constrain Root Bending Moment (Rolling Moment) to 75% of the Elliptical Optimimum.",
"You have to consider both sides of the lifting surface. lspec = lopt1.record[0].value*0.75",
"Distributions axl = None axl = lres_org.plot_trefftz_lift_force_distribution(ax=axl) axl = lopt_ell.plot_trefftz_lift_force_distribution(ax=axl) axl = lopt1.plot_trefftz_lift_force_distribution(ax=axl)",
"print(f'CDi_ell_theory = {CDi_ell_theory:.7f}') print(f'CDi_ell = {lopt_ell.trres.CDi:.7f}') print(f'CDi_opt1 = {lopt1.trres.CDi:.7f}') print(f'CDi_opt2 = {lopt2.trres.CDi:.7f}') print('')",
"lifting surface. lopt1 = LatticeOptimum('Unconstrained Optimised', lsys)#, sym=False) lopt1.set_state() lopt1.add_constraint('L', L) lopt1.add_record('l', strplst=lsys.lstrpi)",
"= LatticeResult('Baseline', lsys) lres_org.set_state(alpha=alpha, beta=beta) display(lres_org) #%% Equivalent Elliptical Lift L = lres_org.nfres.CL*lres_org.qfs*lsys.sref",
"= lres_org.nfres.CL*lres_org.qfs*lsys.sref lell = elliptical_lift_force_distribution(lsys.srfcs[0].strpy, lsys.bref, L) lopt_ell = LatticeOptimum('Equivalent Elliptical', lsys) lopt_ell.set_state(alpha=alpha)",
"= elliptical_lift_force_distribution(lsys.srfcs[0].strpy, lsys.bref, L) lopt_ell = LatticeOptimum('Equivalent Elliptical', lsys) lopt_ell.set_state(alpha=alpha) lopt_ell.set_target_lift_force_distribution(lell, rho=1.0, speed=1.0)",
"strplst=lsys.mstrpi) phi1, lam1 = lopt1.optimum_lift_force_distribution() display(lopt1) #%% Calculate Constrained Optimum # Constrain Root",
"Constrain Only Lift and the resulting lift distribution is Elliptical. # Note: You",
"Constrained Optimum # Constrain Root Bending Moment (Rolling Moment) to 75% of the",
"the lifting surface. lspec = lopt1.record[0].value*0.75 mspec = lopt1.record[1].value*0.75 lopt2 = LatticeOptimum('Constrained Optimised',",
"lopt1.plot_trefftz_lift_force_distribution(ax=axl) axl = lopt2.plot_trefftz_lift_force_distribution(ax=axl) _ = axl.set_ylabel('Lift Distribution') _ = axl.set_xlabel('Span Position') #%%",
"= axl.set_xlabel('Span Position') #%% Print Results CDi_org_theory = lres_org.trres.CL**2/pi/lsys.ar/lres_org.trres.e CDi_ell_theory = lres_org.trres.CL**2/pi/lsys.ar print(f'CL_org",
"import LatticeResult, LatticeOptimum from pyvlm import latticesystem_from_json from pyvlm.tools import elliptical_lift_force_distribution #%% Create",
"Elliptical Optimimum. # Note: You have to consider both sides of the lifting",
"from pyvlm import latticesystem_from_json from pyvlm.tools import elliptical_lift_force_distribution #%% Create Lattice System jsonfilepath",
"and the resulting lift distribution is Elliptical. # Note: You have to consider",
"= lopt1.optimum_lift_force_distribution() display(lopt1) #%% Calculate Constrained Optimum # Constrain Root Bending Moment (Rolling",
"from math import pi from IPython.display import display from pyvlm import LatticeResult, LatticeOptimum",
"lell = elliptical_lift_force_distribution(lsys.srfcs[0].strpy, lsys.bref, L) lopt_ell = LatticeOptimum('Equivalent Elliptical', lsys) lopt_ell.set_state(alpha=alpha) lopt_ell.set_target_lift_force_distribution(lell, rho=1.0,",
"Constrain Root Bending Moment (Rolling Moment) to 75% of the Elliptical Optimimum. #",
"LatticeResult, LatticeOptimum from pyvlm import latticesystem_from_json from pyvlm.tools import elliptical_lift_force_distribution #%% Create Lattice",
"= lopt1.record[1].value*0.75 lopt2 = LatticeOptimum('Constrained Optimised', lsys)#, sym=False) lopt2.set_state() lopt2.add_constraint('L', L) lopt2.add_constraint('l', lspec,",
"L = lres_org.nfres.CL*lres_org.qfs*lsys.sref lell = elliptical_lift_force_distribution(lsys.srfcs[0].strpy, lsys.bref, L) lopt_ell = LatticeOptimum('Equivalent Elliptical', lsys)",
"# Constrain Only Lift and the resulting lift distribution is Elliptical. # Note:",
"sym=False) lopt2.set_state() lopt2.add_constraint('L', L) lopt2.add_constraint('l', lspec, strplst=lsys.lstrpi) lopt2.add_constraint('l', mspec, strplst=lsys.mstrpi) phi2, lam2 =",
"= lopt_ell.plot_trefftz_lift_force_distribution(ax=axl) axl = lopt1.plot_trefftz_lift_force_distribution(ax=axl) axl = lopt2.plot_trefftz_lift_force_distribution(ax=axl) _ = axl.set_ylabel('Lift Distribution') _",
"Results CDi_org_theory = lres_org.trres.CL**2/pi/lsys.ar/lres_org.trres.e CDi_ell_theory = lres_org.trres.CL**2/pi/lsys.ar print(f'CL_org = {lres_org.trres.CL:.3f}') print(f'CL_ell = {lopt_ell.trres.CL:.3f}')",
"latticesystem_from_json(jsonfilepath) display(lsys) #%% Original Case alpha = 3.0 # degrees beta = 0.0",
"math import pi from IPython.display import display from pyvlm import LatticeResult, LatticeOptimum from",
"consider both sides of the lifting surface. lspec = lopt1.record[0].value*0.75 mspec = lopt1.record[1].value*0.75",
"both sides of the lifting surface. lspec = lopt1.record[0].value*0.75 mspec = lopt1.record[1].value*0.75 lopt2",
"display(lopt2) #%% Plot Distributions axl = None axl = lres_org.plot_trefftz_lift_force_distribution(ax=axl) axl = lopt_ell.plot_trefftz_lift_force_distribution(ax=axl)",
"= 3.0 # degrees beta = 0.0 # degrees lres_org = LatticeResult('Baseline', lsys)",
"elliptical_lift_force_distribution(lsys.srfcs[0].strpy, lsys.bref, L) lopt_ell = LatticeOptimum('Equivalent Elliptical', lsys) lopt_ell.set_state(alpha=alpha) lopt_ell.set_target_lift_force_distribution(lell, rho=1.0, speed=1.0) display(lopt_ell)",
"= {lres_org.trres.CDi:.7f}') print(f'CDi_ell_theory = {CDi_ell_theory:.7f}') print(f'CDi_ell = {lopt_ell.trres.CDi:.7f}') print(f'CDi_opt1 = {lopt1.trres.CDi:.7f}') print(f'CDi_opt2 =",
"#%% Create Lattice System jsonfilepath = '../files/Straight_Wing_Cosine_100.json' lsys = latticesystem_from_json(jsonfilepath) display(lsys) #%% Original",
"#%% Calculate Unconstrained Optimum # Constrain Only Lift and the resulting lift distribution",
"the Elliptical Optimimum. # Note: You have to consider both sides of the",
"IPython.display import display from pyvlm import LatticeResult, LatticeOptimum from pyvlm import latticesystem_from_json from",
"strplst=lsys.mstrpi) phi2, lam2 = lopt2.optimum_lift_force_distribution() display(lopt2) #%% Plot Distributions axl = None axl",
"lam2 = lopt2.optimum_lift_force_distribution() display(lopt2) #%% Plot Distributions axl = None axl = lres_org.plot_trefftz_lift_force_distribution(ax=axl)",
"Print Results CDi_org_theory = lres_org.trres.CL**2/pi/lsys.ar/lres_org.trres.e CDi_ell_theory = lres_org.trres.CL**2/pi/lsys.ar print(f'CL_org = {lres_org.trres.CL:.3f}') print(f'CL_ell =",
"rho=1.0, speed=1.0) display(lopt_ell) #%% Calculate Unconstrained Optimum # Constrain Only Lift and the",
"lres_org.nfres.CL*lres_org.qfs*lsys.sref lell = elliptical_lift_force_distribution(lsys.srfcs[0].strpy, lsys.bref, L) lopt_ell = LatticeOptimum('Equivalent Elliptical', lsys) lopt_ell.set_state(alpha=alpha) lopt_ell.set_target_lift_force_distribution(lell,",
"Moment) to 75% of the Elliptical Optimimum. # Note: You have to consider",
"print(f'CL_opt2 = {lopt2.trres.CL:.3f}') print('') print(f'CDi_org_theory = {CDi_org_theory:.7f}') print(f'CDi_org = {lres_org.trres.CDi:.7f}') print(f'CDi_ell_theory = {CDi_ell_theory:.7f}')",
"surface. lopt1 = LatticeOptimum('Unconstrained Optimised', lsys)#, sym=False) lopt1.set_state() lopt1.add_constraint('L', L) lopt1.add_record('l', strplst=lsys.lstrpi) lopt1.add_record('l',",
"LatticeOptimum('Constrained Optimised', lsys)#, sym=False) lopt2.set_state() lopt2.add_constraint('L', L) lopt2.add_constraint('l', lspec, strplst=lsys.lstrpi) lopt2.add_constraint('l', mspec, strplst=lsys.mstrpi)",
"print(f'CL_opt1 = {lopt1.trres.CL:.3f}') print(f'CL_opt2 = {lopt2.trres.CL:.3f}') print('') print(f'CDi_org_theory = {CDi_org_theory:.7f}') print(f'CDi_org = {lres_org.trres.CDi:.7f}')",
"phi2, lam2 = lopt2.optimum_lift_force_distribution() display(lopt2) #%% Plot Distributions axl = None axl =",
"sym=False) lopt1.set_state() lopt1.add_constraint('L', L) lopt1.add_record('l', strplst=lsys.lstrpi) lopt1.add_record('l', strplst=lsys.mstrpi) phi1, lam1 = lopt1.optimum_lift_force_distribution() display(lopt1)",
"= {lres_org.trres.CL:.3f}') print(f'CL_ell = {lopt_ell.trres.CL:.3f}') print(f'CL_opt1 = {lopt1.trres.CL:.3f}') print(f'CL_opt2 = {lopt2.trres.CL:.3f}') print('') print(f'CDi_org_theory",
"beta = 0.0 # degrees lres_org = LatticeResult('Baseline', lsys) lres_org.set_state(alpha=alpha, beta=beta) display(lres_org) #%%",
"= lres_org.plot_trefftz_lift_force_distribution(ax=axl) axl = lopt_ell.plot_trefftz_lift_force_distribution(ax=axl) axl = lopt1.plot_trefftz_lift_force_distribution(ax=axl) axl = lopt2.plot_trefftz_lift_force_distribution(ax=axl) _ =",
"lopt_ell.set_target_lift_force_distribution(lell, rho=1.0, speed=1.0) display(lopt_ell) #%% Calculate Unconstrained Optimum # Constrain Only Lift and",
"lift distribution is Elliptical. # Note: You have to consider root moment for",
"lopt2.plot_trefftz_lift_force_distribution(ax=axl) _ = axl.set_ylabel('Lift Distribution') _ = axl.set_xlabel('Span Position') #%% Print Results CDi_org_theory",
"Note: You have to consider root moment for both sides of the lifting",
"lsys) lopt_ell.set_state(alpha=alpha) lopt_ell.set_target_lift_force_distribution(lell, rho=1.0, speed=1.0) display(lopt_ell) #%% Calculate Unconstrained Optimum # Constrain Only",
"= {CDi_ell_theory:.7f}') print(f'CDi_ell = {lopt_ell.trres.CDi:.7f}') print(f'CDi_opt1 = {lopt1.trres.CDi:.7f}') print(f'CDi_opt2 = {lopt2.trres.CDi:.7f}') print('') print(f'Efficiency",
"lopt1.optimum_lift_force_distribution() display(lopt1) #%% Calculate Constrained Optimum # Constrain Root Bending Moment (Rolling Moment)",
"Elliptical Lift L = lres_org.nfres.CL*lres_org.qfs*lsys.sref lell = elliptical_lift_force_distribution(lsys.srfcs[0].strpy, lsys.bref, L) lopt_ell = LatticeOptimum('Equivalent",
"= LatticeOptimum('Constrained Optimised', lsys)#, sym=False) lopt2.set_state() lopt2.add_constraint('L', L) lopt2.add_constraint('l', lspec, strplst=lsys.lstrpi) lopt2.add_constraint('l', mspec,",
"#%% Calculate Constrained Optimum # Constrain Root Bending Moment (Rolling Moment) to 75%",
"LatticeOptimum from pyvlm import latticesystem_from_json from pyvlm.tools import elliptical_lift_force_distribution #%% Create Lattice System",
"lopt_ell.set_state(alpha=alpha) lopt_ell.set_target_lift_force_distribution(lell, rho=1.0, speed=1.0) display(lopt_ell) #%% Calculate Unconstrained Optimum # Constrain Only Lift",
"axl = None axl = lres_org.plot_trefftz_lift_force_distribution(ax=axl) axl = lopt_ell.plot_trefftz_lift_force_distribution(ax=axl) axl = lopt1.plot_trefftz_lift_force_distribution(ax=axl) axl",
"sides of the lifting surface. lspec = lopt1.record[0].value*0.75 mspec = lopt1.record[1].value*0.75 lopt2 =",
"lres_org.trres.CL**2/pi/lsys.ar/lres_org.trres.e CDi_ell_theory = lres_org.trres.CL**2/pi/lsys.ar print(f'CL_org = {lres_org.trres.CL:.3f}') print(f'CL_ell = {lopt_ell.trres.CL:.3f}') print(f'CL_opt1 = {lopt1.trres.CL:.3f}')",
"display(lopt_ell) #%% Calculate Unconstrained Optimum # Constrain Only Lift and the resulting lift",
"of the lifting surface. lopt1 = LatticeOptimum('Unconstrained Optimised', lsys)#, sym=False) lopt1.set_state() lopt1.add_constraint('L', L)",
"LatticeOptimum('Unconstrained Optimised', lsys)#, sym=False) lopt1.set_state() lopt1.add_constraint('L', L) lopt1.add_record('l', strplst=lsys.lstrpi) lopt1.add_record('l', strplst=lsys.mstrpi) phi1, lam1",
"import latticesystem_from_json from pyvlm.tools import elliptical_lift_force_distribution #%% Create Lattice System jsonfilepath = '../files/Straight_Wing_Cosine_100.json'",
"lopt_ell = LatticeOptimum('Equivalent Elliptical', lsys) lopt_ell.set_state(alpha=alpha) lopt_ell.set_target_lift_force_distribution(lell, rho=1.0, speed=1.0) display(lopt_ell) #%% Calculate Unconstrained",
"lopt2 = LatticeOptimum('Constrained Optimised', lsys)#, sym=False) lopt2.set_state() lopt2.add_constraint('L', L) lopt2.add_constraint('l', lspec, strplst=lsys.lstrpi) lopt2.add_constraint('l',",
"= 0.0 # degrees lres_org = LatticeResult('Baseline', lsys) lres_org.set_state(alpha=alpha, beta=beta) display(lres_org) #%% Equivalent",
"import display from pyvlm import LatticeResult, LatticeOptimum from pyvlm import latticesystem_from_json from pyvlm.tools",
"lopt1.add_record('l', strplst=lsys.lstrpi) lopt1.add_record('l', strplst=lsys.mstrpi) phi1, lam1 = lopt1.optimum_lift_force_distribution() display(lopt1) #%% Calculate Constrained Optimum",
"phi1, lam1 = lopt1.optimum_lift_force_distribution() display(lopt1) #%% Calculate Constrained Optimum # Constrain Root Bending",
"Elliptical', lsys) lopt_ell.set_state(alpha=alpha) lopt_ell.set_target_lift_force_distribution(lell, rho=1.0, speed=1.0) display(lopt_ell) #%% Calculate Unconstrained Optimum # Constrain",
"lres_org.plot_trefftz_lift_force_distribution(ax=axl) axl = lopt_ell.plot_trefftz_lift_force_distribution(ax=axl) axl = lopt1.plot_trefftz_lift_force_distribution(ax=axl) axl = lopt2.plot_trefftz_lift_force_distribution(ax=axl) _ = axl.set_ylabel('Lift",
"= {lopt_ell.trres.CDi:.7f}') print(f'CDi_opt1 = {lopt1.trres.CDi:.7f}') print(f'CDi_opt2 = {lopt2.trres.CDi:.7f}') print('') print(f'Efficiency Improvement = {100.0*(1.0-lopt1.trres.CDi/lres_org.trres.CDi):.2f}%')",
"distribution is Elliptical. # Note: You have to consider root moment for both",
"lopt2.optimum_lift_force_distribution() display(lopt2) #%% Plot Distributions axl = None axl = lres_org.plot_trefftz_lift_force_distribution(ax=axl) axl =",
"Case alpha = 3.0 # degrees beta = 0.0 # degrees lres_org =",
"beta=beta) display(lres_org) #%% Equivalent Elliptical Lift L = lres_org.nfres.CL*lres_org.qfs*lsys.sref lell = elliptical_lift_force_distribution(lsys.srfcs[0].strpy, lsys.bref,",
"lopt2.set_state() lopt2.add_constraint('L', L) lopt2.add_constraint('l', lspec, strplst=lsys.lstrpi) lopt2.add_constraint('l', mspec, strplst=lsys.mstrpi) phi2, lam2 = lopt2.optimum_lift_force_distribution()",
"Bending Moment (Rolling Moment) to 75% of the Elliptical Optimimum. # Note: You",
"Optimised', lsys)#, sym=False) lopt2.set_state() lopt2.add_constraint('L', L) lopt2.add_constraint('l', lspec, strplst=lsys.lstrpi) lopt2.add_constraint('l', mspec, strplst=lsys.mstrpi) phi2,",
"Optimimum. # Note: You have to consider both sides of the lifting surface.",
"Position') #%% Print Results CDi_org_theory = lres_org.trres.CL**2/pi/lsys.ar/lres_org.trres.e CDi_ell_theory = lres_org.trres.CL**2/pi/lsys.ar print(f'CL_org = {lres_org.trres.CL:.3f}')",
"display from pyvlm import LatticeResult, LatticeOptimum from pyvlm import latticesystem_from_json from pyvlm.tools import",
"Calculate Constrained Optimum # Constrain Root Bending Moment (Rolling Moment) to 75% of",
"= LatticeOptimum('Equivalent Elliptical', lsys) lopt_ell.set_state(alpha=alpha) lopt_ell.set_target_lift_force_distribution(lell, rho=1.0, speed=1.0) display(lopt_ell) #%% Calculate Unconstrained Optimum",
"lopt2.add_constraint('l', mspec, strplst=lsys.mstrpi) phi2, lam2 = lopt2.optimum_lift_force_distribution() display(lopt2) #%% Plot Distributions axl =",
"of the lifting surface. lspec = lopt1.record[0].value*0.75 mspec = lopt1.record[1].value*0.75 lopt2 = LatticeOptimum('Constrained",
"import pi from IPython.display import display from pyvlm import LatticeResult, LatticeOptimum from pyvlm",
"axl = lopt_ell.plot_trefftz_lift_force_distribution(ax=axl) axl = lopt1.plot_trefftz_lift_force_distribution(ax=axl) axl = lopt2.plot_trefftz_lift_force_distribution(ax=axl) _ = axl.set_ylabel('Lift Distribution')",
"to consider both sides of the lifting surface. lspec = lopt1.record[0].value*0.75 mspec =",
"lopt2.add_constraint('l', lspec, strplst=lsys.lstrpi) lopt2.add_constraint('l', mspec, strplst=lsys.mstrpi) phi2, lam2 = lopt2.optimum_lift_force_distribution() display(lopt2) #%% Plot",
"= {lopt1.trres.CL:.3f}') print(f'CL_opt2 = {lopt2.trres.CL:.3f}') print('') print(f'CDi_org_theory = {CDi_org_theory:.7f}') print(f'CDi_org = {lres_org.trres.CDi:.7f}') print(f'CDi_ell_theory",
"axl = lopt2.plot_trefftz_lift_force_distribution(ax=axl) _ = axl.set_ylabel('Lift Distribution') _ = axl.set_xlabel('Span Position') #%% Print",
"Plot Distributions axl = None axl = lres_org.plot_trefftz_lift_force_distribution(ax=axl) axl = lopt_ell.plot_trefftz_lift_force_distribution(ax=axl) axl =",
"print(f'CDi_org_theory = {CDi_org_theory:.7f}') print(f'CDi_org = {lres_org.trres.CDi:.7f}') print(f'CDi_ell_theory = {CDi_ell_theory:.7f}') print(f'CDi_ell = {lopt_ell.trres.CDi:.7f}') print(f'CDi_opt1",
"mspec = lopt1.record[1].value*0.75 lopt2 = LatticeOptimum('Constrained Optimised', lsys)#, sym=False) lopt2.set_state() lopt2.add_constraint('L', L) lopt2.add_constraint('l',",
"# Note: You have to consider both sides of the lifting surface. lspec",
"pyvlm import latticesystem_from_json from pyvlm.tools import elliptical_lift_force_distribution #%% Create Lattice System jsonfilepath =",
"lres_org = LatticeResult('Baseline', lsys) lres_org.set_state(alpha=alpha, beta=beta) display(lres_org) #%% Equivalent Elliptical Lift L =",
"display(lres_org) #%% Equivalent Elliptical Lift L = lres_org.nfres.CL*lres_org.qfs*lsys.sref lell = elliptical_lift_force_distribution(lsys.srfcs[0].strpy, lsys.bref, L)",
"lspec = lopt1.record[0].value*0.75 mspec = lopt1.record[1].value*0.75 lopt2 = LatticeOptimum('Constrained Optimised', lsys)#, sym=False) lopt2.set_state()",
"axl = lres_org.plot_trefftz_lift_force_distribution(ax=axl) axl = lopt_ell.plot_trefftz_lift_force_distribution(ax=axl) axl = lopt1.plot_trefftz_lift_force_distribution(ax=axl) axl = lopt2.plot_trefftz_lift_force_distribution(ax=axl) _",
"L) lopt1.add_record('l', strplst=lsys.lstrpi) lopt1.add_record('l', strplst=lsys.mstrpi) phi1, lam1 = lopt1.optimum_lift_force_distribution() display(lopt1) #%% Calculate Constrained",
"from IPython.display import display from pyvlm import LatticeResult, LatticeOptimum from pyvlm import latticesystem_from_json",
"#%% Print Results CDi_org_theory = lres_org.trres.CL**2/pi/lsys.ar/lres_org.trres.e CDi_ell_theory = lres_org.trres.CL**2/pi/lsys.ar print(f'CL_org = {lres_org.trres.CL:.3f}') print(f'CL_ell",
"{lopt1.trres.CL:.3f}') print(f'CL_opt2 = {lopt2.trres.CL:.3f}') print('') print(f'CDi_org_theory = {CDi_org_theory:.7f}') print(f'CDi_org = {lres_org.trres.CDi:.7f}') print(f'CDi_ell_theory =",
"strplst=lsys.lstrpi) lopt2.add_constraint('l', mspec, strplst=lsys.mstrpi) phi2, lam2 = lopt2.optimum_lift_force_distribution() display(lopt2) #%% Plot Distributions axl",
"from pyvlm.tools import elliptical_lift_force_distribution #%% Create Lattice System jsonfilepath = '../files/Straight_Wing_Cosine_100.json' lsys =",
"degrees beta = 0.0 # degrees lres_org = LatticeResult('Baseline', lsys) lres_org.set_state(alpha=alpha, beta=beta) display(lres_org)",
"0.0 # degrees lres_org = LatticeResult('Baseline', lsys) lres_org.set_state(alpha=alpha, beta=beta) display(lres_org) #%% Equivalent Elliptical",
"to consider root moment for both sides of the lifting surface. lopt1 =",
"root moment for both sides of the lifting surface. lopt1 = LatticeOptimum('Unconstrained Optimised',",
"Calculate Unconstrained Optimum # Constrain Only Lift and the resulting lift distribution is",
"lres_org.set_state(alpha=alpha, beta=beta) display(lres_org) #%% Equivalent Elliptical Lift L = lres_org.nfres.CL*lres_org.qfs*lsys.sref lell = elliptical_lift_force_distribution(lsys.srfcs[0].strpy,",
"Original Case alpha = 3.0 # degrees beta = 0.0 # degrees lres_org",
"{lres_org.trres.CDi:.7f}') print(f'CDi_ell_theory = {CDi_ell_theory:.7f}') print(f'CDi_ell = {lopt_ell.trres.CDi:.7f}') print(f'CDi_opt1 = {lopt1.trres.CDi:.7f}') print(f'CDi_opt2 = {lopt2.trres.CDi:.7f}')",
"consider root moment for both sides of the lifting surface. lopt1 = LatticeOptimum('Unconstrained",
"lam1 = lopt1.optimum_lift_force_distribution() display(lopt1) #%% Calculate Constrained Optimum # Constrain Root Bending Moment",
"= lopt1.plot_trefftz_lift_force_distribution(ax=axl) axl = lopt2.plot_trefftz_lift_force_distribution(ax=axl) _ = axl.set_ylabel('Lift Distribution') _ = axl.set_xlabel('Span Position')",
"print(f'CDi_ell = {lopt_ell.trres.CDi:.7f}') print(f'CDi_opt1 = {lopt1.trres.CDi:.7f}') print(f'CDi_opt2 = {lopt2.trres.CDi:.7f}') print('') print(f'Efficiency Improvement =",
"lsys)#, sym=False) lopt2.set_state() lopt2.add_constraint('L', L) lopt2.add_constraint('l', lspec, strplst=lsys.lstrpi) lopt2.add_constraint('l', mspec, strplst=lsys.mstrpi) phi2, lam2",
"resulting lift distribution is Elliptical. # Note: You have to consider root moment",
"Create Lattice System jsonfilepath = '../files/Straight_Wing_Cosine_100.json' lsys = latticesystem_from_json(jsonfilepath) display(lsys) #%% Original Case",
"lsys) lres_org.set_state(alpha=alpha, beta=beta) display(lres_org) #%% Equivalent Elliptical Lift L = lres_org.nfres.CL*lres_org.qfs*lsys.sref lell =",
"= latticesystem_from_json(jsonfilepath) display(lsys) #%% Original Case alpha = 3.0 # degrees beta =",
"lifting surface. lspec = lopt1.record[0].value*0.75 mspec = lopt1.record[1].value*0.75 lopt2 = LatticeOptimum('Constrained Optimised', lsys)#,",
"L) lopt2.add_constraint('l', lspec, strplst=lsys.lstrpi) lopt2.add_constraint('l', mspec, strplst=lsys.mstrpi) phi2, lam2 = lopt2.optimum_lift_force_distribution() display(lopt2) #%%",
"Note: You have to consider both sides of the lifting surface. lspec =",
"= {CDi_org_theory:.7f}') print(f'CDi_org = {lres_org.trres.CDi:.7f}') print(f'CDi_ell_theory = {CDi_ell_theory:.7f}') print(f'CDi_ell = {lopt_ell.trres.CDi:.7f}') print(f'CDi_opt1 =",
"Lift and the resulting lift distribution is Elliptical. # Note: You have to",
"System jsonfilepath = '../files/Straight_Wing_Cosine_100.json' lsys = latticesystem_from_json(jsonfilepath) display(lsys) #%% Original Case alpha =",
"You have to consider root moment for both sides of the lifting surface.",
"Lift L = lres_org.nfres.CL*lres_org.qfs*lsys.sref lell = elliptical_lift_force_distribution(lsys.srfcs[0].strpy, lsys.bref, L) lopt_ell = LatticeOptimum('Equivalent Elliptical',",
"{lopt2.trres.CL:.3f}') print('') print(f'CDi_org_theory = {CDi_org_theory:.7f}') print(f'CDi_org = {lres_org.trres.CDi:.7f}') print(f'CDi_ell_theory = {CDi_ell_theory:.7f}') print(f'CDi_ell =",
"CDi_org_theory = lres_org.trres.CL**2/pi/lsys.ar/lres_org.trres.e CDi_ell_theory = lres_org.trres.CL**2/pi/lsys.ar print(f'CL_org = {lres_org.trres.CL:.3f}') print(f'CL_ell = {lopt_ell.trres.CL:.3f}') print(f'CL_opt1",
"LatticeResult('Baseline', lsys) lres_org.set_state(alpha=alpha, beta=beta) display(lres_org) #%% Equivalent Elliptical Lift L = lres_org.nfres.CL*lres_org.qfs*lsys.sref lell",
"mspec, strplst=lsys.mstrpi) phi2, lam2 = lopt2.optimum_lift_force_distribution() display(lopt2) #%% Plot Distributions axl = None",
"#%% Plot Distributions axl = None axl = lres_org.plot_trefftz_lift_force_distribution(ax=axl) axl = lopt_ell.plot_trefftz_lift_force_distribution(ax=axl) axl",
"Load Dependencies from math import pi from IPython.display import display from pyvlm import",
"None axl = lres_org.plot_trefftz_lift_force_distribution(ax=axl) axl = lopt_ell.plot_trefftz_lift_force_distribution(ax=axl) axl = lopt1.plot_trefftz_lift_force_distribution(ax=axl) axl = lopt2.plot_trefftz_lift_force_distribution(ax=axl)",
"{CDi_ell_theory:.7f}') print(f'CDi_ell = {lopt_ell.trres.CDi:.7f}') print(f'CDi_opt1 = {lopt1.trres.CDi:.7f}') print(f'CDi_opt2 = {lopt2.trres.CDi:.7f}') print('') print(f'Efficiency Improvement",
"the resulting lift distribution is Elliptical. # Note: You have to consider root",
"lsys = latticesystem_from_json(jsonfilepath) display(lsys) #%% Original Case alpha = 3.0 # degrees beta",
"Only Lift and the resulting lift distribution is Elliptical. # Note: You have",
"75% of the Elliptical Optimimum. # Note: You have to consider both sides",
"have to consider root moment for both sides of the lifting surface. lopt1",
"sides of the lifting surface. lopt1 = LatticeOptimum('Unconstrained Optimised', lsys)#, sym=False) lopt1.set_state() lopt1.add_constraint('L',",
"= lopt2.optimum_lift_force_distribution() display(lopt2) #%% Plot Distributions axl = None axl = lres_org.plot_trefftz_lift_force_distribution(ax=axl) axl",
"Equivalent Elliptical Lift L = lres_org.nfres.CL*lres_org.qfs*lsys.sref lell = elliptical_lift_force_distribution(lsys.srfcs[0].strpy, lsys.bref, L) lopt_ell =",
"= lres_org.trres.CL**2/pi/lsys.ar print(f'CL_org = {lres_org.trres.CL:.3f}') print(f'CL_ell = {lopt_ell.trres.CL:.3f}') print(f'CL_opt1 = {lopt1.trres.CL:.3f}') print(f'CL_opt2 =",
"#%% Equivalent Elliptical Lift L = lres_org.nfres.CL*lres_org.qfs*lsys.sref lell = elliptical_lift_force_distribution(lsys.srfcs[0].strpy, lsys.bref, L) lopt_ell",
"Optimum # Constrain Only Lift and the resulting lift distribution is Elliptical. #",
"speed=1.0) display(lopt_ell) #%% Calculate Unconstrained Optimum # Constrain Only Lift and the resulting",
"_ = axl.set_ylabel('Lift Distribution') _ = axl.set_xlabel('Span Position') #%% Print Results CDi_org_theory =",
"lopt1.record[1].value*0.75 lopt2 = LatticeOptimum('Constrained Optimised', lsys)#, sym=False) lopt2.set_state() lopt2.add_constraint('L', L) lopt2.add_constraint('l', lspec, strplst=lsys.lstrpi)",
"pyvlm.tools import elliptical_lift_force_distribution #%% Create Lattice System jsonfilepath = '../files/Straight_Wing_Cosine_100.json' lsys = latticesystem_from_json(jsonfilepath)",
"both sides of the lifting surface. lopt1 = LatticeOptimum('Unconstrained Optimised', lsys)#, sym=False) lopt1.set_state()",
"import elliptical_lift_force_distribution #%% Create Lattice System jsonfilepath = '../files/Straight_Wing_Cosine_100.json' lsys = latticesystem_from_json(jsonfilepath) display(lsys)",
"axl.set_ylabel('Lift Distribution') _ = axl.set_xlabel('Span Position') #%% Print Results CDi_org_theory = lres_org.trres.CL**2/pi/lsys.ar/lres_org.trres.e CDi_ell_theory",
"= '../files/Straight_Wing_Cosine_100.json' lsys = latticesystem_from_json(jsonfilepath) display(lsys) #%% Original Case alpha = 3.0 #",
"lopt1.set_state() lopt1.add_constraint('L', L) lopt1.add_record('l', strplst=lsys.lstrpi) lopt1.add_record('l', strplst=lsys.mstrpi) phi1, lam1 = lopt1.optimum_lift_force_distribution() display(lopt1) #%%",
"lopt_ell.plot_trefftz_lift_force_distribution(ax=axl) axl = lopt1.plot_trefftz_lift_force_distribution(ax=axl) axl = lopt2.plot_trefftz_lift_force_distribution(ax=axl) _ = axl.set_ylabel('Lift Distribution') _ =",
"Optimum # Constrain Root Bending Moment (Rolling Moment) to 75% of the Elliptical",
"elliptical_lift_force_distribution #%% Create Lattice System jsonfilepath = '../files/Straight_Wing_Cosine_100.json' lsys = latticesystem_from_json(jsonfilepath) display(lsys) #%%",
"Unconstrained Optimum # Constrain Only Lift and the resulting lift distribution is Elliptical.",
"lspec, strplst=lsys.lstrpi) lopt2.add_constraint('l', mspec, strplst=lsys.mstrpi) phi2, lam2 = lopt2.optimum_lift_force_distribution() display(lopt2) #%% Plot Distributions",
"strplst=lsys.lstrpi) lopt1.add_record('l', strplst=lsys.mstrpi) phi1, lam1 = lopt1.optimum_lift_force_distribution() display(lopt1) #%% Calculate Constrained Optimum #",
"moment for both sides of the lifting surface. lopt1 = LatticeOptimum('Unconstrained Optimised', lsys)#,",
"print(f'CL_org = {lres_org.trres.CL:.3f}') print(f'CL_ell = {lopt_ell.trres.CL:.3f}') print(f'CL_opt1 = {lopt1.trres.CL:.3f}') print(f'CL_opt2 = {lopt2.trres.CL:.3f}') print('')",
"lsys)#, sym=False) lopt1.set_state() lopt1.add_constraint('L', L) lopt1.add_record('l', strplst=lsys.lstrpi) lopt1.add_record('l', strplst=lsys.mstrpi) phi1, lam1 = lopt1.optimum_lift_force_distribution()",
"axl = lopt1.plot_trefftz_lift_force_distribution(ax=axl) axl = lopt2.plot_trefftz_lift_force_distribution(ax=axl) _ = axl.set_ylabel('Lift Distribution') _ = axl.set_xlabel('Span",
"lopt1.add_constraint('L', L) lopt1.add_record('l', strplst=lsys.lstrpi) lopt1.add_record('l', strplst=lsys.mstrpi) phi1, lam1 = lopt1.optimum_lift_force_distribution() display(lopt1) #%% Calculate",
"lopt2.add_constraint('L', L) lopt2.add_constraint('l', lspec, strplst=lsys.lstrpi) lopt2.add_constraint('l', mspec, strplst=lsys.mstrpi) phi2, lam2 = lopt2.optimum_lift_force_distribution() display(lopt2)",
"= None axl = lres_org.plot_trefftz_lift_force_distribution(ax=axl) axl = lopt_ell.plot_trefftz_lift_force_distribution(ax=axl) axl = lopt1.plot_trefftz_lift_force_distribution(ax=axl) axl =",
"#%% Original Case alpha = 3.0 # degrees beta = 0.0 # degrees",
"CDi_ell_theory = lres_org.trres.CL**2/pi/lsys.ar print(f'CL_org = {lres_org.trres.CL:.3f}') print(f'CL_ell = {lopt_ell.trres.CL:.3f}') print(f'CL_opt1 = {lopt1.trres.CL:.3f}') print(f'CL_opt2",
"surface. lspec = lopt1.record[0].value*0.75 mspec = lopt1.record[1].value*0.75 lopt2 = LatticeOptimum('Constrained Optimised', lsys)#, sym=False)",
"'../files/Straight_Wing_Cosine_100.json' lsys = latticesystem_from_json(jsonfilepath) display(lsys) #%% Original Case alpha = 3.0 # degrees"
] |
[
"= [ path('', views.review, name='review'), path('avaloq/', include('avaloq_app.urls')), path('admin/', admin.site.urls), path('accounts/', include('registration.backends.default.urls')), ] handler404",
"views.review, name='review'), path('avaloq/', include('avaloq_app.urls')), path('admin/', admin.site.urls), path('accounts/', include('registration.backends.default.urls')), ] handler404 = 'avaloq_app.views.page_not_found' handler500='avaloq_app.views.server_error'",
"admin from django.urls import path, include from avaloq_app import views urlpatterns = [",
"urlpatterns = [ path('', views.review, name='review'), path('avaloq/', include('avaloq_app.urls')), path('admin/', admin.site.urls), path('accounts/', include('registration.backends.default.urls')), ]",
"include from avaloq_app import views urlpatterns = [ path('', views.review, name='review'), path('avaloq/', include('avaloq_app.urls')),",
"from django.urls import path, include from avaloq_app import views urlpatterns = [ path('',",
"path, include from avaloq_app import views urlpatterns = [ path('', views.review, name='review'), path('avaloq/',",
"name='review'), path('avaloq/', include('avaloq_app.urls')), path('admin/', admin.site.urls), path('accounts/', include('registration.backends.default.urls')), ] handler404 = 'avaloq_app.views.page_not_found' handler500='avaloq_app.views.server_error' handler400='avaloq_app.views.bad_request'",
"import path, include from avaloq_app import views urlpatterns = [ path('', views.review, name='review'),",
"import views urlpatterns = [ path('', views.review, name='review'), path('avaloq/', include('avaloq_app.urls')), path('admin/', admin.site.urls), path('accounts/',",
"views urlpatterns = [ path('', views.review, name='review'), path('avaloq/', include('avaloq_app.urls')), path('admin/', admin.site.urls), path('accounts/', include('registration.backends.default.urls')),",
"path('avaloq/', include('avaloq_app.urls')), path('admin/', admin.site.urls), path('accounts/', include('registration.backends.default.urls')), ] handler404 = 'avaloq_app.views.page_not_found' handler500='avaloq_app.views.server_error' handler400='avaloq_app.views.bad_request' handler403='avaloq_app.views.permission_denied'",
"from django.contrib import admin from django.urls import path, include from avaloq_app import views",
"[ path('', views.review, name='review'), path('avaloq/', include('avaloq_app.urls')), path('admin/', admin.site.urls), path('accounts/', include('registration.backends.default.urls')), ] handler404 =",
"path('', views.review, name='review'), path('avaloq/', include('avaloq_app.urls')), path('admin/', admin.site.urls), path('accounts/', include('registration.backends.default.urls')), ] handler404 = 'avaloq_app.views.page_not_found'",
"django.contrib import admin from django.urls import path, include from avaloq_app import views urlpatterns",
"import admin from django.urls import path, include from avaloq_app import views urlpatterns =",
"avaloq_app import views urlpatterns = [ path('', views.review, name='review'), path('avaloq/', include('avaloq_app.urls')), path('admin/', admin.site.urls),",
"from avaloq_app import views urlpatterns = [ path('', views.review, name='review'), path('avaloq/', include('avaloq_app.urls')), path('admin/',",
"django.urls import path, include from avaloq_app import views urlpatterns = [ path('', views.review,"
] |
[
"print(\"\\n\\t- Right click the opengui.bat\") print(\"\\t- Select Properties\") print(\"\\t- Click the Shortcut tab\")",
") print(\" =====================================================\\n\") # menu def start(): os.system(\"cls || clear\") print(\"\"\" __ __",
"[ENTER] >>> \") return True # launch_teams(\"\\\\\") else: print(\" Wrong link\") print(\" Try",
"link): open_link(link) launch_gmeet(\"\\\\\") elif re.search(\".zoom.us\", link): open_link(link) launch_zoom(\"\\\\\") elif re.search(\"teams.live\", link): print(\" Chori....\")",
"meeting\") alias = input(\" [User] >>> \") print(\" Now paste your meeting invite",
"on that number\") print(\"Press ENTER to get the menu. To exit press CTRL+C\")",
"find_whom_to_call(link), ).pack(padx=10) window_main.mainloop() # link opener def open_link(link): webbrowser.open(link) f.close() print(\" Waiting for",
"tkinter.Tk(className=\" Meeting Launcher\") frame = tkinter.Frame(window_main) frame.pack(expand=True, padx=10, pady=20) tkinter.Label(frame, text=\"Select your meeting",
"def validate(link): if re.search(\"meet.google.com\", link): return True elif re.search(\"zoom\", link): return True elif",
"yaml.dump(meetings, f) # open_link(link) find_whom_to_call(link) if len(sys.argv) == 1: start() else: arg1 =",
"\") print(\" Now paste your meeting invite link\") link = input(\" [User] >>>",
"to open [\" + loading_symbol + \"]\", end=\"\") launch_gmeet(\"/\") else: print(\"\\r Waiting for",
"\") meetings[\"meetings\"].append(dict({alias: link})) with open(file + \"meeting.yml\", \"w\") as f: yaml.dump(meetings, f) #",
"y) # # except TypeError: # if loading_symbol == \"\\\\\": # print(\"\\r Waiting",
"pyautogui.click(x, y) except TypeError: if loading_symbol == \"\\\\\": print(\"\\r Waiting for browser to",
"arg1.lower() == \"--version\" or arg1.lower() == \"-v\": print(\"Version: 1.0.1\") else: display_help() except KeyboardInterrupt:",
"try: # x, y = pyautogui.locateCenterOnScreen( # file+\"Zoom-Launch-Meeting-Button.png\", confidence=0.8 # ) # pyautogui.click(x,",
"|| clear\") print(\"\"\" __ __ __ __ __ __ _ _ ___ _",
"open_link(link) launch_zoom(\"\\\\\") elif re.search(\"teams.live\", link): print(\" Chori....\") print(\" I'm can't launch microsoft teams",
"confidence=0.8 # ) # pyautogui.click(x, y) # # except TypeError: # if loading_symbol",
"open [\" + loading_symbol + \"]\", end=\"\") launch_gmeet(\"/\") else: print(\"\\r Waiting for browser",
"frame = tkinter.Frame(window_main) frame.pack(expand=True, padx=10, pady=20) tkinter.Label(frame, text=\"Select your meeting to open\", font=(\"Arial\",",
"True elif re.search(\"teams.live\", link): print(\" Chori....\") print(\" I'm can't launch microsoft teams but",
"more_option(opt) # GUI def gui(): window_main = tkinter.Tk(className=\" Meeting Launcher\") frame = tkinter.Frame(window_main)",
"for you\") input(\" [ENTER] >>> \") open_link(link) # launch_teams(\"\\\\\") else: print(\"Wrong link\") start()",
"menu def start(): os.system(\"cls || clear\") print(\"\"\" __ __ __ __ __ __",
"meetings[\"meetings\"]: x = meeting.keys() tkinter.Button( frame, text=list(x)[0], height=\"2\", width=\"40\", bg=\"white\", command=lambda link=meeting[list(x)[0]]: find_whom_to_call(link),",
"teams but I can open it for you\") input(\" [ENTER] >>> \") return",
"else: print(\" Incorrect option\") start() # Displaying Help def display_help(): print(\"\\n =====================================================\") print(\"",
"1 print(\" Type the id number to delete\") alias = int(input(\" [User] >>>",
"/__\\\\ ( )( )( \\\\( )/ __)( )_( )( ___)( _ \\\\ )",
"that number\") print(\"Press ENTER to get the menu. To exit press CTRL+C\") start()",
"Waiting for browser to open [\" + loading_symbol + \"]\", end=\"\") launch_gmeet(\"/\") else:",
"Loader=yaml.FullLoader) except FileNotFoundError: print(\"Give alias for your meeting\") alias = input(\"[User] >>> \")",
"(__ ) _ ( )__) ) / (_/\\\\/\\\\_) (____)(__)(__)(______)(_)\\\\_)\\\\___)(_) (_)(____)(_)\\\\_) \"\"\") print(\"==================\") print(\"1.",
"print(\"Incorrect option\") start more_option(opt) # GUI def gui(): window_main = tkinter.Tk(className=\" Meeting Launcher\")",
"print(\"Give alias for your meeting\") alias = input(\"[User] >>> \") print(\"Now paste your",
"meeting\") print(\"3. Show meeting\") print(\"4. Attend meeting\") print(\"5. Shortcut\") print(\"6. Exit\") print(\"==================\") try:",
"example, if you press the P key,the key combination to run this shortcut",
"+ \"]\", end=\"\") launch_gmeet(\"/\") else: print(\"\\r Waiting for browser to open [\" +",
"= tkinter.Tk(className=\" Meeting Launcher\") frame = tkinter.Frame(window_main) frame.pack(expand=True, padx=10, pady=20) tkinter.Label(frame, text=\"Select your",
"input(\" [ENTER] >>> \") open_link(link) # launch_teams(\"\\\\\") else: print(\"Wrong link\") start() def validate(link):",
"print(\"\\r Waiting for browser to open [\" + loading_symbol + \"]\", end=\"\") launch_zoom(\"\\\\\")",
"# print(\"\\r Waiting for browser to open [\" + loading_symbol + \"]\", end=\"\")",
"print(\"6. Exit\") print(\"==================\") try: opt = int(input(\"[User] >>> \")) except ValueError: print(\"Incorrect option\")",
"Wrong link\") print(\" Try again\") input(\" [ENTER] >>> \") return False try: if",
"KeyboardInterrupt: os.system(\"cls || clear\") print(\"\"\" __ __ __ __ __ __ _ _",
"end=\"\") # launch_teams(\"\\\\\") def find_whom_to_call(link): if re.search(\"meet.google.com\", link): open_link(link) launch_gmeet(\"\\\\\") elif re.search(\".zoom.us\", link):",
"i += 1 print(\" Select the meeting number to start\") alias = int(input(\"",
"launch_zoom(\"\\\\\") def launch_gmeet(loading_symbol): try: x, y = pyautogui.locateCenterOnScreen( file + \"google_meet_join.png\", confidence=0.8 )",
"\".\" + ((5 - len(str(i))) * \" \"), list(x)[0]) i += 1 input(\"\\n",
"Attend meeting\") print(\"5. Shortcut\") print(\"6. Exit\") print(\"==================\") try: opt = int(input(\"[User] >>> \"))",
")__) ) / (_/\\\\/\\\\_) (____)(__)(__)(______)(_)\\\\_)\\\\___)(_) (_)(____)(_)\\\\_) \"\"\") print(\"==================\") print(\"1. Add meeting\") print(\"2. Remove",
"the meeting number to start\") alias = int(input(\" [User] >>> \")) print() open_key_link(meetings[\"meetings\"][alias",
"if len(sys.argv) == 1: start() else: arg1 = sys.argv[1] if re.match(r\"[0-9]*\", arg1).group(): i",
"- 1]) except IndexError: print(\"There is no data on that number\") print(\"Press ENTER",
"\"\\\\\": # print(\"\\r Waiting for browser to open [\" + loading_symbol + \"]\",",
") for meeting in meetings[\"meetings\"]: x = meeting.keys() tkinter.Button( frame, text=list(x)[0], height=\"2\", width=\"40\",",
"[ENTER] >>> \") print() # Exit elif opt == 6: exit() else: print(\"",
"pady=20) tkinter.Label(frame, text=\"Select your meeting to open\", font=(\"Arial\", 12)).pack( pady=10 ) for meeting",
"link opener def open_link(link): webbrowser.open(link) f.close() print(\" Waiting for browser to open\", end=\"\")",
"\") meetings[\"meetings\"].append(dict({alias: link})) if validate(link): with open(file + \"meeting.yml\", \"w\") as f: yaml.dump(meetings,",
"Remove elif opt == 2: i = 1 print(\"\\n Id Alias\") for meeting",
"opt == 4: i = 1 print(\"\\n Id Alias\") for meeting in meetings[\"meetings\"]:",
"with open(file + \"meeting.yml\", \"r\") as f: meetings = yaml.load(f, Loader=yaml.FullLoader) except FileNotFoundError:",
"link\") link = input(\"[User] >>> \") meetings[\"meetings\"].append(dict({alias: link})) with open(file + \"meeting.yml\", \"w\")",
"open(file + \"meeting.yml\", \"r\") as f: meetings = yaml.load(f, Loader=yaml.FullLoader) except FileNotFoundError: print(\"Give",
"def find_whom_to_call(link): if re.search(\"meet.google.com\", link): open_link(link) launch_gmeet(\"\\\\\") elif re.search(\".zoom.us\", link): open_link(link) launch_zoom(\"\\\\\") elif",
"number to start\") alias = int(input(\" [User] >>> \")) print() open_key_link(meetings[\"meetings\"][alias - 1])",
"def more_option(opt): os.system(\"cls || clear\") # Add if opt == 1: print(\" Give",
"for browser to open\", end=\"\") # banana peeler :) (gives link from yaml)",
"number\") print(\"Press ENTER to get the menu. To exit press CTRL+C\") start() elif",
"pyautogui import tkinter file = __file__[:-7] meetings = {\"meetings\": []} def more_option(opt): os.system(\"cls",
"Right click the opengui.bat\") print(\"\\t- Select Properties\") print(\"\\t- Click the Shortcut tab\") print(",
"# link opener def open_link(link): webbrowser.open(link) f.close() print(\" Waiting for browser to open\",",
"1: print(\" Give alias for your meeting\") alias = input(\" [User] >>> \")",
"press the P key,the key combination to run this shortcut is `CTRL+ALT+P`\"\"\" )",
") / (_/\\\\/\\\\_) (____)(__)(__)(______)(_)\\\\_)\\\\___)(_) (_)(____)(_)\\\\_) \"\"\") print(\"==================\") print(\"1. Add meeting\") print(\"2. Remove meeting\")",
"[ENTER] >>> \") return False try: if __name__ == \"__main__\": try: with open(file",
"print(\"\\n Id Alias\") for meeting in meetings[\"meetings\"]: x = meeting.keys() print(\" \" +",
"gui(): window_main = tkinter.Tk(className=\" Meeting Launcher\") frame = tkinter.Frame(window_main) frame.pack(expand=True, padx=10, pady=20) tkinter.Label(frame,",
"input(\" [User] >>> \") print(\" Now paste your meeting invite link\") link =",
"meeting number to start\") alias = int(input(\" [User] >>> \")) print() open_key_link(meetings[\"meetings\"][alias -",
"launch_gmeet(\"/\") else: print(\"\\r Waiting for browser to open [\" + loading_symbol + \"]\",",
"os import re import sys import webbrowser import yaml import pyautogui import tkinter",
"open\", font=(\"Arial\", 12)).pack( pady=10 ) for meeting in meetings[\"meetings\"]: x = meeting.keys() tkinter.Button(",
"if re.search(\"meet.google.com\", link): open_link(link) launch_gmeet(\"\\\\\") elif re.search(\".zoom.us\", link): open_link(link) launch_zoom(\"\\\\\") elif re.search(\"teams.live\", link):",
"- len(str(i))) * \" \"), list(x)[0]) i += 1 print(\" Type the id",
"print(x, y) pyautogui.click(x, y) except TypeError: if loading_symbol == \"\\\\\": print(\"\\r Waiting for",
"import tkinter file = __file__[:-7] meetings = {\"meetings\": []} def more_option(opt): os.system(\"cls ||",
"loading_symbol + \"]\", end=\"\") # launch_teams(\"\\\\\") def find_whom_to_call(link): if re.search(\"meet.google.com\", link): open_link(link) launch_gmeet(\"\\\\\")",
"# file+\"Zoom-Launch-Meeting-Button.png\", confidence=0.8 # ) # pyautogui.click(x, y) # # except TypeError: #",
"letter. For example, if you press the P key,the key combination to run",
"gui\") print(\"\\n\\tuse this command\") print(\"\\tpython3 main.py --gui\") print(\" =====================================================\") print(\" To add shortcut",
"link\") link = input(\" [User] >>> \") meetings[\"meetings\"].append(dict({alias: link})) if validate(link): with open(file",
"(_/\\\\/\\\\_) (____)(__)(__)(______)(_)\\\\_)\\\\___)(_) (_)(____)(_)\\\\_) \"\"\") print(\"==================\") print(\"1. Add meeting\") print(\"2. Remove meeting\") print(\"3. Show",
"meeting in meetings[\"meetings\"]: x = meeting.keys() print(\" \" + str(i) + \".\" +",
"/ (_/\\\\/\\\\_) (____)(__)(__)(______)(_)\\\\_)\\\\___)(_) (_)(____)(_)\\\\_) \"\"\") print(\"==================\") print(\"1. Add meeting\") print(\"2. Remove meeting\") print(\"3.",
"+ ((5 - len(str(i))) * \" \"), list(x)[0]) i += 1 input(\"\\n [ENTER]",
"12)).pack( pady=10 ) for meeting in meetings[\"meetings\"]: x = meeting.keys() tkinter.Button( frame, text=list(x)[0],",
"else: display_help() except KeyboardInterrupt: os.system(\"cls || clear\") print(\"\"\" __ __ __ __ __",
"file+\"Zoom-Launch-Meeting-Button.png\", confidence=0.8 # ) # pyautogui.click(x, y) # # except TypeError: # if",
"import re import sys import webbrowser import yaml import pyautogui import tkinter file",
"+ \"meeting.yml\", \"w\") as f: yaml.dump(meetings, f) # open_link(link) find_whom_to_call(link) if len(sys.argv) ==",
"True # launch_teams(\"\\\\\") else: print(\" Wrong link\") print(\" Try again\") input(\" [ENTER] >>>",
"you\") input(\" [ENTER] >>> \") open_link(link) # launch_teams(\"\\\\\") else: print(\"Wrong link\") start() def",
"1 print(\"\\n Id Alias\") for meeting in meetings[\"meetings\"]: x = meeting.keys() print(\" \"",
">>> \") print() # Exit elif opt == 6: exit() else: print(\" Incorrect",
"exit() else: print(\" Incorrect option\") start() # Displaying Help def display_help(): print(\"\\n =====================================================\")",
").pack(padx=10) window_main.mainloop() # link opener def open_link(link): webbrowser.open(link) f.close() print(\" Waiting for browser",
"open\", end=\"\") # banana peeler :) (gives link from yaml) def open_key_link(_alias): key",
"end=\"\") launch_gmeet(\"/\") else: print(\"\\r Waiting for browser to open [\" + loading_symbol +",
"\") print(\"Now paste your meeting invite link\") link = input(\"[User] >>> \") meetings[\"meetings\"].append(dict({alias:",
"print(\"Now paste your meeting invite link\") link = input(\"[User] >>> \") meetings[\"meetings\"].append(dict({alias: link}))",
"\"meeting.yml\", \"w\") as f: yaml.dump(meetings, f) # open_link(link) find_whom_to_call(link) if len(sys.argv) == 1:",
"file = __file__[:-7] meetings = {\"meetings\": []} def more_option(opt): os.system(\"cls || clear\") #",
"* \" \"), list(x)[0]) i += 1 input(\"\\n [ENTER] >>> \") print() #",
") (( (__ ) _ ( )__) ) / (_/\\\\/\\\\_) (____)(__)(__)(______)(_)\\\\_)\\\\___)(_) (_)(____)(_)\\\\_) \"\"\")",
"link): print(\" Chori....\") print(\" I'm can't launch microsoft teams but I can open",
"f: yaml.dump(meetings, f) print(\" removed\") input(\"\\n [ENTER] >>> \") print() # Show elif",
"f) print(\" removed\") input(\"\\n [ENTER] >>> \") print() # Show elif opt ==",
"else: print(\"\\r Waiting for browser to open [\" + loading_symbol + \"]\", end=\"\")",
"Help elif opt == 5: display_help() input(\"\\n [ENTER] >>> \") print() # Exit",
"meeting invite link\") link = input(\"[User] >>> \") meetings[\"meetings\"].append(dict({alias: link})) with open(file +",
"== \"-v\": print(\"Version: 1.0.1\") else: display_help() except KeyboardInterrupt: os.system(\"cls || clear\") print(\"\"\" __",
"# try: # x, y = pyautogui.locateCenterOnScreen( # file+\"Zoom-Launch-Meeting-Button.png\", confidence=0.8 # ) #",
"print(\" Give alias for your meeting\") alias = input(\" [User] >>> \") print(\"",
"return True elif re.search(\"teams.live\", link): print(\" Chori....\") print(\" I'm can't launch microsoft teams",
"print(\"\\t- Select Properties\") print(\"\\t- Click the Shortcut tab\") print( \"\"\"\\t- Click in the",
"webbrowser import yaml import pyautogui import tkinter file = __file__[:-7] meetings = {\"meetings\":",
"print(\" To add shortcut in windows\") print(\"\\n\\t- Right click the opengui.bat\") print(\"\\t- Select",
"python3 main.py 1\") print(\" =====================================================\") print(\" To open your meeting from gui\") print(\"\\n\\tuse",
"except ValueError: print(\"Incorrect option\") start more_option(opt) # GUI def gui(): window_main = tkinter.Tk(className=\"",
"\") return True # launch_teams(\"\\\\\") else: print(\" Wrong link\") print(\" Try again\") input(\"",
"open_key_link(meetings[\"meetings\"][i - 1]) except IndexError: print(\"There is no data on that number\") print(\"Press",
"meeting\") alias = input(\"[User] >>> \") print(\"Now paste your meeting invite link\") link",
"open [\" + loading_symbol + \"]\", end=\"\") # launch_teams(\"\\\\\") def find_whom_to_call(link): if re.search(\"meet.google.com\",",
"print(\" I'm can't launch microsoft teams but I can open it for you\")",
"print(\"Press ENTER to get the menu. To exit press CTRL+C\") start() elif arg1.lower()",
") pyautogui.click(x, y) except TypeError: if loading_symbol == \"\\\\\": print(\"\\r Waiting for browser",
"int(arg1) print() try: open_key_link(meetings[\"meetings\"][i - 1]) except IndexError: print(\"There is no data on",
"Select the meeting number to start\") alias = int(input(\" [User] >>> \")) print()",
"return True # launch_teams(\"\\\\\") else: print(\" Wrong link\") print(\" Try again\") input(\" [ENTER]",
"=====================================================\") print(\" To open your meeting from command line\") print(\"\\n\\tCheck this following syntax\")",
"meetings[\"meetings\"].pop(alias - 1) with open(file + \"meeting.yml\", \"w\") as f: yaml.dump(meetings, f) print(\"",
"your meeting to open\", font=(\"Arial\", 12)).pack( pady=10 ) for meeting in meetings[\"meetings\"]: x",
"x, y = pyautogui.locateCenterOnScreen( file + \"Zoom-Launch-Meeting-Button.png\", confidence=0.8 ) pyautogui.click(x, y) except TypeError:",
"# launch_teams(\"\\\\\") else: print(\"Wrong link\") start() def validate(link): if re.search(\"meet.google.com\", link): return True",
"print(\"\"\" __ __ __ __ __ __ _ _ ___ _ _ ____",
"Chori....\") print(\" I'm can't launch microsoft teams but I can open it for",
"open [\" + loading_symbol + \"]\", end=\"\") launch_gmeet(\"\\\\\") # def launch_teams(loading_symbol): # try:",
"Shortcut key box and press a letter. For example, if you press the",
"# pyautogui.click(x, y) # # except TypeError: # if loading_symbol == \"\\\\\": #",
"{\"meetings\": []} def more_option(opt): os.system(\"cls || clear\") # Add if opt == 1:",
"# ) # pyautogui.click(x, y) # # except TypeError: # if loading_symbol ==",
"Waiting for browser to open [\" + loading_symbol + \"]\", end=\"\") launch_gmeet(\"\\\\\") #",
"import pyautogui import tkinter file = __file__[:-7] meetings = {\"meetings\": []} def more_option(opt):",
"meetings = yaml.load(f, Loader=yaml.FullLoader) except FileNotFoundError: print(\"Give alias for your meeting\") alias =",
"if __name__ == \"__main__\": try: with open(file + \"meeting.yml\", \"r\") as f: meetings",
"\\\\/ )___( ) /__\\\\ ( )( )( \\\\( )/ __)( )_( )( ___)(",
"- 1) with open(file + \"meeting.yml\", \"w\") as f: yaml.dump(meetings, f) print(\" removed\")",
"Data is added\") input(\"\\n [ENTER] >>> \") print() else: more_option(1) # Remove elif",
"else: more_option(1) # Remove elif opt == 2: i = 1 print(\"\\n Id",
"print() link = _alias[key] find_whom_to_call(link) # LAUNCHER def launch_zoom(loading_symbol): try: x, y =",
"the P key,the key combination to run this shortcut is `CTRL+ALT+P`\"\"\" ) print(\"",
") _ ( )__) ) / (_/\\\\/\\\\_) (____)(__)(__)(______)(_)\\\\_)\\\\___)(_) (_)(____)(_)\\\\_) \"\"\") print(\"==================\") print(\"1. Add",
"+ \"]\", end=\"\") # launch_teams(\"\\\\\") def find_whom_to_call(link): if re.search(\"meet.google.com\", link): open_link(link) launch_gmeet(\"\\\\\") elif",
"((5 - len(str(i))) * \" \"), list(x)[0]) i += 1 input(\"\\n [ENTER] >>>",
"x = meeting.keys() print(\" \" + str(i) + \".\" + ((5 - len(str(i)))",
"opt = int(input(\"[User] >>> \")) except ValueError: print(\"Incorrect option\") start more_option(opt) # GUI",
"alias = input(\" [User] >>> \") print(\" Now paste your meeting invite link\")",
"webbrowser.open(link) f.close() print(\" Waiting for browser to open\", end=\"\") # banana peeler :)",
"frame.pack(expand=True, padx=10, pady=20) tkinter.Label(frame, text=\"Select your meeting to open\", font=(\"Arial\", 12)).pack( pady=10 )",
"arg1.lower() == \"-v\": print(\"Version: 1.0.1\") else: display_help() except KeyboardInterrupt: os.system(\"cls || clear\") print(\"\"\"",
"Waiting for browser to open [\" + loading_symbol + \"]\", end=\"\") launch_zoom(\"\\\\\") def",
"except IndexError: print(\"There is no data on that number\") print(\"Press ENTER to get",
"print(\" Type the id number to delete\") alias = int(input(\" [User] >>> \"))",
"the id number to delete\") alias = int(input(\" [User] >>> \")) meetings[\"meetings\"].pop(alias -",
"+ \".\" + ((5 - len(str(i))) * \" \"), list(x)[0]) i += 1",
"print(\" Now paste your meeting invite link\") link = input(\" [User] >>> \")",
"\"--version\" or arg1.lower() == \"-v\": print(\"Version: 1.0.1\") else: display_help() except KeyboardInterrupt: os.system(\"cls ||",
"is `CTRL+ALT+P`\"\"\" ) print(\" =====================================================\\n\") # menu def start(): os.system(\"cls || clear\") print(\"\"\"",
"else: # print(\"\\r Waiting for browser to open [\" + loading_symbol + \"]\",",
"\") print() # Show elif opt == 3: i = 1 print(\"\\n Id",
"\"--gui\": print(\"Opening gui\") gui() elif arg1.lower() == \"--version\" or arg1.lower() == \"-v\": print(\"Version:",
"\"meeting.yml\", \"w\") as f: yaml.dump(meetings, f) print(\" removed\") input(\"\\n [ENTER] >>> \") print()",
"= int(input(\"[User] >>> \")) except ValueError: print(\"Incorrect option\") start more_option(opt) # GUI def",
"== \"--version\" or arg1.lower() == \"-v\": print(\"Version: 1.0.1\") else: display_help() except KeyboardInterrupt: os.system(\"cls",
"input(\"\\n [ENTER] >>> \") print() else: more_option(1) # Remove elif opt == 2:",
"tkinter.Button( frame, text=list(x)[0], height=\"2\", width=\"40\", bg=\"white\", command=lambda link=meeting[list(x)[0]]: find_whom_to_call(link), ).pack(padx=10) window_main.mainloop() # link",
"[ENTER] >>> \") print() # Show elif opt == 3: i = 1",
"start\") alias = int(input(\" [User] >>> \")) print() open_key_link(meetings[\"meetings\"][alias - 1]) # Help",
"this following syntax\") print(\"\\tpython3 main.py [meeting_number]\") print(\" Example: python3 main.py 1\") print(\" =====================================================\")",
"in meetings[\"meetings\"]: x = meeting.keys() tkinter.Button( frame, text=list(x)[0], height=\"2\", width=\"40\", bg=\"white\", command=lambda link=meeting[list(x)[0]]:",
"try: x, y = pyautogui.locateCenterOnScreen( file + \"google_meet_join.png\", confidence=0.8 ) print(x, y) pyautogui.click(x,",
"\"), list(x)[0]) i += 1 print(\" Select the meeting number to start\") alias",
"list(x)[0]) i += 1 input(\"\\n [ENTER] >>> \") print() # Attend elif opt",
"= int(input(\" [User] >>> \")) meetings[\"meetings\"].pop(alias - 1) with open(file + \"meeting.yml\", \"w\")",
"as f: yaml.dump(meetings, f) # open_link(link) find_whom_to_call(link) if len(sys.argv) == 1: start() else:",
"print(\"\\t- Click the Shortcut tab\") print( \"\"\"\\t- Click in the Shortcut key box",
"pyautogui.locateCenterOnScreen( file + \"Zoom-Launch-Meeting-Button.png\", confidence=0.8 ) pyautogui.click(x, y) except TypeError: if loading_symbol ==",
"Waiting for browser to open\", end=\"\") # banana peeler :) (gives link from",
"loading_symbol + \"]\", end=\"\") launch_gmeet(\"/\") else: print(\"\\r Waiting for browser to open [\"",
">>> \") return True # launch_teams(\"\\\\\") else: print(\" Wrong link\") print(\" Try again\")",
"== \"__main__\": try: with open(file + \"meeting.yml\", \"r\") as f: meetings = yaml.load(f,",
"launch_teams(loading_symbol): # try: # x, y = pyautogui.locateCenterOnScreen( # file+\"Zoom-Launch-Meeting-Button.png\", confidence=0.8 # )",
"line\") print(\"\\n\\tCheck this following syntax\") print(\"\\tpython3 main.py [meeting_number]\") print(\" Example: python3 main.py 1\")",
"_ \\\\ ) ((___))(__ /(__)\\\\ )(__)( ) (( (__ ) _ ( )__)",
"option\") start more_option(opt) # GUI def gui(): window_main = tkinter.Tk(className=\" Meeting Launcher\") frame",
"yaml.load(f, Loader=yaml.FullLoader) except FileNotFoundError: print(\"Give alias for your meeting\") alias = input(\"[User] >>>",
"end=\"\") launch_gmeet(\"\\\\\") # def launch_teams(loading_symbol): # try: # x, y = pyautogui.locateCenterOnScreen( #",
"== 3: i = 1 print(\"\\n Id Alias\") for meeting in meetings[\"meetings\"]: x",
"tkinter file = __file__[:-7] meetings = {\"meetings\": []} def more_option(opt): os.system(\"cls || clear\")",
"+= 1 print(\" Type the id number to delete\") alias = int(input(\" [User]",
"( )__) ) / (_/\\\\/\\\\_) (____)(__)(__)(______)(_)\\\\_)\\\\___)(_) (_)(____)(_)\\\\_) \"\"\") print(\"==================\") print(\"1. Add meeting\") print(\"2.",
"\"]\", end=\"\") launch_gmeet(\"/\") else: print(\"\\r Waiting for browser to open [\" + loading_symbol",
"_ _ ____ ____ ( \\\\/ )___( ) /__\\\\ ( )( )( \\\\(",
"width=\"40\", bg=\"white\", command=lambda link=meeting[list(x)[0]]: find_whom_to_call(link), ).pack(padx=10) window_main.mainloop() # link opener def open_link(link): webbrowser.open(link)",
"print(\"Opening gui\") gui() elif arg1.lower() == \"--version\" or arg1.lower() == \"-v\": print(\"Version: 1.0.1\")",
"print(\" Data is added\") input(\"\\n [ENTER] >>> \") print() else: more_option(1) # Remove",
"link from yaml) def open_key_link(_alias): key = list(_alias)[0] print() link = _alias[key] find_whom_to_call(link)",
"for browser to open [\" + loading_symbol + \"]\", end=\"\") launch_zoom(\"\\\\\") def launch_gmeet(loading_symbol):",
"FileNotFoundError: print(\"Give alias for your meeting\") alias = input(\"[User] >>> \") print(\"Now paste",
"\"]\", end=\"\") launch_gmeet(\"\\\\\") # def launch_teams(loading_symbol): # try: # x, y = pyautogui.locateCenterOnScreen(",
"Properties\") print(\"\\t- Click the Shortcut tab\") print( \"\"\"\\t- Click in the Shortcut key",
"Displaying Help def display_help(): print(\"\\n =====================================================\") print(\" To open your meeting from command",
"meeting in meetings[\"meetings\"]: x = meeting.keys() tkinter.Button( frame, text=list(x)[0], height=\"2\", width=\"40\", bg=\"white\", command=lambda",
"arg1 = sys.argv[1] if re.match(r\"[0-9]*\", arg1).group(): i = int(arg1) print() try: open_key_link(meetings[\"meetings\"][i -",
"= {\"meetings\": []} def more_option(opt): os.system(\"cls || clear\") # Add if opt ==",
"open(file + \"meeting.yml\", \"w\") as f: yaml.dump(meetings, f) print(\" Data is added\") input(\"\\n",
"= tkinter.Frame(window_main) frame.pack(expand=True, padx=10, pady=20) tkinter.Label(frame, text=\"Select your meeting to open\", font=(\"Arial\", 12)).pack(",
"if loading_symbol == \"\\\\\": # print(\"\\r Waiting for browser to open [\" +",
"open_key_link(meetings[\"meetings\"][alias - 1]) # Help elif opt == 5: display_help() input(\"\\n [ENTER] >>>",
"launch_gmeet(\"\\\\\") elif re.search(\".zoom.us\", link): open_link(link) launch_zoom(\"\\\\\") elif re.search(\"teams.live\", link): print(\" Chori....\") print(\" I'm",
"ValueError: print(\"Incorrect option\") start more_option(opt) # GUI def gui(): window_main = tkinter.Tk(className=\" Meeting",
"Alias\") for meeting in meetings[\"meetings\"]: x = meeting.keys() print(\" \" + str(i) +",
"more_option(1) # Remove elif opt == 2: i = 1 print(\"\\n Id Alias\")",
"following syntax\") print(\"\\tpython3 main.py [meeting_number]\") print(\" Example: python3 main.py 1\") print(\" =====================================================\") print(\"",
"browser to open [\" + loading_symbol + \"]\", end=\"\") # launch_teams(\"/\") # else:",
"except FileNotFoundError: print(\"Give alias for your meeting\") alias = input(\"[User] >>> \") print(\"Now",
"print(\" removed\") input(\"\\n [ENTER] >>> \") print() # Show elif opt == 3:",
"(( (__ ) _ ( )__) ) / (_/\\\\/\\\\_) (____)(__)(__)(______)(_)\\\\_)\\\\___)(_) (_)(____)(_)\\\\_) \"\"\") print(\"\\n\\rExited",
"( )( )( \\\\( )/ __)( )_( )( ___)( _ \\\\ ) ((___))(__",
"input(\" [ENTER] >>> \") return False try: if __name__ == \"__main__\": try: with",
"- 1]) # Help elif opt == 5: display_help() input(\"\\n [ENTER] >>> \")",
"False try: if __name__ == \"__main__\": try: with open(file + \"meeting.yml\", \"r\") as",
"import os import re import sys import webbrowser import yaml import pyautogui import",
"print() try: open_key_link(meetings[\"meetings\"][i - 1]) except IndexError: print(\"There is no data on that",
"Give alias for your meeting\") alias = input(\" [User] >>> \") print(\" Now",
"open [\" + loading_symbol + \"]\", end=\"\") launch_zoom(\"\\\\\") def launch_gmeet(loading_symbol): try: x, y",
"Now paste your meeting invite link\") link = input(\" [User] >>> \") meetings[\"meetings\"].append(dict({alias:",
"launch_teams(\"\\\\\") else: print(\"Wrong link\") start() def validate(link): if re.search(\"meet.google.com\", link): return True elif",
"= __file__[:-7] meetings = {\"meetings\": []} def more_option(opt): os.system(\"cls || clear\") # Add",
">>> \") open_link(link) # launch_teams(\"\\\\\") else: print(\"Wrong link\") start() def validate(link): if re.search(\"meet.google.com\",",
"to run this shortcut is `CTRL+ALT+P`\"\"\" ) print(\" =====================================================\\n\") # menu def start():",
"arg1).group(): i = int(arg1) print() try: open_key_link(meetings[\"meetings\"][i - 1]) except IndexError: print(\"There is",
"alias for your meeting\") alias = input(\" [User] >>> \") print(\" Now paste",
"i += 1 input(\"\\n [ENTER] >>> \") print() # Attend elif opt ==",
"print(\"Wrong link\") start() def validate(link): if re.search(\"meet.google.com\", link): return True elif re.search(\"zoom\", link):",
"\" \"), list(x)[0]) i += 1 print(\" Type the id number to delete\")",
"is no data on that number\") print(\"Press ENTER to get the menu. To",
"elif opt == 4: i = 1 print(\"\\n Id Alias\") for meeting in",
"link): open_link(link) launch_zoom(\"\\\\\") elif re.search(\"teams.live\", link): print(\" Chori....\") print(\" I'm can't launch microsoft",
") /__\\\\ ( )( )( \\\\( )/ __)( )_( )( ___)( _ \\\\",
"_ ( )__) ) / (_/\\\\/\\\\_) (____)(__)(__)(______)(_)\\\\_)\\\\___)(_) (_)(____)(_)\\\\_) \"\"\") print(\"==================\") print(\"1. Add meeting\")",
"print(\"\\r Waiting for browser to open [\" + loading_symbol + \"]\", end=\"\") launch_gmeet(\"\\\\\")",
"input(\"\\n [ENTER] >>> \") print() # Attend elif opt == 4: i =",
") # pyautogui.click(x, y) # # except TypeError: # if loading_symbol == \"\\\\\":",
"TypeError: if loading_symbol == \"\\\\\": print(\"\\r Waiting for browser to open [\" +",
"print(\"3. Show meeting\") print(\"4. Attend meeting\") print(\"5. Shortcut\") print(\"6. Exit\") print(\"==================\") try: opt",
"number to delete\") alias = int(input(\" [User] >>> \")) meetings[\"meetings\"].pop(alias - 1) with",
"____ ____ ( \\\\/ )___( ) /__\\\\ ( )( )( \\\\( )/ __)(",
"\")) meetings[\"meetings\"].pop(alias - 1) with open(file + \"meeting.yml\", \"w\") as f: yaml.dump(meetings, f)",
"start(): os.system(\"cls || clear\") print(\"\"\" __ __ __ __ __ __ _ _",
"yaml.dump(meetings, f) print(\" Data is added\") input(\"\\n [ENTER] >>> \") print() else: more_option(1)",
"alias = int(input(\" [User] >>> \")) print() open_key_link(meetings[\"meetings\"][alias - 1]) # Help elif",
"main.py 1\") print(\" =====================================================\") print(\" To open your meeting from gui\") print(\"\\n\\tuse this",
"+ loading_symbol + \"]\", end=\"\") launch_gmeet(\"\\\\\") # def launch_teams(loading_symbol): # try: # x,",
"banana peeler :) (gives link from yaml) def open_key_link(_alias): key = list(_alias)[0] print()",
"+ \"]\", end=\"\") # launch_teams(\"/\") # else: # print(\"\\r Waiting for browser to",
"\"), list(x)[0]) i += 1 print(\" Type the id number to delete\") alias",
"Shortcut tab\") print( \"\"\"\\t- Click in the Shortcut key box and press a",
"print(\" To open your meeting from gui\") print(\"\\n\\tuse this command\") print(\"\\tpython3 main.py --gui\")",
"Show meeting\") print(\"4. Attend meeting\") print(\"5. Shortcut\") print(\"6. Exit\") print(\"==================\") try: opt =",
"in meetings[\"meetings\"]: x = meeting.keys() print(\" \" + str(i) + \".\" + ((5",
"\") print() # Exit elif opt == 6: exit() else: print(\" Incorrect option\")",
"from yaml) def open_key_link(_alias): key = list(_alias)[0] print() link = _alias[key] find_whom_to_call(link) #",
"f: meetings = yaml.load(f, Loader=yaml.FullLoader) except FileNotFoundError: print(\"Give alias for your meeting\") alias",
">>> \") meetings[\"meetings\"].append(dict({alias: link})) if validate(link): with open(file + \"meeting.yml\", \"w\") as f:",
"[\" + loading_symbol + \"]\", end=\"\") launch_zoom(\"/\") else: print(\"\\r Waiting for browser to",
"1: start() else: arg1 = sys.argv[1] if re.match(r\"[0-9]*\", arg1).group(): i = int(arg1) print()",
"_ ___ _ _ ____ ____ ( \\\\/ )___( ) /__\\\\ ( )(",
"find_whom_to_call(link) if len(sys.argv) == 1: start() else: arg1 = sys.argv[1] if re.match(r\"[0-9]*\", arg1).group():",
"# Exit elif opt == 6: exit() else: print(\" Incorrect option\") start() #",
"__ __ __ __ _ _ ___ _ _ ____ ____ ( \\\\/",
"= meeting.keys() tkinter.Button( frame, text=list(x)[0], height=\"2\", width=\"40\", bg=\"white\", command=lambda link=meeting[list(x)[0]]: find_whom_to_call(link), ).pack(padx=10) window_main.mainloop()",
"== \"\\\\\": # print(\"\\r Waiting for browser to open [\" + loading_symbol +",
"re import sys import webbrowser import yaml import pyautogui import tkinter file =",
")_( )( ___)( _ \\\\ ) ((___))(__ /(__)\\\\ )(__)( ) (( (__ )",
"\")) print() open_key_link(meetings[\"meetings\"][alias - 1]) # Help elif opt == 5: display_help() input(\"\\n",
"list(_alias)[0] print() link = _alias[key] find_whom_to_call(link) # LAUNCHER def launch_zoom(loading_symbol): try: x, y",
"with open(file + \"meeting.yml\", \"w\") as f: yaml.dump(meetings, f) print(\" Data is added\")",
"as f: yaml.dump(meetings, f) print(\" removed\") input(\"\\n [ENTER] >>> \") print() # Show",
"\".\" + ((5 - len(str(i))) * \" \"), list(x)[0]) i += 1 print(\"",
"___ _ _ ____ ____ ( \\\\/ )___( ) /__\\\\ ( )( )(",
"launch_zoom(\"\\\\\") elif re.search(\"teams.live\", link): print(\" Chori....\") print(\" I'm can't launch microsoft teams but",
"print(\"==================\") print(\"1. Add meeting\") print(\"2. Remove meeting\") print(\"3. Show meeting\") print(\"4. Attend meeting\")",
"open [\" + loading_symbol + \"]\", end=\"\") launch_zoom(\"/\") else: print(\"\\r Waiting for browser",
"gui() elif arg1.lower() == \"--version\" or arg1.lower() == \"-v\": print(\"Version: 1.0.1\") else: display_help()",
"((___))(__ /(__)\\\\ )(__)( ) (( (__ ) _ ( )__) ) / (_/\\\\/\\\\_)",
"= pyautogui.locateCenterOnScreen( # file+\"Zoom-Launch-Meeting-Button.png\", confidence=0.8 # ) # pyautogui.click(x, y) # # except",
"print(\"5. Shortcut\") print(\"6. Exit\") print(\"==================\") try: opt = int(input(\"[User] >>> \")) except ValueError:",
"print(\"\\tpython3 main.py [meeting_number]\") print(\" Example: python3 main.py 1\") print(\" =====================================================\") print(\" To open",
"loading_symbol + \"]\", end=\"\") # launch_teams(\"/\") # else: # print(\"\\r Waiting for browser",
"\"w\") as f: yaml.dump(meetings, f) # open_link(link) find_whom_to_call(link) if len(sys.argv) == 1: start()",
"link): return True elif re.search(\"teams.live\", link): print(\" Chori....\") print(\" I'm can't launch microsoft",
"(____)(__)(__)(______)(_)\\\\_)\\\\___)(_) (_)(____)(_)\\\\_) \"\"\") print(\"==================\") print(\"1. Add meeting\") print(\"2. Remove meeting\") print(\"3. Show meeting\")",
"6: exit() else: print(\" Incorrect option\") start() # Displaying Help def display_help(): print(\"\\n",
"Click the Shortcut tab\") print( \"\"\"\\t- Click in the Shortcut key box and",
"elif opt == 3: i = 1 print(\"\\n Id Alias\") for meeting in",
"find_whom_to_call(link): if re.search(\"meet.google.com\", link): open_link(link) launch_gmeet(\"\\\\\") elif re.search(\".zoom.us\", link): open_link(link) launch_zoom(\"\\\\\") elif re.search(\"teams.live\",",
"TypeError: # if loading_symbol == \"\\\\\": # print(\"\\r Waiting for browser to open",
"f) print(\" Data is added\") input(\"\\n [ENTER] >>> \") print() else: more_option(1) #",
"input(\"[User] >>> \") meetings[\"meetings\"].append(dict({alias: link})) with open(file + \"meeting.yml\", \"w\") as f: yaml.dump(meetings,",
"with open(file + \"meeting.yml\", \"w\") as f: yaml.dump(meetings, f) print(\" removed\") input(\"\\n [ENTER]",
"end=\"\") launch_zoom(\"/\") else: print(\"\\r Waiting for browser to open [\" + loading_symbol +",
"\") return False try: if __name__ == \"__main__\": try: with open(file + \"meeting.yml\",",
"[User] >>> \") print(\" Now paste your meeting invite link\") link = input(\"",
"y) except TypeError: if loading_symbol == \"\\\\\": print(\"\\r Waiting for browser to open",
"print( \"\"\"\\t- Click in the Shortcut key box and press a letter. For",
"f.close() print(\" Waiting for browser to open\", end=\"\") # banana peeler :) (gives",
"\"__main__\": try: with open(file + \"meeting.yml\", \"r\") as f: meetings = yaml.load(f, Loader=yaml.FullLoader)",
"# menu def start(): os.system(\"cls || clear\") print(\"\"\" __ __ __ __ __",
"= pyautogui.locateCenterOnScreen( file + \"Zoom-Launch-Meeting-Button.png\", confidence=0.8 ) pyautogui.click(x, y) except TypeError: if loading_symbol",
"= 1 print(\"\\n Id Alias\") for meeting in meetings[\"meetings\"]: x = meeting.keys() print(\"",
"import webbrowser import yaml import pyautogui import tkinter file = __file__[:-7] meetings =",
"\") print() # Attend elif opt == 4: i = 1 print(\"\\n Id",
"windows\") print(\"\\n\\t- Right click the opengui.bat\") print(\"\\t- Select Properties\") print(\"\\t- Click the Shortcut",
"it for you\") input(\" [ENTER] >>> \") return True # launch_teams(\"\\\\\") else: print(\"",
"for browser to open [\" + loading_symbol + \"]\", end=\"\") launch_zoom(\"/\") else: print(\"\\r",
"to start\") alias = int(input(\" [User] >>> \")) print() open_key_link(meetings[\"meetings\"][alias - 1]) #",
"len(str(i))) * \" \"), list(x)[0]) i += 1 print(\" Select the meeting number",
"added\") input(\"\\n [ENTER] >>> \") print() else: more_option(1) # Remove elif opt ==",
"open your meeting from command line\") print(\"\\n\\tCheck this following syntax\") print(\"\\tpython3 main.py [meeting_number]\")",
"# if loading_symbol == \"\\\\\": # print(\"\\r Waiting for browser to open [\"",
"meeting.keys() tkinter.Button( frame, text=list(x)[0], height=\"2\", width=\"40\", bg=\"white\", command=lambda link=meeting[list(x)[0]]: find_whom_to_call(link), ).pack(padx=10) window_main.mainloop() #",
"1\") print(\" =====================================================\") print(\" To open your meeting from gui\") print(\"\\n\\tuse this command\")",
"file + \"Zoom-Launch-Meeting-Button.png\", confidence=0.8 ) pyautogui.click(x, y) except TypeError: if loading_symbol == \"\\\\\":",
"your meeting invite link\") link = input(\" [User] >>> \") meetings[\"meetings\"].append(dict({alias: link})) if",
"paste your meeting invite link\") link = input(\" [User] >>> \") meetings[\"meetings\"].append(dict({alias: link}))",
"print(\"\\n\\tCheck this following syntax\") print(\"\\tpython3 main.py [meeting_number]\") print(\" Example: python3 main.py 1\") print(\"",
"=====================================================\") print(\" To add shortcut in windows\") print(\"\\n\\t- Right click the opengui.bat\") print(\"\\t-",
"\"]\", end=\"\") # launch_teams(\"\\\\\") def find_whom_to_call(link): if re.search(\"meet.google.com\", link): open_link(link) launch_gmeet(\"\\\\\") elif re.search(\".zoom.us\",",
"tkinter.Label(frame, text=\"Select your meeting to open\", font=(\"Arial\", 12)).pack( pady=10 ) for meeting in",
"print(\"==================\") try: opt = int(input(\"[User] >>> \")) except ValueError: print(\"Incorrect option\") start more_option(opt)",
"# except TypeError: # if loading_symbol == \"\\\\\": # print(\"\\r Waiting for browser",
"print(\" Select the meeting number to start\") alias = int(input(\" [User] >>> \"))",
"To open your meeting from gui\") print(\"\\n\\tuse this command\") print(\"\\tpython3 main.py --gui\") print(\"",
"f: yaml.dump(meetings, f) print(\" Data is added\") input(\"\\n [ENTER] >>> \") print() else:",
"y) pyautogui.click(x, y) except TypeError: if loading_symbol == \"\\\\\": print(\"\\r Waiting for browser",
"ENTER to get the menu. To exit press CTRL+C\") start() elif arg1.lower() ==",
"exit press CTRL+C\") start() elif arg1.lower() == \"--gui\": print(\"Opening gui\") gui() elif arg1.lower()",
"meeting from command line\") print(\"\\n\\tCheck this following syntax\") print(\"\\tpython3 main.py [meeting_number]\") print(\" Example:",
"def display_help(): print(\"\\n =====================================================\") print(\" To open your meeting from command line\") print(\"\\n\\tCheck",
"file + \"google_meet_join.png\", confidence=0.8 ) print(x, y) pyautogui.click(x, y) except TypeError: if loading_symbol",
"# # except TypeError: # if loading_symbol == \"\\\\\": # print(\"\\r Waiting for",
"# launch_teams(\"\\\\\") def find_whom_to_call(link): if re.search(\"meet.google.com\", link): open_link(link) launch_gmeet(\"\\\\\") elif re.search(\".zoom.us\", link): open_link(link)",
"validate(link): with open(file + \"meeting.yml\", \"w\") as f: yaml.dump(meetings, f) print(\" Data is",
"command=lambda link=meeting[list(x)[0]]: find_whom_to_call(link), ).pack(padx=10) window_main.mainloop() # link opener def open_link(link): webbrowser.open(link) f.close() print(\"",
"+= 1 print(\" Select the meeting number to start\") alias = int(input(\" [User]",
"+ \"meeting.yml\", \"r\") as f: meetings = yaml.load(f, Loader=yaml.FullLoader) except FileNotFoundError: print(\"Give alias",
"len(str(i))) * \" \"), list(x)[0]) i += 1 input(\"\\n [ENTER] >>> \") print()",
"GUI def gui(): window_main = tkinter.Tk(className=\" Meeting Launcher\") frame = tkinter.Frame(window_main) frame.pack(expand=True, padx=10,",
"start more_option(opt) # GUI def gui(): window_main = tkinter.Tk(className=\" Meeting Launcher\") frame =",
"open your meeting from gui\") print(\"\\n\\tuse this command\") print(\"\\tpython3 main.py --gui\") print(\" =====================================================\")",
"def start(): os.system(\"cls || clear\") print(\"\"\" __ __ __ __ __ __ _",
"to open\", font=(\"Arial\", 12)).pack( pady=10 ) for meeting in meetings[\"meetings\"]: x = meeting.keys()",
"padx=10, pady=20) tkinter.Label(frame, text=\"Select your meeting to open\", font=(\"Arial\", 12)).pack( pady=10 ) for",
"to delete\") alias = int(input(\" [User] >>> \")) meetings[\"meetings\"].pop(alias - 1) with open(file",
"\"w\") as f: yaml.dump(meetings, f) print(\" Data is added\") input(\"\\n [ENTER] >>> \")",
"key,the key combination to run this shortcut is `CTRL+ALT+P`\"\"\" ) print(\" =====================================================\\n\") #",
"main.py --gui\") print(\" =====================================================\") print(\" To add shortcut in windows\") print(\"\\n\\t- Right click",
"CTRL+C\") start() elif arg1.lower() == \"--gui\": print(\"Opening gui\") gui() elif arg1.lower() == \"--version\"",
"can't launch microsoft teams but I can open it for you\") input(\" [ENTER]",
"Remove meeting\") print(\"3. Show meeting\") print(\"4. Attend meeting\") print(\"5. Shortcut\") print(\"6. Exit\") print(\"==================\")",
"gui\") gui() elif arg1.lower() == \"--version\" or arg1.lower() == \"-v\": print(\"Version: 1.0.1\") else:",
"text=\"Select your meeting to open\", font=(\"Arial\", 12)).pack( pady=10 ) for meeting in meetings[\"meetings\"]:",
"meeting to open\", font=(\"Arial\", 12)).pack( pady=10 ) for meeting in meetings[\"meetings\"]: x =",
"import sys import webbrowser import yaml import pyautogui import tkinter file = __file__[:-7]",
"def open_key_link(_alias): key = list(_alias)[0] print() link = _alias[key] find_whom_to_call(link) # LAUNCHER def",
"except TypeError: if loading_symbol == \"\\\\\": print(\"\\r Waiting for browser to open [\"",
"\" \"), list(x)[0]) i += 1 input(\"\\n [ENTER] >>> \") print() # Attend",
"option\") start() # Displaying Help def display_help(): print(\"\\n =====================================================\") print(\" To open your",
"if you press the P key,the key combination to run this shortcut is",
"loading_symbol + \"]\", end=\"\") launch_zoom(\"\\\\\") def launch_gmeet(loading_symbol): try: x, y = pyautogui.locateCenterOnScreen( file",
"print(\"2. Remove meeting\") print(\"3. Show meeting\") print(\"4. Attend meeting\") print(\"5. Shortcut\") print(\"6. Exit\")",
"paste your meeting invite link\") link = input(\"[User] >>> \") meetings[\"meetings\"].append(dict({alias: link})) with",
"= pyautogui.locateCenterOnScreen( file + \"google_meet_join.png\", confidence=0.8 ) print(x, y) pyautogui.click(x, y) except TypeError:",
"- len(str(i))) * \" \"), list(x)[0]) i += 1 input(\"\\n [ENTER] >>> \")",
"y = pyautogui.locateCenterOnScreen( # file+\"Zoom-Launch-Meeting-Button.png\", confidence=0.8 # ) # pyautogui.click(x, y) # #",
"opt == 6: exit() else: print(\" Incorrect option\") start() # Displaying Help def",
"display_help(): print(\"\\n =====================================================\") print(\" To open your meeting from command line\") print(\"\\n\\tCheck this",
"the Shortcut key box and press a letter. For example, if you press",
"1]) except IndexError: print(\"There is no data on that number\") print(\"Press ENTER to",
"import yaml import pyautogui import tkinter file = __file__[:-7] meetings = {\"meetings\": []}",
"Id Alias\") for meeting in meetings[\"meetings\"]: x = meeting.keys() print(\" \" + str(i)",
"try: with open(file + \"meeting.yml\", \"r\") as f: meetings = yaml.load(f, Loader=yaml.FullLoader) except",
"--gui\") print(\" =====================================================\") print(\" To add shortcut in windows\") print(\"\\n\\t- Right click the",
"== 1: start() else: arg1 = sys.argv[1] if re.match(r\"[0-9]*\", arg1).group(): i = int(arg1)",
"== 5: display_help() input(\"\\n [ENTER] >>> \") print() # Exit elif opt ==",
"(__ ) _ ( )__) ) / (_/\\\\/\\\\_) (____)(__)(__)(______)(_)\\\\_)\\\\___)(_) (_)(____)(_)\\\\_) \"\"\") print(\"\\n\\rExited Successfully\")",
"browser to open\", end=\"\") # banana peeler :) (gives link from yaml) def",
"P key,the key combination to run this shortcut is `CTRL+ALT+P`\"\"\" ) print(\" =====================================================\\n\")",
"invite link\") link = input(\" [User] >>> \") meetings[\"meetings\"].append(dict({alias: link})) if validate(link): with",
"confidence=0.8 ) print(x, y) pyautogui.click(x, y) except TypeError: if loading_symbol == \"\\\\\": print(\"\\r",
"__ __ __ __ __ _ _ ___ _ _ ____ ____ (",
"input(\" [ENTER] >>> \") return True # launch_teams(\"\\\\\") else: print(\" Wrong link\") print(\"",
"I'm can't launch microsoft teams but I can open it for you\") input(\"",
"int(input(\" [User] >>> \")) print() open_key_link(meetings[\"meetings\"][alias - 1]) # Help elif opt ==",
"launch microsoft teams but I can open it for you\") input(\" [ENTER] >>>",
"validate(link): if re.search(\"meet.google.com\", link): return True elif re.search(\"zoom\", link): return True elif re.search(\"teams.live\",",
"= input(\"[User] >>> \") print(\"Now paste your meeting invite link\") link = input(\"[User]",
"+ str(i) + \".\" + ((5 - len(str(i))) * \" \"), list(x)[0]) i",
"i = int(arg1) print() try: open_key_link(meetings[\"meetings\"][i - 1]) except IndexError: print(\"There is no",
"[\" + loading_symbol + \"]\", end=\"\") # launch_teams(\"\\\\\") def find_whom_to_call(link): if re.search(\"meet.google.com\", link):",
"\"Zoom-Launch-Meeting-Button.png\", confidence=0.8 ) pyautogui.click(x, y) except TypeError: if loading_symbol == \"\\\\\": print(\"\\r Waiting",
"__name__ == \"__main__\": try: with open(file + \"meeting.yml\", \"r\") as f: meetings =",
">>> \") print(\"Now paste your meeting invite link\") link = input(\"[User] >>> \")",
"re.match(r\"[0-9]*\", arg1).group(): i = int(arg1) print() try: open_key_link(meetings[\"meetings\"][i - 1]) except IndexError: print(\"There",
"meetings[\"meetings\"]: x = meeting.keys() print(\" \" + str(i) + \".\" + ((5 -",
"= int(arg1) print() try: open_key_link(meetings[\"meetings\"][i - 1]) except IndexError: print(\"There is no data",
"1) with open(file + \"meeting.yml\", \"w\") as f: yaml.dump(meetings, f) print(\" removed\") input(\"\\n",
"print(\" =====================================================\") print(\" To open your meeting from gui\") print(\"\\n\\tuse this command\") print(\"\\tpython3",
"open_link(link) # launch_teams(\"\\\\\") else: print(\"Wrong link\") start() def validate(link): if re.search(\"meet.google.com\", link): return",
"Attend elif opt == 4: i = 1 print(\"\\n Id Alias\") for meeting",
"the menu. To exit press CTRL+C\") start() elif arg1.lower() == \"--gui\": print(\"Opening gui\")",
"open_key_link(_alias): key = list(_alias)[0] print() link = _alias[key] find_whom_to_call(link) # LAUNCHER def launch_zoom(loading_symbol):",
"Waiting for browser to open [\" + loading_symbol + \"]\", end=\"\") # launch_teams(\"\\\\\")",
"Add if opt == 1: print(\" Give alias for your meeting\") alias =",
"# banana peeler :) (gives link from yaml) def open_key_link(_alias): key = list(_alias)[0]",
"browser to open [\" + loading_symbol + \"]\", end=\"\") launch_zoom(\"\\\\\") def launch_gmeet(loading_symbol): try:",
"Show elif opt == 3: i = 1 print(\"\\n Id Alias\") for meeting",
"(_)(____)(_)\\\\_) \"\"\") print(\"==================\") print(\"1. Add meeting\") print(\"2. Remove meeting\") print(\"3. Show meeting\") print(\"4.",
"for you\") input(\" [ENTER] >>> \") return True # launch_teams(\"\\\\\") else: print(\" Wrong",
"id number to delete\") alias = int(input(\" [User] >>> \")) meetings[\"meetings\"].pop(alias - 1)",
"meetings[\"meetings\"].append(dict({alias: link})) with open(file + \"meeting.yml\", \"w\") as f: yaml.dump(meetings, f) # open_link(link)",
"more_option(opt): os.system(\"cls || clear\") # Add if opt == 1: print(\" Give alias",
"\\\\( )/ __)( )_( )( ___)( _ \\\\ ) ((___))(__ /(__)\\\\ )(__)( )",
"and press a letter. For example, if you press the P key,the key",
"re.search(\"meet.google.com\", link): return True elif re.search(\"zoom\", link): return True elif re.search(\"teams.live\", link): print(\"",
"print(\"\\tpython3 main.py --gui\") print(\" =====================================================\") print(\" To add shortcut in windows\") print(\"\\n\\t- Right",
"\"), list(x)[0]) i += 1 input(\"\\n [ENTER] >>> \") print() # Attend elif",
"for your meeting\") alias = input(\" [User] >>> \") print(\" Now paste your",
"tab\") print( \"\"\"\\t- Click in the Shortcut key box and press a letter.",
"+ loading_symbol + \"]\", end=\"\") launch_zoom(\"/\") else: print(\"\\r Waiting for browser to open",
"start() def validate(link): if re.search(\"meet.google.com\", link): return True elif re.search(\"zoom\", link): return True",
"print(\" Try again\") input(\" [ENTER] >>> \") return False try: if __name__ ==",
"f: yaml.dump(meetings, f) # open_link(link) find_whom_to_call(link) if len(sys.argv) == 1: start() else: arg1",
"print(\" Waiting for browser to open\", end=\"\") # banana peeler :) (gives link",
"x, y = pyautogui.locateCenterOnScreen( file + \"google_meet_join.png\", confidence=0.8 ) print(x, y) pyautogui.click(x, y)",
"meeting from gui\") print(\"\\n\\tuse this command\") print(\"\\tpython3 main.py --gui\") print(\" =====================================================\") print(\" To",
"clear\") # Add if opt == 1: print(\" Give alias for your meeting\")",
"text=list(x)[0], height=\"2\", width=\"40\", bg=\"white\", command=lambda link=meeting[list(x)[0]]: find_whom_to_call(link), ).pack(padx=10) window_main.mainloop() # link opener def",
"+ \"]\", end=\"\") launch_zoom(\"\\\\\") def launch_gmeet(loading_symbol): try: x, y = pyautogui.locateCenterOnScreen( file +",
"1 print(\" Select the meeting number to start\") alias = int(input(\" [User] >>>",
"print(\" \" + str(i) + \".\" + ((5 - len(str(i))) * \" \"),",
"+ loading_symbol + \"]\", end=\"\") launch_zoom(\"\\\\\") def launch_gmeet(loading_symbol): try: x, y = pyautogui.locateCenterOnScreen(",
"menu. To exit press CTRL+C\") start() elif arg1.lower() == \"--gui\": print(\"Opening gui\") gui()",
"== 2: i = 1 print(\"\\n Id Alias\") for meeting in meetings[\"meetings\"]: x",
"browser to open [\" + loading_symbol + \"]\", end=\"\") # launch_teams(\"\\\\\") def find_whom_to_call(link):",
"(gives link from yaml) def open_key_link(_alias): key = list(_alias)[0] print() link = _alias[key]",
"__ _ _ ___ _ _ ____ ____ ( \\\\/ )___( ) /__\\\\",
"print(\"\\n =====================================================\") print(\" To open your meeting from command line\") print(\"\\n\\tCheck this following",
"browser to open [\" + loading_symbol + \"]\", end=\"\") launch_zoom(\"/\") else: print(\"\\r Waiting",
"1 input(\"\\n [ENTER] >>> \") print() # Attend elif opt == 4: i",
"open [\" + loading_symbol + \"]\", end=\"\") # launch_teams(\"/\") # else: # print(\"\\r",
"\") open_link(link) # launch_teams(\"\\\\\") else: print(\"Wrong link\") start() def validate(link): if re.search(\"meet.google.com\", link):",
"print() # Show elif opt == 3: i = 1 print(\"\\n Id Alias\")",
"\")) except ValueError: print(\"Incorrect option\") start more_option(opt) # GUI def gui(): window_main =",
"to open [\" + loading_symbol + \"]\", end=\"\") launch_zoom(\"\\\\\") def launch_gmeet(loading_symbol): try: x,",
"True elif re.search(\"zoom\", link): return True elif re.search(\"teams.live\", link): print(\" Chori....\") print(\" I'm",
"alias for your meeting\") alias = input(\"[User] >>> \") print(\"Now paste your meeting",
"= input(\"[User] >>> \") meetings[\"meetings\"].append(dict({alias: link})) with open(file + \"meeting.yml\", \"w\") as f:",
"clear\") print(\"\"\" __ __ __ __ __ __ _ _ ___ _ _",
"# Attend elif opt == 4: i = 1 print(\"\\n Id Alias\") for",
"For example, if you press the P key,the key combination to run this",
"\"]\", end=\"\") launch_zoom(\"/\") else: print(\"\\r Waiting for browser to open [\" + loading_symbol",
"open(file + \"meeting.yml\", \"w\") as f: yaml.dump(meetings, f) print(\" removed\") input(\"\\n [ENTER] >>>",
"else: arg1 = sys.argv[1] if re.match(r\"[0-9]*\", arg1).group(): i = int(arg1) print() try: open_key_link(meetings[\"meetings\"][i",
"if opt == 1: print(\" Give alias for your meeting\") alias = input(\"",
"len(str(i))) * \" \"), list(x)[0]) i += 1 print(\" Type the id number",
"# open_link(link) find_whom_to_call(link) if len(sys.argv) == 1: start() else: arg1 = sys.argv[1] if",
"\"\"\"\\t- Click in the Shortcut key box and press a letter. For example,",
"your meeting invite link\") link = input(\"[User] >>> \") meetings[\"meetings\"].append(dict({alias: link})) with open(file",
"open(file + \"meeting.yml\", \"w\") as f: yaml.dump(meetings, f) # open_link(link) find_whom_to_call(link) if len(sys.argv)",
")(__)( ) (( (__ ) _ ( )__) ) / (_/\\\\/\\\\_) (____)(__)(__)(______)(_)\\\\_)\\\\___)(_) (_)(____)(_)\\\\_)",
"display_help() input(\"\\n [ENTER] >>> \") print() # Exit elif opt == 6: exit()",
") ((___))(__ /(__)\\\\ )(__)( ) (( (__ ) _ ( )__) ) /",
"list(x)[0]) i += 1 print(\" Select the meeting number to start\") alias =",
"launch_teams(\"\\\\\") def find_whom_to_call(link): if re.search(\"meet.google.com\", link): open_link(link) launch_gmeet(\"\\\\\") elif re.search(\".zoom.us\", link): open_link(link) launch_zoom(\"\\\\\")",
"as f: meetings = yaml.load(f, Loader=yaml.FullLoader) except FileNotFoundError: print(\"Give alias for your meeting\")",
"elif arg1.lower() == \"--version\" or arg1.lower() == \"-v\": print(\"Version: 1.0.1\") else: display_help() except",
"- len(str(i))) * \" \"), list(x)[0]) i += 1 print(\" Select the meeting",
"the Shortcut tab\") print( \"\"\"\\t- Click in the Shortcut key box and press",
"# def launch_teams(loading_symbol): # try: # x, y = pyautogui.locateCenterOnScreen( # file+\"Zoom-Launch-Meeting-Button.png\", confidence=0.8",
"Select Properties\") print(\"\\t- Click the Shortcut tab\") print( \"\"\"\\t- Click in the Shortcut",
"str(i) + \".\" + ((5 - len(str(i))) * \" \"), list(x)[0]) i +=",
"input(\" [User] >>> \") meetings[\"meetings\"].append(dict({alias: link})) if validate(link): with open(file + \"meeting.yml\", \"w\")",
"re.search(\"meet.google.com\", link): open_link(link) launch_gmeet(\"\\\\\") elif re.search(\".zoom.us\", link): open_link(link) launch_zoom(\"\\\\\") elif re.search(\"teams.live\", link): print(\"",
"print(\" Wrong link\") print(\" Try again\") input(\" [ENTER] >>> \") return False try:",
"+ ((5 - len(str(i))) * \" \"), list(x)[0]) i += 1 print(\" Type",
"input(\"\\n [ENTER] >>> \") print() # Exit elif opt == 6: exit() else:",
"( \\\\/ )___( ) /__\\\\ ( )( )( \\\\( )/ __)( )_( )(",
"invite link\") link = input(\"[User] >>> \") meetings[\"meetings\"].append(dict({alias: link})) with open(file + \"meeting.yml\",",
"int(input(\"[User] >>> \")) except ValueError: print(\"Incorrect option\") start more_option(opt) # GUI def gui():",
"\\\\ ) ((___))(__ /(__)\\\\ )(__)( ) (( (__ ) _ ( )__) )",
"[]} def more_option(opt): os.system(\"cls || clear\") # Add if opt == 1: print(\"",
"opt == 1: print(\" Give alias for your meeting\") alias = input(\" [User]",
"key box and press a letter. For example, if you press the P",
"[User] >>> \")) meetings[\"meetings\"].pop(alias - 1) with open(file + \"meeting.yml\", \"w\") as f:",
"def launch_gmeet(loading_symbol): try: x, y = pyautogui.locateCenterOnScreen( file + \"google_meet_join.png\", confidence=0.8 ) print(x,",
"[User] >>> \")) print() open_key_link(meetings[\"meetings\"][alias - 1]) # Help elif opt == 5:",
"elif re.search(\"teams.live\", link): print(\" Chori....\") print(\" I'm can't launch microsoft teams but I",
"__file__[:-7] meetings = {\"meetings\": []} def more_option(opt): os.system(\"cls || clear\") # Add if",
"re.search(\"teams.live\", link): print(\" Chori....\") print(\" I'm can't launch microsoft teams but I can",
"LAUNCHER def launch_zoom(loading_symbol): try: x, y = pyautogui.locateCenterOnScreen( file + \"Zoom-Launch-Meeting-Button.png\", confidence=0.8 )",
"opt == 2: i = 1 print(\"\\n Id Alias\") for meeting in meetings[\"meetings\"]:",
"+ ((5 - len(str(i))) * \" \"), list(x)[0]) i += 1 print(\" Select",
"yaml) def open_key_link(_alias): key = list(_alias)[0] print() link = _alias[key] find_whom_to_call(link) # LAUNCHER",
"y = pyautogui.locateCenterOnScreen( file + \"Zoom-Launch-Meeting-Button.png\", confidence=0.8 ) pyautogui.click(x, y) except TypeError: if",
"your meeting\") alias = input(\"[User] >>> \") print(\"Now paste your meeting invite link\")",
">>> \") print(\" Now paste your meeting invite link\") link = input(\" [User]",
"`CTRL+ALT+P`\"\"\" ) print(\" =====================================================\\n\") # menu def start(): os.system(\"cls || clear\") print(\"\"\" __",
"window_main = tkinter.Tk(className=\" Meeting Launcher\") frame = tkinter.Frame(window_main) frame.pack(expand=True, padx=10, pady=20) tkinter.Label(frame, text=\"Select",
"* \" \"), list(x)[0]) i += 1 print(\" Select the meeting number to",
"return True elif re.search(\"zoom\", link): return True elif re.search(\"teams.live\", link): print(\" Chori....\") print(\"",
"def gui(): window_main = tkinter.Tk(className=\" Meeting Launcher\") frame = tkinter.Frame(window_main) frame.pack(expand=True, padx=10, pady=20)",
"Waiting for browser to open [\" + loading_symbol + \"]\", end=\"\") launch_zoom(\"/\") else:",
"removed\") input(\"\\n [ENTER] >>> \") print() # Show elif opt == 3: i",
"# Show elif opt == 3: i = 1 print(\"\\n Id Alias\") for",
"launch_gmeet(\"\\\\\") # def launch_teams(loading_symbol): # try: # x, y = pyautogui.locateCenterOnScreen( # file+\"Zoom-Launch-Meeting-Button.png\",",
"\"-v\": print(\"Version: 1.0.1\") else: display_help() except KeyboardInterrupt: os.system(\"cls || clear\") print(\"\"\" __ __",
"__ __ __ _ _ ___ _ _ ____ ____ ( \\\\/ )___(",
"start() elif arg1.lower() == \"--gui\": print(\"Opening gui\") gui() elif arg1.lower() == \"--version\" or",
"for browser to open [\" + loading_symbol + \"]\", end=\"\") # launch_teams(\"\\\\\") def",
"Try again\") input(\" [ENTER] >>> \") return False try: if __name__ == \"__main__\":",
"alias = int(input(\" [User] >>> \")) meetings[\"meetings\"].pop(alias - 1) with open(file + \"meeting.yml\",",
"command line\") print(\"\\n\\tCheck this following syntax\") print(\"\\tpython3 main.py [meeting_number]\") print(\" Example: python3 main.py",
"print(\"4. Attend meeting\") print(\"5. Shortcut\") print(\"6. Exit\") print(\"==================\") try: opt = int(input(\"[User] >>>",
">>> \") meetings[\"meetings\"].append(dict({alias: link})) with open(file + \"meeting.yml\", \"w\") as f: yaml.dump(meetings, f)",
"for meeting in meetings[\"meetings\"]: x = meeting.keys() print(\" \" + str(i) + \".\"",
"def launch_teams(loading_symbol): # try: # x, y = pyautogui.locateCenterOnScreen( # file+\"Zoom-Launch-Meeting-Button.png\", confidence=0.8 #",
"print(\" =====================================================\") print(\" To add shortcut in windows\") print(\"\\n\\t- Right click the opengui.bat\")",
"\"r\") as f: meetings = yaml.load(f, Loader=yaml.FullLoader) except FileNotFoundError: print(\"Give alias for your",
"again\") input(\" [ENTER] >>> \") return False try: if __name__ == \"__main__\": try:",
"__)( )_( )( ___)( _ \\\\ ) ((___))(__ /(__)\\\\ )(__)( ) (( (__",
"to open [\" + loading_symbol + \"]\", end=\"\") # launch_teams(\"\\\\\") def find_whom_to_call(link): if",
">>> \")) meetings[\"meetings\"].pop(alias - 1) with open(file + \"meeting.yml\", \"w\") as f: yaml.dump(meetings,",
"yaml.dump(meetings, f) print(\" removed\") input(\"\\n [ENTER] >>> \") print() # Show elif opt",
"print(\" =====================================================\\n\") # menu def start(): os.system(\"cls || clear\") print(\"\"\" __ __ __",
"_ ____ ____ ( \\\\/ )___( ) /__\\\\ ( )( )( \\\\( )/",
">>> \")) print() open_key_link(meetings[\"meetings\"][alias - 1]) # Help elif opt == 5: display_help()",
"key = list(_alias)[0] print() link = _alias[key] find_whom_to_call(link) # LAUNCHER def launch_zoom(loading_symbol): try:",
"to open [\" + loading_symbol + \"]\", end=\"\") launch_zoom(\"/\") else: print(\"\\r Waiting for",
"for browser to open [\" + loading_symbol + \"]\", end=\"\") launch_gmeet(\"/\") else: print(\"\\r",
"+ \"google_meet_join.png\", confidence=0.8 ) print(x, y) pyautogui.click(x, y) except TypeError: if loading_symbol ==",
"((5 - len(str(i))) * \" \"), list(x)[0]) i += 1 print(\" Select the",
"print(\"\\r Waiting for browser to open [\" + loading_symbol + \"]\", end=\"\") #",
"command\") print(\"\\tpython3 main.py --gui\") print(\" =====================================================\") print(\" To add shortcut in windows\") print(\"\\n\\t-",
"\" \"), list(x)[0]) i += 1 print(\" Select the meeting number to start\")",
"your meeting from gui\") print(\"\\n\\tuse this command\") print(\"\\tpython3 main.py --gui\") print(\" =====================================================\") print(\"",
"print(\" Incorrect option\") start() # Displaying Help def display_help(): print(\"\\n =====================================================\") print(\" To",
":) (gives link from yaml) def open_key_link(_alias): key = list(_alias)[0] print() link =",
"def launch_zoom(loading_symbol): try: x, y = pyautogui.locateCenterOnScreen( file + \"Zoom-Launch-Meeting-Button.png\", confidence=0.8 ) pyautogui.click(x,",
"pady=10 ) for meeting in meetings[\"meetings\"]: x = meeting.keys() tkinter.Button( frame, text=list(x)[0], height=\"2\",",
"y = pyautogui.locateCenterOnScreen( file + \"google_meet_join.png\", confidence=0.8 ) print(x, y) pyautogui.click(x, y) except",
"launch_zoom(loading_symbol): try: x, y = pyautogui.locateCenterOnScreen( file + \"Zoom-Launch-Meeting-Button.png\", confidence=0.8 ) pyautogui.click(x, y)",
"f) # open_link(link) find_whom_to_call(link) if len(sys.argv) == 1: start() else: arg1 = sys.argv[1]",
"\"meeting.yml\", \"w\") as f: yaml.dump(meetings, f) print(\" Data is added\") input(\"\\n [ENTER] >>>",
"((5 - len(str(i))) * \" \"), list(x)[0]) i += 1 print(\" Type the",
"Add meeting\") print(\"2. Remove meeting\") print(\"3. Show meeting\") print(\"4. Attend meeting\") print(\"5. Shortcut\")",
"open it for you\") input(\" [ENTER] >>> \") return True # launch_teams(\"\\\\\") else:",
"open it for you\") input(\" [ENTER] >>> \") open_link(link) # launch_teams(\"\\\\\") else: print(\"Wrong",
"if re.match(r\"[0-9]*\", arg1).group(): i = int(arg1) print() try: open_key_link(meetings[\"meetings\"][i - 1]) except IndexError:",
"=====================================================\\n\") # menu def start(): os.system(\"cls || clear\") print(\"\"\" __ __ __ __",
"Incorrect option\") start() # Displaying Help def display_help(): print(\"\\n =====================================================\") print(\" To open",
"data on that number\") print(\"Press ENTER to get the menu. To exit press",
"=====================================================\") print(\" To open your meeting from gui\") print(\"\\n\\tuse this command\") print(\"\\tpython3 main.py",
"run this shortcut is `CTRL+ALT+P`\"\"\" ) print(\" =====================================================\\n\") # menu def start(): os.system(\"cls",
"* \" \"), list(x)[0]) i += 1 print(\" Type the id number to",
"confidence=0.8 ) pyautogui.click(x, y) except TypeError: if loading_symbol == \"\\\\\": print(\"\\r Waiting for",
">>> \")) except ValueError: print(\"Incorrect option\") start more_option(opt) # GUI def gui(): window_main",
"for browser to open [\" + loading_symbol + \"]\", end=\"\") launch_gmeet(\"\\\\\") # def",
"frame, text=list(x)[0], height=\"2\", width=\"40\", bg=\"white\", command=lambda link=meeting[list(x)[0]]: find_whom_to_call(link), ).pack(padx=10) window_main.mainloop() # link opener",
"meeting invite link\") link = input(\" [User] >>> \") meetings[\"meetings\"].append(dict({alias: link})) if validate(link):",
">>> \") print() # Show elif opt == 3: i = 1 print(\"\\n",
"= _alias[key] find_whom_to_call(link) # LAUNCHER def launch_zoom(loading_symbol): try: x, y = pyautogui.locateCenterOnScreen( file",
"x = meeting.keys() tkinter.Button( frame, text=list(x)[0], height=\"2\", width=\"40\", bg=\"white\", command=lambda link=meeting[list(x)[0]]: find_whom_to_call(link), ).pack(padx=10)",
"start() else: arg1 = sys.argv[1] if re.match(r\"[0-9]*\", arg1).group(): i = int(arg1) print() try:",
"end=\"\") launch_zoom(\"\\\\\") def launch_gmeet(loading_symbol): try: x, y = pyautogui.locateCenterOnScreen( file + \"google_meet_join.png\", confidence=0.8",
"list(x)[0]) i += 1 print(\" Type the id number to delete\") alias =",
"is added\") input(\"\\n [ENTER] >>> \") print() else: more_option(1) # Remove elif opt",
"syntax\") print(\"\\tpython3 main.py [meeting_number]\") print(\" Example: python3 main.py 1\") print(\" =====================================================\") print(\" To",
"with open(file + \"meeting.yml\", \"w\") as f: yaml.dump(meetings, f) # open_link(link) find_whom_to_call(link) if",
"opengui.bat\") print(\"\\t- Select Properties\") print(\"\\t- Click the Shortcut tab\") print( \"\"\"\\t- Click in",
"sys.argv[1] if re.match(r\"[0-9]*\", arg1).group(): i = int(arg1) print() try: open_key_link(meetings[\"meetings\"][i - 1]) except",
"meeting.keys() print(\" \" + str(i) + \".\" + ((5 - len(str(i))) * \"",
"delete\") alias = int(input(\" [User] >>> \")) meetings[\"meetings\"].pop(alias - 1) with open(file +",
"print(\"\\n\\tuse this command\") print(\"\\tpython3 main.py --gui\") print(\" =====================================================\") print(\" To add shortcut in",
"To exit press CTRL+C\") start() elif arg1.lower() == \"--gui\": print(\"Opening gui\") gui() elif",
"+ \"meeting.yml\", \"w\") as f: yaml.dump(meetings, f) print(\" removed\") input(\"\\n [ENTER] >>> \")",
"launch_teams(\"\\\\\") else: print(\" Wrong link\") print(\" Try again\") input(\" [ENTER] >>> \") return",
"__ __ __ __ __ __ _ _ ___ _ _ ____ ____",
"# else: # print(\"\\r Waiting for browser to open [\" + loading_symbol +",
"end=\"\") # banana peeler :) (gives link from yaml) def open_key_link(_alias): key =",
"window_main.mainloop() # link opener def open_link(link): webbrowser.open(link) f.close() print(\" Waiting for browser to",
"Type the id number to delete\") alias = int(input(\" [User] >>> \")) meetings[\"meetings\"].pop(alias",
"= input(\" [User] >>> \") meetings[\"meetings\"].append(dict({alias: link})) if validate(link): with open(file + \"meeting.yml\",",
"shortcut in windows\") print(\"\\n\\t- Right click the opengui.bat\") print(\"\\t- Select Properties\") print(\"\\t- Click",
"/(__)\\\\ )(__)( ) (( (__ ) _ ( )__) ) / (_/\\\\/\\\\_) (____)(__)(__)(______)(_)\\\\_)\\\\___)(_)",
"link = input(\" [User] >>> \") meetings[\"meetings\"].append(dict({alias: link})) if validate(link): with open(file +",
"main.py [meeting_number]\") print(\" Example: python3 main.py 1\") print(\" =====================================================\") print(\" To open your",
"os.system(\"cls || clear\") # Add if opt == 1: print(\" Give alias for",
"if re.search(\"meet.google.com\", link): return True elif re.search(\"zoom\", link): return True elif re.search(\"teams.live\", link):",
"\"\"\") print(\"==================\") print(\"1. Add meeting\") print(\"2. Remove meeting\") print(\"3. Show meeting\") print(\"4. Attend",
"+ \"meeting.yml\", \"w\") as f: yaml.dump(meetings, f) print(\" Data is added\") input(\"\\n [ENTER]",
")( ___)( _ \\\\ ) ((___))(__ /(__)\\\\ )(__)( ) (( (__ ) _",
"sys import webbrowser import yaml import pyautogui import tkinter file = __file__[:-7] meetings",
"open_link(link): webbrowser.open(link) f.close() print(\" Waiting for browser to open\", end=\"\") # banana peeler",
"+= 1 input(\"\\n [ENTER] >>> \") print() # Attend elif opt == 4:",
"# x, y = pyautogui.locateCenterOnScreen( # file+\"Zoom-Launch-Meeting-Button.png\", confidence=0.8 # ) # pyautogui.click(x, y)",
"# Remove elif opt == 2: i = 1 print(\"\\n Id Alias\") for",
"2: i = 1 print(\"\\n Id Alias\") for meeting in meetings[\"meetings\"]: x =",
"print() open_key_link(meetings[\"meetings\"][alias - 1]) # Help elif opt == 5: display_help() input(\"\\n [ENTER]",
"To open your meeting from command line\") print(\"\\n\\tCheck this following syntax\") print(\"\\tpython3 main.py",
"meetings = {\"meetings\": []} def more_option(opt): os.system(\"cls || clear\") # Add if opt",
"pyautogui.click(x, y) # # except TypeError: # if loading_symbol == \"\\\\\": # print(\"\\r",
"print(\"1. Add meeting\") print(\"2. Remove meeting\") print(\"3. Show meeting\") print(\"4. Attend meeting\") print(\"5.",
"\"meeting.yml\", \"r\") as f: meetings = yaml.load(f, Loader=yaml.FullLoader) except FileNotFoundError: print(\"Give alias for",
"Example: python3 main.py 1\") print(\" =====================================================\") print(\" To open your meeting from gui\")",
"pyautogui.locateCenterOnScreen( # file+\"Zoom-Launch-Meeting-Button.png\", confidence=0.8 # ) # pyautogui.click(x, y) # # except TypeError:",
"for meeting in meetings[\"meetings\"]: x = meeting.keys() tkinter.Button( frame, text=list(x)[0], height=\"2\", width=\"40\", bg=\"white\",",
"to open\", end=\"\") # banana peeler :) (gives link from yaml) def open_key_link(_alias):",
"opt == 5: display_help() input(\"\\n [ENTER] >>> \") print() # Exit elif opt",
"\"]\", end=\"\") # launch_teams(\"/\") # else: # print(\"\\r Waiting for browser to open",
"loading_symbol + \"]\", end=\"\") launch_zoom(\"/\") else: print(\"\\r Waiting for browser to open [\"",
"4: i = 1 print(\"\\n Id Alias\") for meeting in meetings[\"meetings\"]: x =",
"1.0.1\") else: display_help() except KeyboardInterrupt: os.system(\"cls || clear\") print(\"\"\" __ __ __ __",
"in the Shortcut key box and press a letter. For example, if you",
"except TypeError: # if loading_symbol == \"\\\\\": # print(\"\\r Waiting for browser to",
"end=\"\") # launch_teams(\"/\") # else: # print(\"\\r Waiting for browser to open [\"",
"else: print(\"Wrong link\") start() def validate(link): if re.search(\"meet.google.com\", link): return True elif re.search(\"zoom\",",
"you\") input(\" [ENTER] >>> \") return True # launch_teams(\"\\\\\") else: print(\" Wrong link\")",
"link = _alias[key] find_whom_to_call(link) # LAUNCHER def launch_zoom(loading_symbol): try: x, y = pyautogui.locateCenterOnScreen(",
"print(\"\\r Waiting for browser to open [\" + loading_symbol + \"]\", end=\"\") launch_gmeet(\"/\")",
"# Help elif opt == 5: display_help() input(\"\\n [ENTER] >>> \") print() #",
"\"\\\\\": print(\"\\r Waiting for browser to open [\" + loading_symbol + \"]\", end=\"\")",
"print(\" To open your meeting from command line\") print(\"\\n\\tCheck this following syntax\") print(\"\\tpython3",
"+ loading_symbol + \"]\", end=\"\") # launch_teams(\"\\\\\") def find_whom_to_call(link): if re.search(\"meet.google.com\", link): open_link(link)",
"open_link(link) find_whom_to_call(link) if len(sys.argv) == 1: start() else: arg1 = sys.argv[1] if re.match(r\"[0-9]*\",",
"re.search(\".zoom.us\", link): open_link(link) launch_zoom(\"\\\\\") elif re.search(\"teams.live\", link): print(\" Chori....\") print(\" I'm can't launch",
"elif opt == 5: display_help() input(\"\\n [ENTER] >>> \") print() # Exit elif",
"try: x, y = pyautogui.locateCenterOnScreen( file + \"Zoom-Launch-Meeting-Button.png\", confidence=0.8 ) pyautogui.click(x, y) except",
"launch_gmeet(loading_symbol): try: x, y = pyautogui.locateCenterOnScreen( file + \"google_meet_join.png\", confidence=0.8 ) print(x, y)",
"[\" + loading_symbol + \"]\", end=\"\") launch_gmeet(\"/\") else: print(\"\\r Waiting for browser to",
"print() # Attend elif opt == 4: i = 1 print(\"\\n Id Alias\")",
"for browser to open [\" + loading_symbol + \"]\", end=\"\") # launch_teams(\"/\") #",
"_ _ ___ _ _ ____ ____ ( \\\\/ )___( ) /__\\\\ (",
"opener def open_link(link): webbrowser.open(link) f.close() print(\" Waiting for browser to open\", end=\"\") #",
"Waiting for browser to open [\" + loading_symbol + \"]\", end=\"\") # launch_teams(\"/\")",
"elif opt == 6: exit() else: print(\" Incorrect option\") start() # Displaying Help",
"[ENTER] >>> \") print() # Attend elif opt == 4: i = 1",
"[\" + loading_symbol + \"]\", end=\"\") # launch_teams(\"/\") # else: # print(\"\\r Waiting",
"\"]\", end=\"\") launch_zoom(\"\\\\\") def launch_gmeet(loading_symbol): try: x, y = pyautogui.locateCenterOnScreen( file + \"google_meet_join.png\",",
"Click in the Shortcut key box and press a letter. For example, if",
"opt == 3: i = 1 print(\"\\n Id Alias\") for meeting in meetings[\"meetings\"]:",
"it for you\") input(\" [ENTER] >>> \") open_link(link) # launch_teams(\"\\\\\") else: print(\"Wrong link\")",
"try: open_key_link(meetings[\"meetings\"][i - 1]) except IndexError: print(\"There is no data on that number\")",
"# Displaying Help def display_help(): print(\"\\n =====================================================\") print(\" To open your meeting from",
"int(input(\" [User] >>> \")) meetings[\"meetings\"].pop(alias - 1) with open(file + \"meeting.yml\", \"w\") as",
"link\") print(\" Try again\") input(\" [ENTER] >>> \") return False try: if __name__",
"to open [\" + loading_symbol + \"]\", end=\"\") # launch_teams(\"/\") # else: #",
"link})) if validate(link): with open(file + \"meeting.yml\", \"w\") as f: yaml.dump(meetings, f) print(\"",
"teams but I can open it for you\") input(\" [ENTER] >>> \") open_link(link)",
"from command line\") print(\"\\n\\tCheck this following syntax\") print(\"\\tpython3 main.py [meeting_number]\") print(\" Example: python3",
"key combination to run this shortcut is `CTRL+ALT+P`\"\"\" ) print(\" =====================================================\\n\") # menu",
"arg1.lower() == \"--gui\": print(\"Opening gui\") gui() elif arg1.lower() == \"--version\" or arg1.lower() ==",
"launch_zoom(\"/\") else: print(\"\\r Waiting for browser to open [\" + loading_symbol + \"]\",",
"this command\") print(\"\\tpython3 main.py --gui\") print(\" =====================================================\") print(\" To add shortcut in windows\")",
"5: display_help() input(\"\\n [ENTER] >>> \") print() # Exit elif opt == 6:",
"but I can open it for you\") input(\" [ENTER] >>> \") return True",
"print(\" Chori....\") print(\" I'm can't launch microsoft teams but I can open it",
"len(sys.argv) == 1: start() else: arg1 = sys.argv[1] if re.match(r\"[0-9]*\", arg1).group(): i =",
"os.system(\"cls || clear\") print(\"\"\" __ __ __ __ __ __ _ _ ___",
"link\") start() def validate(link): if re.search(\"meet.google.com\", link): return True elif re.search(\"zoom\", link): return",
"[meeting_number]\") print(\" Example: python3 main.py 1\") print(\" =====================================================\") print(\" To open your meeting",
"\"google_meet_join.png\", confidence=0.8 ) print(x, y) pyautogui.click(x, y) except TypeError: if loading_symbol == \"\\\\\":",
"i = 1 print(\"\\n Id Alias\") for meeting in meetings[\"meetings\"]: x = meeting.keys()",
"= int(input(\" [User] >>> \")) print() open_key_link(meetings[\"meetings\"][alias - 1]) # Help elif opt",
"if loading_symbol == \"\\\\\": print(\"\\r Waiting for browser to open [\" + loading_symbol",
"print() else: more_option(1) # Remove elif opt == 2: i = 1 print(\"\\n",
"+ \"]\", end=\"\") launch_gmeet(\"\\\\\") # def launch_teams(loading_symbol): # try: # x, y =",
"open_link(link) launch_gmeet(\"\\\\\") elif re.search(\".zoom.us\", link): open_link(link) launch_zoom(\"\\\\\") elif re.search(\"teams.live\", link): print(\" Chori....\") print(\"",
"elif re.search(\".zoom.us\", link): open_link(link) launch_zoom(\"\\\\\") elif re.search(\"teams.live\", link): print(\" Chori....\") print(\" I'm can't",
"(( (__ ) _ ( )__) ) / (_/\\\\/\\\\_) (____)(__)(__)(______)(_)\\\\_)\\\\___)(_) (_)(____)(_)\\\\_) \"\"\") print(\"==================\")",
"but I can open it for you\") input(\" [ENTER] >>> \") open_link(link) #",
"\") print() else: more_option(1) # Remove elif opt == 2: i = 1",
"To add shortcut in windows\") print(\"\\n\\t- Right click the opengui.bat\") print(\"\\t- Select Properties\")",
"\"w\") as f: yaml.dump(meetings, f) print(\" removed\") input(\"\\n [ENTER] >>> \") print() #",
"3: i = 1 print(\"\\n Id Alias\") for meeting in meetings[\"meetings\"]: x =",
"the opengui.bat\") print(\"\\t- Select Properties\") print(\"\\t- Click the Shortcut tab\") print( \"\"\"\\t- Click",
"add shortcut in windows\") print(\"\\n\\t- Right click the opengui.bat\") print(\"\\t- Select Properties\") print(\"\\t-",
"\" + str(i) + \".\" + ((5 - len(str(i))) * \" \"), list(x)[0])",
"bg=\"white\", command=lambda link=meeting[list(x)[0]]: find_whom_to_call(link), ).pack(padx=10) window_main.mainloop() # link opener def open_link(link): webbrowser.open(link) f.close()",
"as f: yaml.dump(meetings, f) print(\" Data is added\") input(\"\\n [ENTER] >>> \") print()",
"from gui\") print(\"\\n\\tuse this command\") print(\"\\tpython3 main.py --gui\") print(\" =====================================================\") print(\" To add",
"launch_teams(\"/\") # else: # print(\"\\r Waiting for browser to open [\" + loading_symbol",
"a letter. For example, if you press the P key,the key combination to",
"== 6: exit() else: print(\" Incorrect option\") start() # Displaying Help def display_help():",
"link})) with open(file + \"meeting.yml\", \"w\") as f: yaml.dump(meetings, f) # open_link(link) find_whom_to_call(link)",
")/ __)( )_( )( ___)( _ \\\\ ) ((___))(__ /(__)\\\\ )(__)( ) ((",
")___( ) /__\\\\ ( )( )( \\\\( )/ __)( )_( )( ___)( _",
"loading_symbol == \"\\\\\": print(\"\\r Waiting for browser to open [\" + loading_symbol +",
"input(\"[User] >>> \") print(\"Now paste your meeting invite link\") link = input(\"[User] >>>",
"== \"\\\\\": print(\"\\r Waiting for browser to open [\" + loading_symbol + \"]\",",
"browser to open [\" + loading_symbol + \"]\", end=\"\") launch_gmeet(\"/\") else: print(\"\\r Waiting",
"= input(\" [User] >>> \") print(\" Now paste your meeting invite link\") link",
"print() # Exit elif opt == 6: exit() else: print(\" Incorrect option\") start()",
"|| clear\") # Add if opt == 1: print(\" Give alias for your",
">>> \") print() else: more_option(1) # Remove elif opt == 2: i =",
"== 1: print(\" Give alias for your meeting\") alias = input(\" [User] >>>",
"yaml import pyautogui import tkinter file = __file__[:-7] meetings = {\"meetings\": []} def",
"____ ( \\\\/ )___( ) /__\\\\ ( )( )( \\\\( )/ __)( )_(",
"[ENTER] >>> \") print() else: more_option(1) # Remove elif opt == 2: i",
"shortcut is `CTRL+ALT+P`\"\"\" ) print(\" =====================================================\\n\") # menu def start(): os.system(\"cls || clear\")",
"Shortcut\") print(\"6. Exit\") print(\"==================\") try: opt = int(input(\"[User] >>> \")) except ValueError: print(\"Incorrect",
"Exit elif opt == 6: exit() else: print(\" Incorrect option\") start() # Displaying",
"Help def display_help(): print(\"\\n =====================================================\") print(\" To open your meeting from command line\")",
"loading_symbol == \"\\\\\": # print(\"\\r Waiting for browser to open [\" + loading_symbol",
"meeting\") print(\"5. Shortcut\") print(\"6. Exit\") print(\"==================\") try: opt = int(input(\"[User] >>> \")) except",
"x, y = pyautogui.locateCenterOnScreen( # file+\"Zoom-Launch-Meeting-Button.png\", confidence=0.8 # ) # pyautogui.click(x, y) #",
"elif re.search(\"zoom\", link): return True elif re.search(\"teams.live\", link): print(\" Chori....\") print(\" I'm can't",
"print(\"There is no data on that number\") print(\"Press ENTER to get the menu.",
")( \\\\( )/ __)( )_( )( ___)( _ \\\\ ) ((___))(__ /(__)\\\\ )(__)(",
"link = input(\"[User] >>> \") meetings[\"meetings\"].append(dict({alias: link})) with open(file + \"meeting.yml\", \"w\") as",
"this shortcut is `CTRL+ALT+P`\"\"\" ) print(\" =====================================================\\n\") # menu def start(): os.system(\"cls ||",
"link): return True elif re.search(\"zoom\", link): return True elif re.search(\"teams.live\", link): print(\" Chori....\")",
"if validate(link): with open(file + \"meeting.yml\", \"w\") as f: yaml.dump(meetings, f) print(\" Data",
"input(\"\\n [ENTER] >>> \") print() # Show elif opt == 3: i =",
"[\" + loading_symbol + \"]\", end=\"\") launch_zoom(\"\\\\\") def launch_gmeet(loading_symbol): try: x, y =",
"I can open it for you\") input(\" [ENTER] >>> \") open_link(link) # launch_teams(\"\\\\\")",
"get the menu. To exit press CTRL+C\") start() elif arg1.lower() == \"--gui\": print(\"Opening",
"try: if __name__ == \"__main__\": try: with open(file + \"meeting.yml\", \"r\") as f:",
"link=meeting[list(x)[0]]: find_whom_to_call(link), ).pack(padx=10) window_main.mainloop() # link opener def open_link(link): webbrowser.open(link) f.close() print(\" Waiting",
"= sys.argv[1] if re.match(r\"[0-9]*\", arg1).group(): i = int(arg1) print() try: open_key_link(meetings[\"meetings\"][i - 1])",
"to open [\" + loading_symbol + \"]\", end=\"\") launch_gmeet(\"\\\\\") # def launch_teams(loading_symbol): #",
"display_help() except KeyboardInterrupt: os.system(\"cls || clear\") print(\"\"\" __ __ __ __ __ __",
"print(\" Example: python3 main.py 1\") print(\" =====================================================\") print(\" To open your meeting from",
"combination to run this shortcut is `CTRL+ALT+P`\"\"\" ) print(\" =====================================================\\n\") # menu def",
"def open_link(link): webbrowser.open(link) f.close() print(\" Waiting for browser to open\", end=\"\") # banana",
"+ \"Zoom-Launch-Meeting-Button.png\", confidence=0.8 ) pyautogui.click(x, y) except TypeError: if loading_symbol == \"\\\\\": print(\"\\r",
"your meeting\") alias = input(\" [User] >>> \") print(\" Now paste your meeting",
"can open it for you\") input(\" [ENTER] >>> \") open_link(link) # launch_teams(\"\\\\\") else:",
"= yaml.load(f, Loader=yaml.FullLoader) except FileNotFoundError: print(\"Give alias for your meeting\") alias = input(\"[User]",
"== \"--gui\": print(\"Opening gui\") gui() elif arg1.lower() == \"--version\" or arg1.lower() == \"-v\":",
"else: print(\" Wrong link\") print(\" Try again\") input(\" [ENTER] >>> \") return False",
"[User] >>> \") meetings[\"meetings\"].append(dict({alias: link})) if validate(link): with open(file + \"meeting.yml\", \"w\") as",
"box and press a letter. For example, if you press the P key,the",
"meeting\") print(\"4. Attend meeting\") print(\"5. Shortcut\") print(\"6. Exit\") print(\"==================\") try: opt = int(input(\"[User]",
"try: opt = int(input(\"[User] >>> \")) except ValueError: print(\"Incorrect option\") start more_option(opt) #",
">>> \") return False try: if __name__ == \"__main__\": try: with open(file +",
"no data on that number\") print(\"Press ENTER to get the menu. To exit",
"IndexError: print(\"There is no data on that number\") print(\"Press ENTER to get the",
"elif opt == 2: i = 1 print(\"\\n Id Alias\") for meeting in",
"return False try: if __name__ == \"__main__\": try: with open(file + \"meeting.yml\", \"r\")",
"= meeting.keys() print(\" \" + str(i) + \".\" + ((5 - len(str(i))) *",
"print(\"\\r Waiting for browser to open [\" + loading_symbol + \"]\", end=\"\") launch_zoom(\"/\")",
"meetings[\"meetings\"].append(dict({alias: link})) if validate(link): with open(file + \"meeting.yml\", \"w\") as f: yaml.dump(meetings, f)",
"or arg1.lower() == \"-v\": print(\"Version: 1.0.1\") else: display_help() except KeyboardInterrupt: os.system(\"cls || clear\")",
"in windows\") print(\"\\n\\t- Right click the opengui.bat\") print(\"\\t- Select Properties\") print(\"\\t- Click the",
"___)( _ \\\\ ) ((___))(__ /(__)\\\\ )(__)( ) (( (__ ) _ (",
"1]) # Help elif opt == 5: display_help() input(\"\\n [ENTER] >>> \") print()",
"for your meeting\") alias = input(\"[User] >>> \") print(\"Now paste your meeting invite",
"to get the menu. To exit press CTRL+C\") start() elif arg1.lower() == \"--gui\":",
")( )( \\\\( )/ __)( )_( )( ___)( _ \\\\ ) ((___))(__ /(__)\\\\",
">>> \") print() # Attend elif opt == 4: i = 1 print(\"\\n",
"Meeting Launcher\") frame = tkinter.Frame(window_main) frame.pack(expand=True, padx=10, pady=20) tkinter.Label(frame, text=\"Select your meeting to",
"meeting\") print(\"2. Remove meeting\") print(\"3. Show meeting\") print(\"4. Attend meeting\") print(\"5. Shortcut\") print(\"6.",
"print(\"Version: 1.0.1\") else: display_help() except KeyboardInterrupt: os.system(\"cls || clear\") print(\"\"\" __ __ __",
"click the opengui.bat\") print(\"\\t- Select Properties\") print(\"\\t- Click the Shortcut tab\") print( \"\"\"\\t-",
"= list(_alias)[0] print() link = _alias[key] find_whom_to_call(link) # LAUNCHER def launch_zoom(loading_symbol): try: x,",
"press a letter. For example, if you press the P key,the key combination",
"# LAUNCHER def launch_zoom(loading_symbol): try: x, y = pyautogui.locateCenterOnScreen( file + \"Zoom-Launch-Meeting-Button.png\", confidence=0.8",
"== 4: i = 1 print(\"\\n Id Alias\") for meeting in meetings[\"meetings\"]: x",
"# GUI def gui(): window_main = tkinter.Tk(className=\" Meeting Launcher\") frame = tkinter.Frame(window_main) frame.pack(expand=True,",
"Launcher\") frame = tkinter.Frame(window_main) frame.pack(expand=True, padx=10, pady=20) tkinter.Label(frame, text=\"Select your meeting to open\",",
"_alias[key] find_whom_to_call(link) # LAUNCHER def launch_zoom(loading_symbol): try: x, y = pyautogui.locateCenterOnScreen( file +",
"find_whom_to_call(link) # LAUNCHER def launch_zoom(loading_symbol): try: x, y = pyautogui.locateCenterOnScreen( file + \"Zoom-Launch-Meeting-Button.png\",",
"can open it for you\") input(\" [ENTER] >>> \") return True # launch_teams(\"\\\\\")",
") print(x, y) pyautogui.click(x, y) except TypeError: if loading_symbol == \"\\\\\": print(\"\\r Waiting",
"alias = input(\"[User] >>> \") print(\"Now paste your meeting invite link\") link =",
"[ENTER] >>> \") open_link(link) # launch_teams(\"\\\\\") else: print(\"Wrong link\") start() def validate(link): if",
"font=(\"Arial\", 12)).pack( pady=10 ) for meeting in meetings[\"meetings\"]: x = meeting.keys() tkinter.Button( frame,",
"# launch_teams(\"\\\\\") else: print(\" Wrong link\") print(\" Try again\") input(\" [ENTER] >>> \")",
"start() # Displaying Help def display_help(): print(\"\\n =====================================================\") print(\" To open your meeting",
"pyautogui.locateCenterOnScreen( file + \"google_meet_join.png\", confidence=0.8 ) print(x, y) pyautogui.click(x, y) except TypeError: if",
"+ \"]\", end=\"\") launch_zoom(\"/\") else: print(\"\\r Waiting for browser to open [\" +",
"peeler :) (gives link from yaml) def open_key_link(_alias): key = list(_alias)[0] print() link",
"height=\"2\", width=\"40\", bg=\"white\", command=lambda link=meeting[list(x)[0]]: find_whom_to_call(link), ).pack(padx=10) window_main.mainloop() # link opener def open_link(link):",
"except KeyboardInterrupt: os.system(\"cls || clear\") print(\"\"\" __ __ __ __ __ __ _",
"re.search(\"zoom\", link): return True elif re.search(\"teams.live\", link): print(\" Chori....\") print(\" I'm can't launch",
"I can open it for you\") input(\" [ENTER] >>> \") return True #",
"# launch_teams(\"/\") # else: # print(\"\\r Waiting for browser to open [\" +",
"# Add if opt == 1: print(\" Give alias for your meeting\") alias",
"__ __ _ _ ___ _ _ ____ ____ ( \\\\/ )___( )",
"tkinter.Frame(window_main) frame.pack(expand=True, padx=10, pady=20) tkinter.Label(frame, text=\"Select your meeting to open\", font=(\"Arial\", 12)).pack( pady=10",
"+ loading_symbol + \"]\", end=\"\") launch_gmeet(\"/\") else: print(\"\\r Waiting for browser to open",
"[\" + loading_symbol + \"]\", end=\"\") launch_gmeet(\"\\\\\") # def launch_teams(loading_symbol): # try: #",
"microsoft teams but I can open it for you\") input(\" [ENTER] >>> \")",
"Exit\") print(\"==================\") try: opt = int(input(\"[User] >>> \")) except ValueError: print(\"Incorrect option\") start",
"press CTRL+C\") start() elif arg1.lower() == \"--gui\": print(\"Opening gui\") gui() elif arg1.lower() ==",
"elif arg1.lower() == \"--gui\": print(\"Opening gui\") gui() elif arg1.lower() == \"--version\" or arg1.lower()",
"+ loading_symbol + \"]\", end=\"\") # launch_teams(\"/\") # else: # print(\"\\r Waiting for",
"browser to open [\" + loading_symbol + \"]\", end=\"\") launch_gmeet(\"\\\\\") # def launch_teams(loading_symbol):",
"loading_symbol + \"]\", end=\"\") launch_gmeet(\"\\\\\") # def launch_teams(loading_symbol): # try: # x, y",
"you press the P key,the key combination to run this shortcut is `CTRL+ALT+P`\"\"\"",
"i += 1 print(\" Type the id number to delete\") alias = int(input(\"",
"your meeting from command line\") print(\"\\n\\tCheck this following syntax\") print(\"\\tpython3 main.py [meeting_number]\") print(\""
] |
[
"{}'.format( op_slice_sizes, output_op_slices_sizes)) op_handler_util.group_op_with_inputs_and_outputs( op, [], output_op_slices, op_slice_sizes, op_reg_manager) def _get_output_op_slices(self, output_ops, op_reg_manager):",
"op_reg_manager.get_op_slices(op) output_op_slices = op_handler_util.get_op_slices( output_ops_to_group, op_reg_manager) aligned_op_slice_sizes = op_handler_util.get_aligned_op_slice_sizes( op_slices, [], output_op_slices) op_handler_util.reslice_ops([op]",
"process them. input_ops = op_handler_util.get_input_ops(op, op_reg_manager) input_ops_without_group = op_handler_util.get_ops_without_groups( input_ops, op_reg_manager) # Check",
"op and updates the manager. Args: op: tf.Operation to assign grouping to. op_reg_manager:",
"# Reprocess ops. op_reg_manager.process_ops(output_ops_to_process + input_ops_to_process) def _group_with_output_slices( self, op, output_op_slices, op_slices, op_reg_manager):",
"Args: output_ops: List of tf.Operation. op_reg_manager: OpRegularizerManager to keep track of the grouping.",
"op_reg_manager): \"\"\"Returns op slices for outputs. Args: output_ops: List of tf.Operation. op_reg_manager: OpRegularizerManager",
"size. output_ops_to_group, output_ops_to_process = ( op_handler_util.separate_same_size_ops(op, output_ops)) # Also process ungrouped ops. input_ops_to_process",
"# Only group with ops that have the same size. Process the ops",
"op_handler_util class OutputNonPassthroughOpHandler(op_handler.OpHandler): \"\"\"OpHandler implementation for OutputNonPassthrough operations. These ops take their regularizer",
"op_reg_manager: OpRegularizerManager to keep track of grouping. Raises: ValueError: If sizes for current",
"the manager to process them. input_ops = op_handler_util.get_input_ops(op, op_reg_manager) input_ops_without_group = op_handler_util.get_ops_without_groups( input_ops,",
"Args: op: tf.Operation to assign grouping to. op_reg_manager: OpRegularizerManager to keep track of",
"to the given op and updates the manager. Args: op: tf.Operation to assign",
"self._get_output_op_slices( output_ops_to_group, op_reg_manager) # Group with inputs and outputs. op_handler_util.group_op_with_inputs_and_outputs( op, [], output_op_slices,",
"that have the same size. Process the ops that have # mismatched size.",
"{}, {}'.format( op_slice_sizes, output_op_slices_sizes)) op_handler_util.group_op_with_inputs_and_outputs( op, [], output_op_slices, op_slice_sizes, op_reg_manager) def _get_output_op_slices(self, output_ops,",
"# mismatched size. output_ops_to_group, output_ops_to_process = ( op_handler_util.separate_same_size_ops(op, output_ops)) # Also process ungrouped",
"op_handler_util.get_op_slices( output_ops_to_group, op_reg_manager) aligned_op_slice_sizes = op_handler_util.get_aligned_op_slice_sizes( op_slices, [], output_op_slices) op_handler_util.reslice_ops([op] + output_ops_to_group, aligned_op_slice_sizes,",
"the manager. Args: op: tf.Operation to assign grouping to. op_reg_manager: OpRegularizerManager to keep",
"List of OpSlice for current op. op_reg_manager: OpRegularizerManager to keep track of grouping.",
"TODO(a1): Consider refactoring this method. # Repopulate OpSlice data, as ops may have",
"current and output op slices are not the same. \"\"\" # Assert that",
"op_reg_manager) aligned_op_slice_sizes = op_handler_util.get_aligned_op_slice_sizes( op_slices, [], output_op_slices) op_handler_util.reslice_ops([op] + output_ops_to_group, aligned_op_slice_sizes, op_reg_manager) #",
"if all output ops have groups, or tell the manager to process them.",
"def _get_output_op_slices(self, output_ops, op_reg_manager): \"\"\"Returns op slices for outputs. Args: output_ops: List of",
"OutputNonPassthroughOpHandler(op_handler.OpHandler): \"\"\"OpHandler implementation for OutputNonPassthrough operations. These ops take their regularizer from the",
"def is_passthrough(self): return False def assign_grouping(self, op, op_reg_manager): \"\"\"Assign grouping to the given",
"from morph_net.framework import op_handler_util class OutputNonPassthroughOpHandler(op_handler.OpHandler): \"\"\"OpHandler implementation for OutputNonPassthrough operations. These ops",
"slice ' 'sizes: {}, {}'.format( op_slice_sizes, output_op_slices_sizes)) op_handler_util.group_op_with_inputs_and_outputs( op, [], output_op_slices, op_slice_sizes, op_reg_manager)",
"their input. \"\"\" @property def is_source_op(self): return False @property def is_passthrough(self): return False",
"the same size. Process the ops that have # mismatched size. output_ops_to_group, output_ops_to_process",
"regularizer to their input. This is the default OpHandler for ops like Conv2D",
"op_reg_manager) # Group with inputs and outputs. op_handler_util.group_op_with_inputs_and_outputs( op, [], output_op_slices, aligned_op_slice_sizes, op_reg_manager)",
"absolute_import from __future__ import division from __future__ import print_function from morph_net.framework import op_handler",
"output_ops = op_handler_util.get_output_ops(op, op_reg_manager) output_ops_without_group = op_handler_util.get_ops_without_groups( output_ops, op_reg_manager) # Remove non-passthrough ops",
"op_handler_util.remove_non_passthrough_ops( output_ops, op_reg_manager) # Only group with ops that have the same size.",
"per output op. \"\"\" return op_handler_util.get_op_slices(output_ops, op_reg_manager) def create_regularizer(self, _): raise NotImplementedError('Not a",
"outputs. Args: output_ops: List of tf.Operation. op_reg_manager: OpRegularizerManager to keep track of the",
"raise ValueError('Current op and output op have differing slice ' 'sizes: {}, {}'.format(",
"grouping for. output_op_slices: List of list of OpSlice, with a list per output",
"output_op_slices: List of list of OpSlice, with a list per output op. op_slices:",
"= op_handler_util.get_ops_without_groups( input_ops, op_reg_manager) # Check if all output ops have groups, or",
"op_reg_manager) # Check if all output ops have groups, or tell the manager",
"output_ops_to_process.extend(output_ops_without_group) # Align op slice sizes if needed. op_slices = op_reg_manager.get_op_slices(op) output_op_slices =",
"the output and do not passthrough the regularizer to their input. \"\"\" @property",
"Args: op: tf.Operation to determine grouping for. output_op_slices: List of list of OpSlice,",
"with. output_ops = op_handler_util.remove_non_passthrough_ops( output_ops, op_reg_manager) # Only group with ops that have",
"op_reg_manager) output_ops_without_group = op_handler_util.get_ops_without_groups( output_ops, op_reg_manager) # Remove non-passthrough ops from outputs ops",
"have differing slice ' 'sizes: {}, {}'.format( op_slice_sizes, output_op_slices_sizes)) op_handler_util.group_op_with_inputs_and_outputs( op, [], output_op_slices,",
"of OpSlice, with a list per output op. op_slices: List of OpSlice for",
"to assign grouping to. op_reg_manager: OpRegularizerManager to keep track of the grouping. \"\"\"",
"These ops take their regularizer from the output and do not passthrough the",
"the manager to process them. output_ops = op_handler_util.get_output_ops(op, op_reg_manager) output_ops_without_group = op_handler_util.get_ops_without_groups( output_ops,",
"op, [], output_op_slices, aligned_op_slice_sizes, op_reg_manager) # Reprocess ops. op_reg_manager.process_ops(output_ops_to_process + input_ops_to_process) def _group_with_output_slices(",
"output_op_slices = op_handler_util.get_op_slices( output_ops_to_group, op_reg_manager) aligned_op_slice_sizes = op_handler_util.get_aligned_op_slice_sizes( op_slices, [], output_op_slices) op_handler_util.reslice_ops([op] +",
"( op_handler_util.separate_same_size_ops(op, output_ops)) # Also process ungrouped ops. input_ops_to_process = input_ops_without_group output_ops_to_process.extend(output_ops_without_group) #",
"ops. input_ops_to_process = input_ops_without_group output_ops_to_process.extend(output_ops_without_group) # Align op slice sizes if needed. op_slices",
"output ops have groups, or tell the manager to process them. output_ops =",
"are aligned. output_op_slices_sizes = op_handler_util.get_op_slice_sizes( output_op_slices) op_slice_sizes = op_handler_util.get_op_slice_sizes([op_slices]) if op_slice_sizes != output_op_slices_sizes:",
"# Assert that op slices for output and current op are aligned. output_op_slices_sizes",
"and output op have differing slice ' 'sizes: {}, {}'.format( op_slice_sizes, output_op_slices_sizes)) op_handler_util.group_op_with_inputs_and_outputs(",
"op. op_reg_manager: OpRegularizerManager to keep track of grouping. Raises: ValueError: If sizes for",
"assign_grouping(self, op, op_reg_manager): \"\"\"Assign grouping to the given op and updates the manager.",
"them. input_ops = op_handler_util.get_input_ops(op, op_reg_manager) input_ops_without_group = op_handler_util.get_ops_without_groups( input_ops, op_reg_manager) # Check if",
"and outputs. op_handler_util.group_op_with_inputs_and_outputs( op, [], output_op_slices, aligned_op_slice_sizes, op_reg_manager) # Reprocess ops. op_reg_manager.process_ops(output_ops_to_process +",
"# Remove non-passthrough ops from outputs ops to group with. output_ops = op_handler_util.remove_non_passthrough_ops(",
"manager to process them. output_ops = op_handler_util.get_output_ops(op, op_reg_manager) output_ops_without_group = op_handler_util.get_ops_without_groups( output_ops, op_reg_manager)",
"with ops that have the same size. Process the ops that have #",
"a list per output op. op_slices: List of OpSlice for current op. op_reg_manager:",
"of the grouping. \"\"\" # Check if all input ops have groups, or",
"needed. op_slices = op_reg_manager.get_op_slices(op) output_op_slices = op_handler_util.get_op_slices( output_ops_to_group, op_reg_manager) aligned_op_slice_sizes = op_handler_util.get_aligned_op_slice_sizes( op_slices,",
"of op have been aligned with output, groups the corresponding OpSlice. Args: op:",
"\"\"\"OpHandler implementation for OutputNonPassthrough operations. These ops take their regularizer from the output",
"may have been resliced. output_op_slices = self._get_output_op_slices( output_ops_to_group, op_reg_manager) # Group with inputs",
"output_op_slices, op_slice_sizes, op_reg_manager) def _get_output_op_slices(self, output_ops, op_reg_manager): \"\"\"Returns op slices for outputs. Args:",
"\"\"\" # Check if all input ops have groups, or tell the manager",
"current op. op_reg_manager: OpRegularizerManager to keep track of grouping. Raises: ValueError: If sizes",
"op, output_op_slices, op_slices, op_reg_manager): \"\"\"Groups OpSlice of current op with output ops. Assuming",
"ops may have been resliced. output_op_slices = self._get_output_op_slices( output_ops_to_group, op_reg_manager) # Group with",
"to group with. output_ops = op_handler_util.remove_non_passthrough_ops( output_ops, op_reg_manager) # Only group with ops",
"output op. \"\"\" return op_handler_util.get_op_slices(output_ops, op_reg_manager) def create_regularizer(self, _): raise NotImplementedError('Not a source",
"ops that have # mismatched size. output_ops_to_group, output_ops_to_process = ( op_handler_util.separate_same_size_ops(op, output_ops)) #",
"If sizes for current and output op slices are not the same. \"\"\"",
"ValueError('Current op and output op have differing slice ' 'sizes: {}, {}'.format( op_slice_sizes,",
"outputs. op_handler_util.group_op_with_inputs_and_outputs( op, [], output_op_slices, aligned_op_slice_sizes, op_reg_manager) # Reprocess ops. op_reg_manager.process_ops(output_ops_to_process + input_ops_to_process)",
"return False def assign_grouping(self, op, op_reg_manager): \"\"\"Assign grouping to the given op and",
"for OutputNonPassthrough ops. OutputNonPassthrough ops take their regularizer from the output and do",
"op_handler_util.get_op_slice_sizes( output_op_slices) op_slice_sizes = op_handler_util.get_op_slice_sizes([op_slices]) if op_slice_sizes != output_op_slices_sizes: raise ValueError('Current op and",
"or tell the manager to process them. output_ops = op_handler_util.get_output_ops(op, op_reg_manager) output_ops_without_group =",
"op_reg_manager) # Only group with ops that have the same size. Process the",
"as ops may have been resliced. output_op_slices = self._get_output_op_slices( output_ops_to_group, op_reg_manager) # Group",
"input ops have groups, or tell the manager to process them. input_ops =",
"to their input. \"\"\" @property def is_source_op(self): return False @property def is_passthrough(self): return",
"updates the manager. Args: op: tf.Operation to assign grouping to. op_reg_manager: OpRegularizerManager to",
"aligned with output, groups the corresponding OpSlice. Args: op: tf.Operation to determine grouping",
"to keep track of the grouping. Returns: A list of list of OpSlice",
"to keep track of the grouping. \"\"\" # Check if all input ops",
"op_handler_util.get_op_slice_sizes([op_slices]) if op_slice_sizes != output_op_slices_sizes: raise ValueError('Current op and output op have differing",
"input_ops_to_process) def _group_with_output_slices( self, op, output_op_slices, op_slices, op_reg_manager): \"\"\"Groups OpSlice of current op",
"op_handler_util.get_input_ops(op, op_reg_manager) input_ops_without_group = op_handler_util.get_ops_without_groups( input_ops, op_reg_manager) # Check if all output ops",
"from morph_net.framework import op_handler from morph_net.framework import op_handler_util class OutputNonPassthroughOpHandler(op_handler.OpHandler): \"\"\"OpHandler implementation for",
"and updates the manager. Args: op: tf.Operation to assign grouping to. op_reg_manager: OpRegularizerManager",
"# Check if all output ops have groups, or tell the manager to",
"Conv2D and MatMul when L1-gamma regularization is used. \"\"\" from __future__ import absolute_import",
"op_handler_util.get_aligned_op_slice_sizes( op_slices, [], output_op_slices) op_handler_util.reslice_ops([op] + output_ops_to_group, aligned_op_slice_sizes, op_reg_manager) # TODO(a1): Consider refactoring",
"outputs ops to group with. output_ops = op_handler_util.remove_non_passthrough_ops( output_ops, op_reg_manager) # Only group",
"the default OpHandler for ops like Conv2D and MatMul when L1-gamma regularization is",
"= op_handler_util.get_input_ops(op, op_reg_manager) input_ops_without_group = op_handler_util.get_ops_without_groups( input_ops, op_reg_manager) # Check if all output",
"morph_net.framework import op_handler from morph_net.framework import op_handler_util class OutputNonPassthroughOpHandler(op_handler.OpHandler): \"\"\"OpHandler implementation for OutputNonPassthrough",
"the corresponding OpSlice. Args: op: tf.Operation to determine grouping for. output_op_slices: List of",
"output_ops: List of tf.Operation. op_reg_manager: OpRegularizerManager to keep track of the grouping. Returns:",
"op slices for outputs. Args: output_ops: List of tf.Operation. op_reg_manager: OpRegularizerManager to keep",
"ValueError: If sizes for current and output op slices are not the same.",
"when L1-gamma regularization is used. \"\"\" from __future__ import absolute_import from __future__ import",
"list of list of OpSlice with a list per output op. \"\"\" return",
"aligned_op_slice_sizes, op_reg_manager) # TODO(a1): Consider refactoring this method. # Repopulate OpSlice data, as",
"is_passthrough(self): return False def assign_grouping(self, op, op_reg_manager): \"\"\"Assign grouping to the given op",
"List of list of OpSlice, with a list per output op. op_slices: List",
"op, op_reg_manager): \"\"\"Assign grouping to the given op and updates the manager. Args:",
"grouping. Raises: ValueError: If sizes for current and output op slices are not",
"from outputs ops to group with. output_ops = op_handler_util.remove_non_passthrough_ops( output_ops, op_reg_manager) # Only",
"ops have groups, or tell the manager to process them. output_ops = op_handler_util.get_output_ops(op,",
"output and do not passthrough the regularizer to their input. This is the",
"op. \"\"\" return op_handler_util.get_op_slices(output_ops, op_reg_manager) def create_regularizer(self, _): raise NotImplementedError('Not a source op.')",
"assign grouping to. op_reg_manager: OpRegularizerManager to keep track of the grouping. \"\"\" #",
"__future__ import absolute_import from __future__ import division from __future__ import print_function from morph_net.framework",
"@property def is_passthrough(self): return False def assign_grouping(self, op, op_reg_manager): \"\"\"Assign grouping to the",
"been resliced. output_op_slices = self._get_output_op_slices( output_ops_to_group, op_reg_manager) # Group with inputs and outputs.",
"keep track of grouping. Raises: ValueError: If sizes for current and output op",
"from the output and do not passthrough the regularizer to their input. This",
"output and do not passthrough the regularizer to their input. \"\"\" @property def",
"for outputs. Args: output_ops: List of tf.Operation. op_reg_manager: OpRegularizerManager to keep track of",
"regularizer from the output and do not passthrough the regularizer to their input.",
"have the same size. Process the ops that have # mismatched size. output_ops_to_group,",
"their regularizer from the output and do not passthrough the regularizer to their",
"to process them. output_ops = op_handler_util.get_output_ops(op, op_reg_manager) output_ops_without_group = op_handler_util.get_ops_without_groups( output_ops, op_reg_manager) #",
"the ops that have # mismatched size. output_ops_to_group, output_ops_to_process = ( op_handler_util.separate_same_size_ops(op, output_ops))",
"regularizer to their input. \"\"\" @property def is_source_op(self): return False @property def is_passthrough(self):",
"op_reg_manager): \"\"\"Groups OpSlice of current op with output ops. Assuming OpSlice of op",
"op slices are not the same. \"\"\" # Assert that op slices for",
"_get_output_op_slices(self, output_ops, op_reg_manager): \"\"\"Returns op slices for outputs. Args: output_ops: List of tf.Operation.",
"op_slices, [], output_op_slices) op_handler_util.reslice_ops([op] + output_ops_to_group, aligned_op_slice_sizes, op_reg_manager) # TODO(a1): Consider refactoring this",
"op_reg_manager) input_ops_without_group = op_handler_util.get_ops_without_groups( input_ops, op_reg_manager) # Check if all output ops have",
"input_ops = op_handler_util.get_input_ops(op, op_reg_manager) input_ops_without_group = op_handler_util.get_ops_without_groups( input_ops, op_reg_manager) # Check if all",
"op_reg_manager) # TODO(a1): Consider refactoring this method. # Repopulate OpSlice data, as ops",
"return False @property def is_passthrough(self): return False def assign_grouping(self, op, op_reg_manager): \"\"\"Assign grouping",
"Remove non-passthrough ops from outputs ops to group with. output_ops = op_handler_util.remove_non_passthrough_ops( output_ops,",
"OutputNonPassthrough ops take their regularizer from the output and do not passthrough the",
"__future__ import division from __future__ import print_function from morph_net.framework import op_handler from morph_net.framework",
"__future__ import print_function from morph_net.framework import op_handler from morph_net.framework import op_handler_util class OutputNonPassthroughOpHandler(op_handler.OpHandler):",
"Reprocess ops. op_reg_manager.process_ops(output_ops_to_process + input_ops_to_process) def _group_with_output_slices( self, op, output_op_slices, op_slices, op_reg_manager): \"\"\"Groups",
"output and current op are aligned. output_op_slices_sizes = op_handler_util.get_op_slice_sizes( output_op_slices) op_slice_sizes = op_handler_util.get_op_slice_sizes([op_slices])",
"Returns: A list of list of OpSlice with a list per output op.",
"op: tf.Operation to determine grouping for. output_op_slices: List of list of OpSlice, with",
"used. \"\"\" from __future__ import absolute_import from __future__ import division from __future__ import",
"output_op_slices, aligned_op_slice_sizes, op_reg_manager) # Reprocess ops. op_reg_manager.process_ops(output_ops_to_process + input_ops_to_process) def _group_with_output_slices( self, op,",
"determine grouping for. output_op_slices: List of list of OpSlice, with a list per",
"op_reg_manager) # Remove non-passthrough ops from outputs ops to group with. output_ops =",
"aligned. output_op_slices_sizes = op_handler_util.get_op_slice_sizes( output_op_slices) op_slice_sizes = op_handler_util.get_op_slice_sizes([op_slices]) if op_slice_sizes != output_op_slices_sizes: raise",
"op_slices, op_reg_manager): \"\"\"Groups OpSlice of current op with output ops. Assuming OpSlice of",
"# Group with inputs and outputs. op_handler_util.group_op_with_inputs_and_outputs( op, [], output_op_slices, aligned_op_slice_sizes, op_reg_manager) #",
"that have # mismatched size. output_ops_to_group, output_ops_to_process = ( op_handler_util.separate_same_size_ops(op, output_ops)) # Also",
"tf.Operation to determine grouping for. output_op_slices: List of list of OpSlice, with a",
"that op slices for output and current op are aligned. output_op_slices_sizes = op_handler_util.get_op_slice_sizes(",
"<gh_stars>1000+ \"\"\"OpHandler for OutputNonPassthrough ops. OutputNonPassthrough ops take their regularizer from the output",
"[], output_op_slices) op_handler_util.reslice_ops([op] + output_ops_to_group, aligned_op_slice_sizes, op_reg_manager) # TODO(a1): Consider refactoring this method.",
"Process the ops that have # mismatched size. output_ops_to_group, output_ops_to_process = ( op_handler_util.separate_same_size_ops(op,",
"are not the same. \"\"\" # Assert that op slices for output and",
"this method. # Repopulate OpSlice data, as ops may have been resliced. output_op_slices",
"track of the grouping. Returns: A list of list of OpSlice with a",
"list of OpSlice with a list per output op. \"\"\" return op_handler_util.get_op_slices(output_ops, op_reg_manager)",
"# TODO(a1): Consider refactoring this method. # Repopulate OpSlice data, as ops may",
"grouping. \"\"\" # Check if all input ops have groups, or tell the",
"OpSlice of current op with output ops. Assuming OpSlice of op have been",
"tell the manager to process them. output_ops = op_handler_util.get_output_ops(op, op_reg_manager) output_ops_without_group = op_handler_util.get_ops_without_groups(",
"# Align op slice sizes if needed. op_slices = op_reg_manager.get_op_slices(op) output_op_slices = op_handler_util.get_op_slices(",
"have been aligned with output, groups the corresponding OpSlice. Args: op: tf.Operation to",
"passthrough the regularizer to their input. This is the default OpHandler for ops",
"passthrough the regularizer to their input. \"\"\" @property def is_source_op(self): return False @property",
"ungrouped ops. input_ops_to_process = input_ops_without_group output_ops_to_process.extend(output_ops_without_group) # Align op slice sizes if needed.",
"the given op and updates the manager. Args: op: tf.Operation to assign grouping",
"op slice sizes if needed. op_slices = op_reg_manager.get_op_slices(op) output_op_slices = op_handler_util.get_op_slices( output_ops_to_group, op_reg_manager)",
"op_slice_sizes, output_op_slices_sizes)) op_handler_util.group_op_with_inputs_and_outputs( op, [], output_op_slices, op_slice_sizes, op_reg_manager) def _get_output_op_slices(self, output_ops, op_reg_manager): \"\"\"Returns",
"process ungrouped ops. input_ops_to_process = input_ops_without_group output_ops_to_process.extend(output_ops_without_group) # Align op slice sizes if",
"Repopulate OpSlice data, as ops may have been resliced. output_op_slices = self._get_output_op_slices( output_ops_to_group,",
"Assuming OpSlice of op have been aligned with output, groups the corresponding OpSlice.",
"input_ops_to_process = input_ops_without_group output_ops_to_process.extend(output_ops_without_group) # Align op slice sizes if needed. op_slices =",
"= self._get_output_op_slices( output_ops_to_group, op_reg_manager) # Group with inputs and outputs. op_handler_util.group_op_with_inputs_and_outputs( op, [],",
"OpRegularizerManager to keep track of the grouping. Returns: A list of list of",
"output op have differing slice ' 'sizes: {}, {}'.format( op_slice_sizes, output_op_slices_sizes)) op_handler_util.group_op_with_inputs_and_outputs( op,",
"\"\"\" @property def is_source_op(self): return False @property def is_passthrough(self): return False def assign_grouping(self,",
"= op_handler_util.get_ops_without_groups( output_ops, op_reg_manager) # Remove non-passthrough ops from outputs ops to group",
"to their input. This is the default OpHandler for ops like Conv2D and",
"for. output_op_slices: List of list of OpSlice, with a list per output op.",
"output_op_slices = self._get_output_op_slices( output_ops_to_group, op_reg_manager) # Group with inputs and outputs. op_handler_util.group_op_with_inputs_and_outputs( op,",
"output_ops = op_handler_util.remove_non_passthrough_ops( output_ops, op_reg_manager) # Only group with ops that have the",
"implementation for OutputNonPassthrough operations. These ops take their regularizer from the output and",
"Check if all output ops have groups, or tell the manager to process",
"and do not passthrough the regularizer to their input. \"\"\" @property def is_source_op(self):",
"of OpSlice for current op. op_reg_manager: OpRegularizerManager to keep track of grouping. Raises:",
"the regularizer to their input. \"\"\" @property def is_source_op(self): return False @property def",
"if needed. op_slices = op_reg_manager.get_op_slices(op) output_op_slices = op_handler_util.get_op_slices( output_ops_to_group, op_reg_manager) aligned_op_slice_sizes = op_handler_util.get_aligned_op_slice_sizes(",
"output_op_slices) op_handler_util.reslice_ops([op] + output_ops_to_group, aligned_op_slice_sizes, op_reg_manager) # TODO(a1): Consider refactoring this method. #",
"input. \"\"\" @property def is_source_op(self): return False @property def is_passthrough(self): return False def",
"list per output op. op_slices: List of OpSlice for current op. op_reg_manager: OpRegularizerManager",
"ops. OutputNonPassthrough ops take their regularizer from the output and do not passthrough",
"all output ops have groups, or tell the manager to process them. output_ops",
"op, [], output_op_slices, op_slice_sizes, op_reg_manager) def _get_output_op_slices(self, output_ops, op_reg_manager): \"\"\"Returns op slices for",
"output_ops_to_process = ( op_handler_util.separate_same_size_ops(op, output_ops)) # Also process ungrouped ops. input_ops_to_process = input_ops_without_group",
"op: tf.Operation to assign grouping to. op_reg_manager: OpRegularizerManager to keep track of the",
"keep track of the grouping. Returns: A list of list of OpSlice with",
"OpSlice of op have been aligned with output, groups the corresponding OpSlice. Args:",
"op have differing slice ' 'sizes: {}, {}'.format( op_slice_sizes, output_op_slices_sizes)) op_handler_util.group_op_with_inputs_and_outputs( op, [],",
"mismatched size. output_ops_to_group, output_ops_to_process = ( op_handler_util.separate_same_size_ops(op, output_ops)) # Also process ungrouped ops.",
"not passthrough the regularizer to their input. This is the default OpHandler for",
"regularization is used. \"\"\" from __future__ import absolute_import from __future__ import division from",
"Assert that op slices for output and current op are aligned. output_op_slices_sizes =",
"op_slice_sizes = op_handler_util.get_op_slice_sizes([op_slices]) if op_slice_sizes != output_op_slices_sizes: raise ValueError('Current op and output op",
"group with ops that have the same size. Process the ops that have",
"op_reg_manager.process_ops(output_ops_to_process + input_ops_to_process) def _group_with_output_slices( self, op, output_op_slices, op_slices, op_reg_manager): \"\"\"Groups OpSlice of",
"differing slice ' 'sizes: {}, {}'.format( op_slice_sizes, output_op_slices_sizes)) op_handler_util.group_op_with_inputs_and_outputs( op, [], output_op_slices, op_slice_sizes,",
"OutputNonPassthrough ops. OutputNonPassthrough ops take their regularizer from the output and do not",
"Only group with ops that have the same size. Process the ops that",
"of list of OpSlice, with a list per output op. op_slices: List of",
"from the output and do not passthrough the regularizer to their input. \"\"\"",
"import op_handler_util class OutputNonPassthroughOpHandler(op_handler.OpHandler): \"\"\"OpHandler implementation for OutputNonPassthrough operations. These ops take their",
"OpRegularizerManager to keep track of the grouping. \"\"\" # Check if all input",
"' 'sizes: {}, {}'.format( op_slice_sizes, output_op_slices_sizes)) op_handler_util.group_op_with_inputs_and_outputs( op, [], output_op_slices, op_slice_sizes, op_reg_manager) def",
"group with. output_ops = op_handler_util.remove_non_passthrough_ops( output_ops, op_reg_manager) # Only group with ops that",
"Align op slice sizes if needed. op_slices = op_reg_manager.get_op_slices(op) output_op_slices = op_handler_util.get_op_slices( output_ops_to_group,",
"output, groups the corresponding OpSlice. Args: op: tf.Operation to determine grouping for. output_op_slices:",
"ops have groups, or tell the manager to process them. input_ops = op_handler_util.get_input_ops(op,",
"of list of OpSlice with a list per output op. \"\"\" return op_handler_util.get_op_slices(output_ops,",
"the same. \"\"\" # Assert that op slices for output and current op",
"non-passthrough ops from outputs ops to group with. output_ops = op_handler_util.remove_non_passthrough_ops( output_ops, op_reg_manager)",
"slice sizes if needed. op_slices = op_reg_manager.get_op_slices(op) output_op_slices = op_handler_util.get_op_slices( output_ops_to_group, op_reg_manager) aligned_op_slice_sizes",
"output_ops)) # Also process ungrouped ops. input_ops_to_process = input_ops_without_group output_ops_to_process.extend(output_ops_without_group) # Align op",
"op_handler_util.reslice_ops([op] + output_ops_to_group, aligned_op_slice_sizes, op_reg_manager) # TODO(a1): Consider refactoring this method. # Repopulate",
"with output, groups the corresponding OpSlice. Args: op: tf.Operation to determine grouping for.",
"current op with output ops. Assuming OpSlice of op have been aligned with",
"\"\"\"OpHandler for OutputNonPassthrough ops. OutputNonPassthrough ops take their regularizer from the output and",
"output_ops_to_group, op_reg_manager) # Group with inputs and outputs. op_handler_util.group_op_with_inputs_and_outputs( op, [], output_op_slices, aligned_op_slice_sizes,",
"ops like Conv2D and MatMul when L1-gamma regularization is used. \"\"\" from __future__",
"keep track of the grouping. \"\"\" # Check if all input ops have",
"op_reg_manager): \"\"\"Assign grouping to the given op and updates the manager. Args: op:",
"been aligned with output, groups the corresponding OpSlice. Args: op: tf.Operation to determine",
"with a list per output op. op_slices: List of OpSlice for current op.",
"refactoring this method. # Repopulate OpSlice data, as ops may have been resliced.",
"grouping to. op_reg_manager: OpRegularizerManager to keep track of the grouping. \"\"\" # Check",
"op_slice_sizes != output_op_slices_sizes: raise ValueError('Current op and output op have differing slice '",
"import op_handler from morph_net.framework import op_handler_util class OutputNonPassthroughOpHandler(op_handler.OpHandler): \"\"\"OpHandler implementation for OutputNonPassthrough operations.",
"op_slices = op_reg_manager.get_op_slices(op) output_op_slices = op_handler_util.get_op_slices( output_ops_to_group, op_reg_manager) aligned_op_slice_sizes = op_handler_util.get_aligned_op_slice_sizes( op_slices, [],",
"'sizes: {}, {}'.format( op_slice_sizes, output_op_slices_sizes)) op_handler_util.group_op_with_inputs_and_outputs( op, [], output_op_slices, op_slice_sizes, op_reg_manager) def _get_output_op_slices(self,",
"manager. Args: op: tf.Operation to assign grouping to. op_reg_manager: OpRegularizerManager to keep track",
"[], output_op_slices, op_slice_sizes, op_reg_manager) def _get_output_op_slices(self, output_ops, op_reg_manager): \"\"\"Returns op slices for outputs.",
"input_ops_without_group output_ops_to_process.extend(output_ops_without_group) # Align op slice sizes if needed. op_slices = op_reg_manager.get_op_slices(op) output_op_slices",
"for OutputNonPassthrough operations. These ops take their regularizer from the output and do",
"def is_source_op(self): return False @property def is_passthrough(self): return False def assign_grouping(self, op, op_reg_manager):",
"have groups, or tell the manager to process them. output_ops = op_handler_util.get_output_ops(op, op_reg_manager)",
"for output and current op are aligned. output_op_slices_sizes = op_handler_util.get_op_slice_sizes( output_op_slices) op_slice_sizes =",
"grouping to the given op and updates the manager. Args: op: tf.Operation to",
"op_slices: List of OpSlice for current op. op_reg_manager: OpRegularizerManager to keep track of",
"OpSlice data, as ops may have been resliced. output_op_slices = self._get_output_op_slices( output_ops_to_group, op_reg_manager)",
"output_op_slices, op_slices, op_reg_manager): \"\"\"Groups OpSlice of current op with output ops. Assuming OpSlice",
"same. \"\"\" # Assert that op slices for output and current op are",
"False @property def is_passthrough(self): return False def assign_grouping(self, op, op_reg_manager): \"\"\"Assign grouping to",
"size. Process the ops that have # mismatched size. output_ops_to_group, output_ops_to_process = (",
"OpSlice. Args: op: tf.Operation to determine grouping for. output_op_slices: List of list of",
"tf.Operation. op_reg_manager: OpRegularizerManager to keep track of the grouping. Returns: A list of",
"Also process ungrouped ops. input_ops_to_process = input_ops_without_group output_ops_to_process.extend(output_ops_without_group) # Align op slice sizes",
"to keep track of grouping. Raises: ValueError: If sizes for current and output",
"# Also process ungrouped ops. input_ops_to_process = input_ops_without_group output_ops_to_process.extend(output_ops_without_group) # Align op slice",
"same size. Process the ops that have # mismatched size. output_ops_to_group, output_ops_to_process =",
"method. # Repopulate OpSlice data, as ops may have been resliced. output_op_slices =",
"\"\"\" # Assert that op slices for output and current op are aligned.",
"default OpHandler for ops like Conv2D and MatMul when L1-gamma regularization is used.",
"have # mismatched size. output_ops_to_group, output_ops_to_process = ( op_handler_util.separate_same_size_ops(op, output_ops)) # Also process",
"= op_reg_manager.get_op_slices(op) output_op_slices = op_handler_util.get_op_slices( output_ops_to_group, op_reg_manager) aligned_op_slice_sizes = op_handler_util.get_aligned_op_slice_sizes( op_slices, [], output_op_slices)",
"with inputs and outputs. op_handler_util.group_op_with_inputs_and_outputs( op, [], output_op_slices, aligned_op_slice_sizes, op_reg_manager) # Reprocess ops.",
"self, op, output_op_slices, op_slices, op_reg_manager): \"\"\"Groups OpSlice of current op with output ops.",
"OpSlice, with a list per output op. op_slices: List of OpSlice for current",
"op_handler_util.get_output_ops(op, op_reg_manager) output_ops_without_group = op_handler_util.get_ops_without_groups( output_ops, op_reg_manager) # Remove non-passthrough ops from outputs",
"input_ops_without_group = op_handler_util.get_ops_without_groups( input_ops, op_reg_manager) # Check if all output ops have groups,",
"ops. op_reg_manager.process_ops(output_ops_to_process + input_ops_to_process) def _group_with_output_slices( self, op, output_op_slices, op_slices, op_reg_manager): \"\"\"Groups OpSlice",
"slices for output and current op are aligned. output_op_slices_sizes = op_handler_util.get_op_slice_sizes( output_op_slices) op_slice_sizes",
"= input_ops_without_group output_ops_to_process.extend(output_ops_without_group) # Align op slice sizes if needed. op_slices = op_reg_manager.get_op_slices(op)",
"like Conv2D and MatMul when L1-gamma regularization is used. \"\"\" from __future__ import",
"op and output op have differing slice ' 'sizes: {}, {}'.format( op_slice_sizes, output_op_slices_sizes))",
"to determine grouping for. output_op_slices: List of list of OpSlice, with a list",
"the grouping. Returns: A list of list of OpSlice with a list per",
"is used. \"\"\" from __future__ import absolute_import from __future__ import division from __future__",
"inputs and outputs. op_handler_util.group_op_with_inputs_and_outputs( op, [], output_op_slices, aligned_op_slice_sizes, op_reg_manager) # Reprocess ops. op_reg_manager.process_ops(output_ops_to_process",
"and MatMul when L1-gamma regularization is used. \"\"\" from __future__ import absolute_import from",
"output_ops, op_reg_manager): \"\"\"Returns op slices for outputs. Args: output_ops: List of tf.Operation. op_reg_manager:",
"op with output ops. Assuming OpSlice of op have been aligned with output,",
"tell the manager to process them. input_ops = op_handler_util.get_input_ops(op, op_reg_manager) input_ops_without_group = op_handler_util.get_ops_without_groups(",
"Check if all input ops have groups, or tell the manager to process",
"division from __future__ import print_function from morph_net.framework import op_handler from morph_net.framework import op_handler_util",
"output_op_slices_sizes = op_handler_util.get_op_slice_sizes( output_op_slices) op_slice_sizes = op_handler_util.get_op_slice_sizes([op_slices]) if op_slice_sizes != output_op_slices_sizes: raise ValueError('Current",
"a list per output op. \"\"\" return op_handler_util.get_op_slices(output_ops, op_reg_manager) def create_regularizer(self, _): raise",
"This is the default OpHandler for ops like Conv2D and MatMul when L1-gamma",
"OutputNonPassthrough operations. These ops take their regularizer from the output and do not",
"for current op. op_reg_manager: OpRegularizerManager to keep track of grouping. Raises: ValueError: If",
"of tf.Operation. op_reg_manager: OpRegularizerManager to keep track of the grouping. Returns: A list",
"given op and updates the manager. Args: op: tf.Operation to assign grouping to.",
"sizes for current and output op slices are not the same. \"\"\" #",
"list per output op. \"\"\" return op_handler_util.get_op_slices(output_ops, op_reg_manager) def create_regularizer(self, _): raise NotImplementedError('Not",
"\"\"\"Groups OpSlice of current op with output ops. Assuming OpSlice of op have",
"output_ops_to_group, op_reg_manager) aligned_op_slice_sizes = op_handler_util.get_aligned_op_slice_sizes( op_slices, [], output_op_slices) op_handler_util.reslice_ops([op] + output_ops_to_group, aligned_op_slice_sizes, op_reg_manager)",
"aligned_op_slice_sizes, op_reg_manager) # Reprocess ops. op_reg_manager.process_ops(output_ops_to_process + input_ops_to_process) def _group_with_output_slices( self, op, output_op_slices,",
"ops to group with. output_ops = op_handler_util.remove_non_passthrough_ops( output_ops, op_reg_manager) # Only group with",
"[], output_op_slices, aligned_op_slice_sizes, op_reg_manager) # Reprocess ops. op_reg_manager.process_ops(output_ops_to_process + input_ops_to_process) def _group_with_output_slices( self,",
"sizes if needed. op_slices = op_reg_manager.get_op_slices(op) output_op_slices = op_handler_util.get_op_slices( output_ops_to_group, op_reg_manager) aligned_op_slice_sizes =",
"groups, or tell the manager to process them. input_ops = op_handler_util.get_input_ops(op, op_reg_manager) input_ops_without_group",
"per output op. op_slices: List of OpSlice for current op. op_reg_manager: OpRegularizerManager to",
"False def assign_grouping(self, op, op_reg_manager): \"\"\"Assign grouping to the given op and updates",
"op_handler_util.group_op_with_inputs_and_outputs( op, [], output_op_slices, aligned_op_slice_sizes, op_reg_manager) # Reprocess ops. op_reg_manager.process_ops(output_ops_to_process + input_ops_to_process) def",
"and current op are aligned. output_op_slices_sizes = op_handler_util.get_op_slice_sizes( output_op_slices) op_slice_sizes = op_handler_util.get_op_slice_sizes([op_slices]) if",
"slices are not the same. \"\"\" # Assert that op slices for output",
"OpRegularizerManager to keep track of grouping. Raises: ValueError: If sizes for current and",
"op_handler_util.get_ops_without_groups( output_ops, op_reg_manager) # Remove non-passthrough ops from outputs ops to group with.",
"List of tf.Operation. op_reg_manager: OpRegularizerManager to keep track of the grouping. Returns: A",
"and output op slices are not the same. \"\"\" # Assert that op",
"of current op with output ops. Assuming OpSlice of op have been aligned",
"current op are aligned. output_op_slices_sizes = op_handler_util.get_op_slice_sizes( output_op_slices) op_slice_sizes = op_handler_util.get_op_slice_sizes([op_slices]) if op_slice_sizes",
"have been resliced. output_op_slices = self._get_output_op_slices( output_ops_to_group, op_reg_manager) # Group with inputs and",
"aligned_op_slice_sizes = op_handler_util.get_aligned_op_slice_sizes( op_slices, [], output_op_slices) op_handler_util.reslice_ops([op] + output_ops_to_group, aligned_op_slice_sizes, op_reg_manager) # TODO(a1):",
"grouping. Returns: A list of list of OpSlice with a list per output",
"all input ops have groups, or tell the manager to process them. input_ops",
"from __future__ import division from __future__ import print_function from morph_net.framework import op_handler from",
"Consider refactoring this method. # Repopulate OpSlice data, as ops may have been",
"for ops like Conv2D and MatMul when L1-gamma regularization is used. \"\"\" from",
"A list of list of OpSlice with a list per output op. \"\"\"",
"import print_function from morph_net.framework import op_handler from morph_net.framework import op_handler_util class OutputNonPassthroughOpHandler(op_handler.OpHandler): \"\"\"OpHandler",
"the output and do not passthrough the regularizer to their input. This is",
"process them. output_ops = op_handler_util.get_output_ops(op, op_reg_manager) output_ops_without_group = op_handler_util.get_ops_without_groups( output_ops, op_reg_manager) # Remove",
"manager to process them. input_ops = op_handler_util.get_input_ops(op, op_reg_manager) input_ops_without_group = op_handler_util.get_ops_without_groups( input_ops, op_reg_manager)",
"ops. Assuming OpSlice of op have been aligned with output, groups the corresponding",
"of grouping. Raises: ValueError: If sizes for current and output op slices are",
"groups the corresponding OpSlice. Args: op: tf.Operation to determine grouping for. output_op_slices: List",
"op_slice_sizes, op_reg_manager) def _get_output_op_slices(self, output_ops, op_reg_manager): \"\"\"Returns op slices for outputs. Args: output_ops:",
"= op_handler_util.get_op_slices( output_ops_to_group, op_reg_manager) aligned_op_slice_sizes = op_handler_util.get_aligned_op_slice_sizes( op_slices, [], output_op_slices) op_handler_util.reslice_ops([op] + output_ops_to_group,",
"is the default OpHandler for ops like Conv2D and MatMul when L1-gamma regularization",
"from __future__ import absolute_import from __future__ import division from __future__ import print_function from",
"output ops. Assuming OpSlice of op have been aligned with output, groups the",
"op. op_slices: List of OpSlice for current op. op_reg_manager: OpRegularizerManager to keep track",
"op_handler_util.get_ops_without_groups( input_ops, op_reg_manager) # Check if all output ops have groups, or tell",
"output_op_slices_sizes)) op_handler_util.group_op_with_inputs_and_outputs( op, [], output_op_slices, op_slice_sizes, op_reg_manager) def _get_output_op_slices(self, output_ops, op_reg_manager): \"\"\"Returns op",
"OpSlice with a list per output op. \"\"\" return op_handler_util.get_op_slices(output_ops, op_reg_manager) def create_regularizer(self,",
"the grouping. \"\"\" # Check if all input ops have groups, or tell",
"output_op_slices) op_slice_sizes = op_handler_util.get_op_slice_sizes([op_slices]) if op_slice_sizes != output_op_slices_sizes: raise ValueError('Current op and output",
"the regularizer to their input. This is the default OpHandler for ops like",
"morph_net.framework import op_handler_util class OutputNonPassthroughOpHandler(op_handler.OpHandler): \"\"\"OpHandler implementation for OutputNonPassthrough operations. These ops take",
"have groups, or tell the manager to process them. input_ops = op_handler_util.get_input_ops(op, op_reg_manager)",
"= ( op_handler_util.separate_same_size_ops(op, output_ops)) # Also process ungrouped ops. input_ops_to_process = input_ops_without_group output_ops_to_process.extend(output_ops_without_group)",
"and do not passthrough the regularizer to their input. This is the default",
"them. output_ops = op_handler_util.get_output_ops(op, op_reg_manager) output_ops_without_group = op_handler_util.get_ops_without_groups( output_ops, op_reg_manager) # Remove non-passthrough",
"if all input ops have groups, or tell the manager to process them.",
"output_ops, op_reg_manager) # Remove non-passthrough ops from outputs ops to group with. output_ops",
"OpSlice for current op. op_reg_manager: OpRegularizerManager to keep track of grouping. Raises: ValueError:",
"_group_with_output_slices( self, op, output_op_slices, op_slices, op_reg_manager): \"\"\"Groups OpSlice of current op with output",
"do not passthrough the regularizer to their input. \"\"\" @property def is_source_op(self): return",
"op_reg_manager: OpRegularizerManager to keep track of the grouping. Returns: A list of list",
"for current and output op slices are not the same. \"\"\" # Assert",
"output_ops_to_group, aligned_op_slice_sizes, op_reg_manager) # TODO(a1): Consider refactoring this method. # Repopulate OpSlice data,",
"not passthrough the regularizer to their input. \"\"\" @property def is_source_op(self): return False",
"to process them. input_ops = op_handler_util.get_input_ops(op, op_reg_manager) input_ops_without_group = op_handler_util.get_ops_without_groups( input_ops, op_reg_manager) #",
"@property def is_source_op(self): return False @property def is_passthrough(self): return False def assign_grouping(self, op,",
"tf.Operation to assign grouping to. op_reg_manager: OpRegularizerManager to keep track of the grouping.",
"output_ops_without_group = op_handler_util.get_ops_without_groups( output_ops, op_reg_manager) # Remove non-passthrough ops from outputs ops to",
"list of OpSlice, with a list per output op. op_slices: List of OpSlice",
"op have been aligned with output, groups the corresponding OpSlice. Args: op: tf.Operation",
"def _group_with_output_slices( self, op, output_op_slices, op_slices, op_reg_manager): \"\"\"Groups OpSlice of current op with",
"\"\"\" from __future__ import absolute_import from __future__ import division from __future__ import print_function",
"not the same. \"\"\" # Assert that op slices for output and current",
"track of grouping. Raises: ValueError: If sizes for current and output op slices",
"= op_handler_util.get_op_slice_sizes([op_slices]) if op_slice_sizes != output_op_slices_sizes: raise ValueError('Current op and output op have",
"if op_slice_sizes != output_op_slices_sizes: raise ValueError('Current op and output op have differing slice",
"op slices for output and current op are aligned. output_op_slices_sizes = op_handler_util.get_op_slice_sizes( output_op_slices)",
"of the grouping. Returns: A list of list of OpSlice with a list",
"their input. This is the default OpHandler for ops like Conv2D and MatMul",
"= op_handler_util.get_op_slice_sizes( output_op_slices) op_slice_sizes = op_handler_util.get_op_slice_sizes([op_slices]) if op_slice_sizes != output_op_slices_sizes: raise ValueError('Current op",
"resliced. output_op_slices = self._get_output_op_slices( output_ops_to_group, op_reg_manager) # Group with inputs and outputs. op_handler_util.group_op_with_inputs_and_outputs(",
"do not passthrough the regularizer to their input. This is the default OpHandler",
"from __future__ import print_function from morph_net.framework import op_handler from morph_net.framework import op_handler_util class",
"\"\"\"Assign grouping to the given op and updates the manager. Args: op: tf.Operation",
"= op_handler_util.get_aligned_op_slice_sizes( op_slices, [], output_op_slices) op_handler_util.reslice_ops([op] + output_ops_to_group, aligned_op_slice_sizes, op_reg_manager) # TODO(a1): Consider",
"output_op_slices_sizes: raise ValueError('Current op and output op have differing slice ' 'sizes: {},",
"corresponding OpSlice. Args: op: tf.Operation to determine grouping for. output_op_slices: List of list",
"or tell the manager to process them. input_ops = op_handler_util.get_input_ops(op, op_reg_manager) input_ops_without_group =",
"+ output_ops_to_group, aligned_op_slice_sizes, op_reg_manager) # TODO(a1): Consider refactoring this method. # Repopulate OpSlice",
"op are aligned. output_op_slices_sizes = op_handler_util.get_op_slice_sizes( output_op_slices) op_slice_sizes = op_handler_util.get_op_slice_sizes([op_slices]) if op_slice_sizes !=",
"op_reg_manager) # Reprocess ops. op_reg_manager.process_ops(output_ops_to_process + input_ops_to_process) def _group_with_output_slices( self, op, output_op_slices, op_slices,",
"slices for outputs. Args: output_ops: List of tf.Operation. op_reg_manager: OpRegularizerManager to keep track",
"Group with inputs and outputs. op_handler_util.group_op_with_inputs_and_outputs( op, [], output_op_slices, aligned_op_slice_sizes, op_reg_manager) # Reprocess",
"data, as ops may have been resliced. output_op_slices = self._get_output_op_slices( output_ops_to_group, op_reg_manager) #",
"is_source_op(self): return False @property def is_passthrough(self): return False def assign_grouping(self, op, op_reg_manager): \"\"\"Assign",
"class OutputNonPassthroughOpHandler(op_handler.OpHandler): \"\"\"OpHandler implementation for OutputNonPassthrough operations. These ops take their regularizer from",
"L1-gamma regularization is used. \"\"\" from __future__ import absolute_import from __future__ import division",
"output op slices are not the same. \"\"\" # Assert that op slices",
"= op_handler_util.remove_non_passthrough_ops( output_ops, op_reg_manager) # Only group with ops that have the same",
"op_reg_manager) def _get_output_op_slices(self, output_ops, op_reg_manager): \"\"\"Returns op slices for outputs. Args: output_ops: List",
"with a list per output op. \"\"\" return op_handler_util.get_op_slices(output_ops, op_reg_manager) def create_regularizer(self, _):",
"= op_handler_util.get_output_ops(op, op_reg_manager) output_ops_without_group = op_handler_util.get_ops_without_groups( output_ops, op_reg_manager) # Remove non-passthrough ops from",
"op_handler_util.separate_same_size_ops(op, output_ops)) # Also process ungrouped ops. input_ops_to_process = input_ops_without_group output_ops_to_process.extend(output_ops_without_group) # Align",
"op_handler_util.group_op_with_inputs_and_outputs( op, [], output_op_slices, op_slice_sizes, op_reg_manager) def _get_output_op_slices(self, output_ops, op_reg_manager): \"\"\"Returns op slices",
"import division from __future__ import print_function from morph_net.framework import op_handler from morph_net.framework import",
"to. op_reg_manager: OpRegularizerManager to keep track of the grouping. \"\"\" # Check if",
"output_ops, op_reg_manager) # Only group with ops that have the same size. Process",
"output op. op_slices: List of OpSlice for current op. op_reg_manager: OpRegularizerManager to keep",
"track of the grouping. \"\"\" # Check if all input ops have groups,",
"output_ops_to_group, output_ops_to_process = ( op_handler_util.separate_same_size_ops(op, output_ops)) # Also process ungrouped ops. input_ops_to_process =",
"ops take their regularizer from the output and do not passthrough the regularizer",
"OpHandler for ops like Conv2D and MatMul when L1-gamma regularization is used. \"\"\"",
"# Repopulate OpSlice data, as ops may have been resliced. output_op_slices = self._get_output_op_slices(",
"print_function from morph_net.framework import op_handler from morph_net.framework import op_handler_util class OutputNonPassthroughOpHandler(op_handler.OpHandler): \"\"\"OpHandler implementation",
"op_handler from morph_net.framework import op_handler_util class OutputNonPassthroughOpHandler(op_handler.OpHandler): \"\"\"OpHandler implementation for OutputNonPassthrough operations. These",
"operations. These ops take their regularizer from the output and do not passthrough",
"+ input_ops_to_process) def _group_with_output_slices( self, op, output_op_slices, op_slices, op_reg_manager): \"\"\"Groups OpSlice of current",
"\"\"\"Returns op slices for outputs. Args: output_ops: List of tf.Operation. op_reg_manager: OpRegularizerManager to",
"groups, or tell the manager to process them. output_ops = op_handler_util.get_output_ops(op, op_reg_manager) output_ops_without_group",
"take their regularizer from the output and do not passthrough the regularizer to",
"import absolute_import from __future__ import division from __future__ import print_function from morph_net.framework import",
"input_ops, op_reg_manager) # Check if all output ops have groups, or tell the",
"op_reg_manager: OpRegularizerManager to keep track of the grouping. \"\"\" # Check if all",
"ops from outputs ops to group with. output_ops = op_handler_util.remove_non_passthrough_ops( output_ops, op_reg_manager) #",
"!= output_op_slices_sizes: raise ValueError('Current op and output op have differing slice ' 'sizes:",
"def assign_grouping(self, op, op_reg_manager): \"\"\"Assign grouping to the given op and updates the",
"# Check if all input ops have groups, or tell the manager to",
"input. This is the default OpHandler for ops like Conv2D and MatMul when",
"with output ops. Assuming OpSlice of op have been aligned with output, groups",
"Raises: ValueError: If sizes for current and output op slices are not the",
"ops that have the same size. Process the ops that have # mismatched",
"MatMul when L1-gamma regularization is used. \"\"\" from __future__ import absolute_import from __future__",
"of OpSlice with a list per output op. \"\"\" return op_handler_util.get_op_slices(output_ops, op_reg_manager) def"
] |
[
"+ str(left_d) + \" \" + str(top_d)) self.move(left, top, left_d, top_d) left =",
"self.h or x2 < 0 or y2 < 0 or x2 > self.w",
"self.board[x2][y2] = color self.board[(x1 - 1)][y1 + sign] = 0 return else: return",
"left_d = POS[args[i][0]] top_d = 7-(int(args[i][1])-1) except KeyError as e: await ctx.send(\"incorrect input\")",
"if self.board[(x1 + 1)][y1+sign] == opponent_color: self.board[x1][y1] = 0 self.board[x2][y2] = color self.board[(x1",
"str(top_d)) self.move(left, top, left_d, top_d) left = left_d top = top_d self.turn =",
"(y2 - y1) * sign == 2: if x2 - x1 == 2:",
"'g': 6, 'h': 7} class Chess(commands.Cog, name=\"chess test\"): board = [] w =",
"'d': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7} class Chess(commands.Cog, name=\"chess",
"else: return elif (y2 - y1) * sign == 1: self.board[x1][y1] = 0",
"move(self, x1, y1, x2, y2): if self.turn: color = 2 opponent_color = 1",
"import commands POS = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e':",
"1 msg = self.print_board() await ctx.send(msg) @commands.command(name=\"chess\") @commands.cooldown(1, 5, commands.BucketType.default) async def chess(self,",
"input\") return for i in range(len(args)): try: left_d = POS[args[i][0]] top_d = 7-(int(args[i][1])-1)",
"res + str(self.board[x][y]) + \" \" res += \"\\n\" res = res +",
"0 or x2 > self.w or y2 > self.h: return if self.board[x1][y1] !=",
"@commands.command(name=\"chess\") @commands.cooldown(1, 5, commands.BucketType.default) async def chess(self, ctx, arg1, *args): try: left =",
"or x2 > self.w or y2 > self.h: return if self.board[x1][y1] != color",
"y1 < 0 or x1 > self.w or y1 > self.h or x2",
"board = [] w = 8 h = 8 turn = False def",
"y2 < 0 or x2 > self.w or y2 > self.h: return if",
"= not self.turn msg = self.print_board() await ctx.send(msg) def move(self, x1, y1, x2,",
"0 or y2 < 0 or x2 > self.w or y2 > self.h:",
"top = 7 - (int(arg1[1]) - 1) except KeyError as e: await ctx.send(\"incorrect",
"+ 1)][y1 + sign] = 0 return else: return elif x2 - x1",
"sign] = 0 return else: return elif x2 - x1 == -2: if",
"self.turn = not self.turn msg = self.print_board() await ctx.send(msg) def move(self, x1, y1,",
"- 1) except KeyError as e: await ctx.send(\"incorrect input\") return for i in",
"in range(len(args)): try: left_d = POS[args[i][0]] top_d = 7-(int(args[i][1])-1) except KeyError as e:",
"opponent_color: self.board[x1][y1] = 0 self.board[x2][y2] = color self.board[(x1 + 1)][y1 + sign] =",
"class Chess(commands.Cog, name=\"chess test\"): board = [] w = 8 h = 8",
"str(self.board[x][y]) + \" \" res += \"\\n\" res = res + \" _______________\\n\"",
"= 1 msg = self.print_board() await ctx.send(msg) @commands.command(name=\"chess\") @commands.cooldown(1, 5, commands.BucketType.default) async def",
"< 0 or x2 > self.w or y2 > self.h: return if self.board[x1][y1]",
"return for i in range(len(args)): try: left_d = POS[args[i][0]] top_d = 7-(int(args[i][1])-1) except",
"self.board[x1][y1] = 0 self.board[x2][y2] = color self.board[(x1 - 1)][y1 + sign] = 0",
"1)][y1+sign] == opponent_color: self.board[x1][y1] = 0 self.board[x2][y2] = color self.board[(x1 - 1)][y1 +",
"<reponame>adgj-1/cs221bot<gh_stars>0 from discord.ext import commands POS = {'a': 0, 'b': 1, 'c': 2,",
"if self.board[(x1 - 1)][y1+sign] == opponent_color: self.board[x1][y1] = 0 self.board[x2][y2] = color self.board[(x1",
"= 7-(int(args[i][1])-1) except KeyError as e: await ctx.send(\"incorrect input\") return await ctx.send(str(left) +",
"a b c d e f g h\\n\" res += \"```\" return res",
"* sign == 1: self.board[x1][y1] = 0 self.board[x2][y2] = color return def print_board(self):",
"for y in range(self.h)] for y in range(0, 2): for x in range(y",
"await ctx.send(\"incorrect input\") return await ctx.send(str(left) + \" \" + str(top) + \"",
"range(y % 2, 8, 2): self.board[x][y] = 2 for y in range(6, 8):",
"2, 8, 2): self.board[x][y] = 2 for y in range(6, 8): for x",
"1)][y1 + sign] = 0 return else: return elif x2 - x1 ==",
"!= 0: return if (y2 - y1) * sign == 2: if x2",
"for x in range(y % 2, 8, 2): self.board[x][y] = 1 msg =",
"0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6,",
"y in range(0, 2): for x in range(y % 2, 8, 2): self.board[x][y]",
"5, commands.BucketType.default) async def chess(self, ctx, arg1, *args): try: left = POS[arg1[0]] top",
"== -2: if self.board[(x1 - 1)][y1+sign] == opponent_color: self.board[x1][y1] = 0 self.board[x2][y2] =",
"- x1 == -2: if self.board[(x1 - 1)][y1+sign] == opponent_color: self.board[x1][y1] = 0",
"= 0 self.board[x2][y2] = color self.board[(x1 + 1)][y1 + sign] = 0 return",
"= 2 sign = -1 if x1 < 0 or y1 < 0",
"or y1 > self.h or x2 < 0 or y2 < 0 or",
"commands.BucketType.default) async def chess(self, ctx, arg1, *args): try: left = POS[arg1[0]] top =",
"0 return else: return elif (y2 - y1) * sign == 1: self.board[x1][y1]",
"= res + str(self.board[x][y]) + \" \" res += \"\\n\" res = res",
"y1) * sign == 2: if x2 - x1 == 2: if self.board[(x1",
"+ str(top_d)) self.move(left, top, left_d, top_d) left = left_d top = top_d self.turn",
"8 h = 8 turn = False def __init__(self, bot): self.bot = bot",
"to \" + str(left_d) + \" \" + str(top_d)) self.move(left, top, left_d, top_d)",
"+= \"\\n\" res = res + \" _______________\\n\" res = res + \"",
"(y2 - y1) * sign == 1: self.board[x1][y1] = 0 self.board[x2][y2] = color",
"1 else: color = 1 opponent_color = 2 sign = -1 if x1",
"msg = self.print_board() await ctx.send(msg) @commands.command(name=\"chess\") @commands.cooldown(1, 5, commands.BucketType.default) async def chess(self, ctx,",
"range(y % 2, 8, 2): self.board[x][y] = 1 msg = self.print_board() await ctx.send(msg)",
"'f': 5, 'g': 6, 'h': 7} class Chess(commands.Cog, name=\"chess test\"): board = []",
"8, 2): self.board[x][y] = 2 for y in range(6, 8): for x in",
"return elif x2 - x1 == -2: if self.board[(x1 - 1)][y1+sign] == opponent_color:",
"self.w or y2 > self.h: return if self.board[x1][y1] != color or self.board[x2][y2] !=",
"= 1 sign = 1 else: color = 1 opponent_color = 2 sign",
"1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7}",
"0 or x1 > self.w or y1 > self.h or x2 < 0",
"= res + str(8-y) + \"| \" for x in range(0, 8): res",
"POS[args[i][0]] top_d = 7-(int(args[i][1])-1) except KeyError as e: await ctx.send(\"incorrect input\") return await",
"or y1 < 0 or x1 > self.w or y1 > self.h or",
"= POS[args[i][0]] top_d = 7-(int(args[i][1])-1) except KeyError as e: await ctx.send(\"incorrect input\") return",
"8): for x in range(y % 2, 8, 2): self.board[x][y] = 1 msg",
"self.board[x2][y2] = color self.board[(x1 + 1)][y1 + sign] = 0 return else: return",
"> self.h: return if self.board[x1][y1] != color or self.board[x2][y2] != 0: return if",
"7 - (int(arg1[1]) - 1) except KeyError as e: await ctx.send(\"incorrect input\") return",
"[] w = 8 h = 8 turn = False def __init__(self, bot):",
"def __init__(self, bot): self.bot = bot @commands.command(name=\"chessreset\") @commands.cooldown(1, 5, commands.BucketType.default) async def chessreset(self,",
"from discord.ext import commands POS = {'a': 0, 'b': 1, 'c': 2, 'd':",
"= [] w = 8 h = 8 turn = False def __init__(self,",
"= -1 if x1 < 0 or y1 < 0 or x1 >",
"commands POS = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4,",
"- 1)][y1 + sign] = 0 return else: return elif (y2 - y1)",
"1)][y1 + sign] = 0 return else: return elif (y2 - y1) *",
"> self.w or y2 > self.h: return if self.board[x1][y1] != color or self.board[x2][y2]",
"1: self.board[x1][y1] = 0 self.board[x2][y2] = color return def print_board(self): res = \"```\"",
"0: return if (y2 - y1) * sign == 2: if x2 -",
"\" _______________\\n\" res = res + \" a b c d e f",
"self.board[x1][y1] = 0 self.board[x2][y2] = color self.board[(x1 + 1)][y1 + sign] = 0",
"self.move(left, top, left_d, top_d) left = left_d top = top_d self.turn = not",
"% 2, 8, 2): self.board[x][y] = 1 msg = self.print_board() await ctx.send(msg) @commands.command(name=\"chess\")",
"x in range(y % 2, 8, 2): self.board[x][y] = 1 msg = self.print_board()",
"ctx.send(msg) def move(self, x1, y1, x2, y2): if self.turn: color = 2 opponent_color",
"opponent_color: self.board[x1][y1] = 0 self.board[x2][y2] = color self.board[(x1 - 1)][y1 + sign] =",
"-2: if self.board[(x1 - 1)][y1+sign] == opponent_color: self.board[x1][y1] = 0 self.board[x2][y2] = color",
"as e: await ctx.send(\"incorrect input\") return await ctx.send(str(left) + \" \" + str(top)",
"= color self.board[(x1 + 1)][y1 + sign] = 0 return else: return elif",
"for i in range(len(args)): try: left_d = POS[args[i][0]] top_d = 7-(int(args[i][1])-1) except KeyError",
"return if (y2 - y1) * sign == 2: if x2 - x1",
"y in range(0, 8): res = res + str(8-y) + \"| \" for",
"str(left_d) + \" \" + str(top_d)) self.move(left, top, left_d, top_d) left = left_d",
"self.turn msg = self.print_board() await ctx.send(msg) def move(self, x1, y1, x2, y2): if",
"= 2 opponent_color = 1 sign = 1 else: color = 1 opponent_color",
"'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7} class",
"opponent_color = 2 sign = -1 if x1 < 0 or y1 <",
"== 2: if x2 - x1 == 2: if self.board[(x1 + 1)][y1+sign] ==",
"= 1 opponent_color = 2 sign = -1 if x1 < 0 or",
"> self.w or y1 > self.h or x2 < 0 or y2 <",
"sign = 1 else: color = 1 opponent_color = 2 sign = -1",
"top = top_d self.turn = not self.turn msg = self.print_board() await ctx.send(msg) def",
"6, 'h': 7} class Chess(commands.Cog, name=\"chess test\"): board = [] w = 8",
"ctx.send(\"incorrect input\") return await ctx.send(str(left) + \" \" + str(top) + \" to",
"self.board[(x1 - 1)][y1 + sign] = 0 return else: return elif (y2 -",
"self.turn: color = 2 opponent_color = 1 sign = 1 else: color =",
"self.board[(x1 - 1)][y1+sign] == opponent_color: self.board[x1][y1] = 0 self.board[x2][y2] = color self.board[(x1 -",
"% 2, 8, 2): self.board[x][y] = 2 for y in range(6, 8): for",
"for x in range(self.w)] for y in range(self.h)] for y in range(0, 2):",
"self.board[x1][y1] != color or self.board[x2][y2] != 0: return if (y2 - y1) *",
"5, commands.BucketType.default) async def chessreset(self, ctx): self.board = [[0 for x in range(self.w)]",
"\" res += \"\\n\" res = res + \" _______________\\n\" res = res",
"left_d top = top_d self.turn = not self.turn msg = self.print_board() await ctx.send(msg)",
"in range(self.h)] for y in range(0, 2): for x in range(y % 2,",
"y in range(self.h)] for y in range(0, 2): for x in range(y %",
"color = 2 opponent_color = 1 sign = 1 else: color = 1",
"h = 8 turn = False def __init__(self, bot): self.bot = bot @commands.command(name=\"chessreset\")",
"\" + str(top_d)) self.move(left, top, left_d, top_d) left = left_d top = top_d",
"def chessreset(self, ctx): self.board = [[0 for x in range(self.w)] for y in",
"0 self.board[x2][y2] = color self.board[(x1 + 1)][y1 + sign] = 0 return else:",
"_______________\\n\" res = res + \" a b c d e f g",
"+ sign] = 0 return else: return elif x2 - x1 == -2:",
"res + str(8-y) + \"| \" for x in range(0, 8): res =",
"KeyError as e: await ctx.send(\"incorrect input\") return await ctx.send(str(left) + \" \" +",
"await ctx.send(msg) def move(self, x1, y1, x2, y2): if self.turn: color = 2",
"!= color or self.board[x2][y2] != 0: return if (y2 - y1) * sign",
"-1 if x1 < 0 or y1 < 0 or x1 > self.w",
"res += \"\\n\" res = res + \" _______________\\n\" res = res +",
"top_d) left = left_d top = top_d self.turn = not self.turn msg =",
"self.board[x1][y1] = 0 self.board[x2][y2] = color return def print_board(self): res = \"```\" for",
"KeyError as e: await ctx.send(\"incorrect input\") return for i in range(len(args)): try: left_d",
"e: await ctx.send(\"incorrect input\") return for i in range(len(args)): try: left_d = POS[args[i][0]]",
"@commands.cooldown(1, 5, commands.BucketType.default) async def chessreset(self, ctx): self.board = [[0 for x in",
"x1, y1, x2, y2): if self.turn: color = 2 opponent_color = 1 sign",
"color return def print_board(self): res = \"```\" for y in range(0, 8): res",
"self.board[x][y] = 1 msg = self.print_board() await ctx.send(msg) @commands.command(name=\"chess\") @commands.cooldown(1, 5, commands.BucketType.default) async",
"color self.board[(x1 - 1)][y1 + sign] = 0 return else: return elif (y2",
"await ctx.send(\"incorrect input\") return for i in range(len(args)): try: left_d = POS[args[i][0]] top_d",
"ctx): self.board = [[0 for x in range(self.w)] for y in range(self.h)] for",
"x1 == -2: if self.board[(x1 - 1)][y1+sign] == opponent_color: self.board[x1][y1] = 0 self.board[x2][y2]",
"or y2 > self.h: return if self.board[x1][y1] != color or self.board[x2][y2] != 0:",
"range(self.w)] for y in range(self.h)] for y in range(0, 2): for x in",
"*args): try: left = POS[arg1[0]] top = 7 - (int(arg1[1]) - 1) except",
"+ sign] = 0 return else: return elif (y2 - y1) * sign",
"__init__(self, bot): self.bot = bot @commands.command(name=\"chessreset\") @commands.cooldown(1, 5, commands.BucketType.default) async def chessreset(self, ctx):",
"color self.board[(x1 + 1)][y1 + sign] = 0 return else: return elif x2",
"left = POS[arg1[0]] top = 7 - (int(arg1[1]) - 1) except KeyError as",
"2 sign = -1 if x1 < 0 or y1 < 0 or",
"await ctx.send(msg) @commands.command(name=\"chess\") @commands.cooldown(1, 5, commands.BucketType.default) async def chess(self, ctx, arg1, *args): try:",
"res = res + \" _______________\\n\" res = res + \" a b",
"= 2 for y in range(6, 8): for x in range(y % 2,",
"= POS[arg1[0]] top = 7 - (int(arg1[1]) - 1) except KeyError as e:",
"def print_board(self): res = \"```\" for y in range(0, 8): res = res",
"except KeyError as e: await ctx.send(\"incorrect input\") return for i in range(len(args)): try:",
"in range(0, 8): res = res + str(8-y) + \"| \" for x",
"top_d self.turn = not self.turn msg = self.print_board() await ctx.send(msg) def move(self, x1,",
"\" + str(left_d) + \" \" + str(top_d)) self.move(left, top, left_d, top_d) left",
"> self.h or x2 < 0 or y2 < 0 or x2 >",
"2): for x in range(y % 2, 8, 2): self.board[x][y] = 2 for",
"= 8 turn = False def __init__(self, bot): self.bot = bot @commands.command(name=\"chessreset\") @commands.cooldown(1,",
"\" \" res += \"\\n\" res = res + \" _______________\\n\" res =",
"res = res + \" a b c d e f g h\\n\"",
"\" \" + str(top_d)) self.move(left, top, left_d, top_d) left = left_d top =",
"x2 - x1 == -2: if self.board[(x1 - 1)][y1+sign] == opponent_color: self.board[x1][y1] =",
"self.w or y1 > self.h or x2 < 0 or y2 < 0",
"\"| \" for x in range(0, 8): res = res + str(self.board[x][y]) +",
"8, 2): self.board[x][y] = 1 msg = self.print_board() await ctx.send(msg) @commands.command(name=\"chess\") @commands.cooldown(1, 5,",
"input\") return await ctx.send(str(left) + \" \" + str(top) + \" to \"",
"return else: return elif (y2 - y1) * sign == 1: self.board[x1][y1] =",
"arg1, *args): try: left = POS[arg1[0]] top = 7 - (int(arg1[1]) - 1)",
"= 0 self.board[x2][y2] = color self.board[(x1 - 1)][y1 + sign] = 0 return",
"== 2: if self.board[(x1 + 1)][y1+sign] == opponent_color: self.board[x1][y1] = 0 self.board[x2][y2] =",
"str(8-y) + \"| \" for x in range(0, 8): res = res +",
"try: left = POS[arg1[0]] top = 7 - (int(arg1[1]) - 1) except KeyError",
"or x2 < 0 or y2 < 0 or x2 > self.w or",
"self.board = [[0 for x in range(self.w)] for y in range(self.h)] for y",
"sign] = 0 return else: return elif (y2 - y1) * sign ==",
"sign == 1: self.board[x1][y1] = 0 self.board[x2][y2] = color return def print_board(self): res",
"x1 < 0 or y1 < 0 or x1 > self.w or y1",
"res + \" a b c d e f g h\\n\" res +=",
"d e f g h\\n\" res += \"```\" return res def setup(bot): bot.add_cog(Chess(bot))",
"bot @commands.command(name=\"chessreset\") @commands.cooldown(1, 5, commands.BucketType.default) async def chessreset(self, ctx): self.board = [[0 for",
"sign = -1 if x1 < 0 or y1 < 0 or x1",
"self.board[x][y] = 2 for y in range(6, 8): for x in range(y %",
"chessreset(self, ctx): self.board = [[0 for x in range(self.w)] for y in range(self.h)]",
"if self.board[x1][y1] != color or self.board[x2][y2] != 0: return if (y2 - y1)",
"== opponent_color: self.board[x1][y1] = 0 self.board[x2][y2] = color self.board[(x1 - 1)][y1 + sign]",
"commands.BucketType.default) async def chessreset(self, ctx): self.board = [[0 for x in range(self.w)] for",
"= res + \" a b c d e f g h\\n\" res",
"self.print_board() await ctx.send(msg) def move(self, x1, y1, x2, y2): if self.turn: color =",
"y2): if self.turn: color = 2 opponent_color = 1 sign = 1 else:",
"* sign == 2: if x2 - x1 == 2: if self.board[(x1 +",
"print_board(self): res = \"```\" for y in range(0, 8): res = res +",
"2: if self.board[(x1 + 1)][y1+sign] == opponent_color: self.board[x1][y1] = 0 self.board[x2][y2] = color",
"def move(self, x1, y1, x2, y2): if self.turn: color = 2 opponent_color =",
"for y in range(0, 2): for x in range(y % 2, 8, 2):",
"self.board[(x1 + 1)][y1 + sign] = 0 return else: return elif x2 -",
"'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h':",
"+ \" \" + str(top) + \" to \" + str(left_d) + \"",
"+ \" _______________\\n\" res = res + \" a b c d e",
"= color return def print_board(self): res = \"```\" for y in range(0, 8):",
"+ \"| \" for x in range(0, 8): res = res + str(self.board[x][y])",
"+ \" a b c d e f g h\\n\" res += \"```\"",
"e: await ctx.send(\"incorrect input\") return await ctx.send(str(left) + \" \" + str(top) +",
"'e': 4, 'f': 5, 'g': 6, 'h': 7} class Chess(commands.Cog, name=\"chess test\"): board",
"not self.turn msg = self.print_board() await ctx.send(msg) def move(self, x1, y1, x2, y2):",
"= [[0 for x in range(self.w)] for y in range(self.h)] for y in",
"= 1 else: color = 1 opponent_color = 2 sign = -1 if",
"2): self.board[x][y] = 2 for y in range(6, 8): for x in range(y",
"@commands.cooldown(1, 5, commands.BucketType.default) async def chess(self, ctx, arg1, *args): try: left = POS[arg1[0]]",
"\" + str(top) + \" to \" + str(left_d) + \" \" +",
"if self.turn: color = 2 opponent_color = 1 sign = 1 else: color",
"return def print_board(self): res = \"```\" for y in range(0, 8): res =",
"self.board[x2][y2] = color return def print_board(self): res = \"```\" for y in range(0,",
"+ \" to \" + str(left_d) + \" \" + str(top_d)) self.move(left, top,",
"y1) * sign == 1: self.board[x1][y1] = 0 self.board[x2][y2] = color return def",
"POS[arg1[0]] top = 7 - (int(arg1[1]) - 1) except KeyError as e: await",
"- (int(arg1[1]) - 1) except KeyError as e: await ctx.send(\"incorrect input\") return for",
"2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7} class Chess(commands.Cog,",
"or x1 > self.w or y1 > self.h or x2 < 0 or",
"return if self.board[x1][y1] != color or self.board[x2][y2] != 0: return if (y2 -",
"except KeyError as e: await ctx.send(\"incorrect input\") return await ctx.send(str(left) + \" \"",
"+ str(8-y) + \"| \" for x in range(0, 8): res = res",
"+ \" \" res += \"\\n\" res = res + \" _______________\\n\" res",
"name=\"chess test\"): board = [] w = 8 h = 8 turn =",
"self.bot = bot @commands.command(name=\"chessreset\") @commands.cooldown(1, 5, commands.BucketType.default) async def chessreset(self, ctx): self.board =",
"color = 1 opponent_color = 2 sign = -1 if x1 < 0",
"range(0, 8): res = res + str(8-y) + \"| \" for x in",
"= bot @commands.command(name=\"chessreset\") @commands.cooldown(1, 5, commands.BucketType.default) async def chessreset(self, ctx): self.board = [[0",
"< 0 or y1 < 0 or x1 > self.w or y1 >",
"= 8 h = 8 turn = False def __init__(self, bot): self.bot =",
"x2 - x1 == 2: if self.board[(x1 + 1)][y1+sign] == opponent_color: self.board[x1][y1] =",
"2 opponent_color = 1 sign = 1 else: color = 1 opponent_color =",
"y1, x2, y2): if self.turn: color = 2 opponent_color = 1 sign =",
"c d e f g h\\n\" res += \"```\" return res def setup(bot):",
"self.h: return if self.board[x1][y1] != color or self.board[x2][y2] != 0: return if (y2",
"+ \" \" + str(top_d)) self.move(left, top, left_d, top_d) left = left_d top",
"2: if x2 - x1 == 2: if self.board[(x1 + 1)][y1+sign] == opponent_color:",
"POS = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f':",
"color or self.board[x2][y2] != 0: return if (y2 - y1) * sign ==",
"= 0 return else: return elif (y2 - y1) * sign == 1:",
"0 self.board[x2][y2] = color return def print_board(self): res = \"```\" for y in",
"= 7 - (int(arg1[1]) - 1) except KeyError as e: await ctx.send(\"incorrect input\")",
"\" \" + str(top) + \" to \" + str(left_d) + \" \"",
"0 return else: return elif x2 - x1 == -2: if self.board[(x1 -",
"x in range(0, 8): res = res + str(self.board[x][y]) + \" \" res",
"False def __init__(self, bot): self.bot = bot @commands.command(name=\"chessreset\") @commands.cooldown(1, 5, commands.BucketType.default) async def",
"8): res = res + str(self.board[x][y]) + \" \" res += \"\\n\" res",
"x2 < 0 or y2 < 0 or x2 > self.w or y2",
"\"```\" for y in range(0, 8): res = res + str(8-y) + \"|",
"7-(int(args[i][1])-1) except KeyError as e: await ctx.send(\"incorrect input\") return await ctx.send(str(left) + \"",
"- 1)][y1+sign] == opponent_color: self.board[x1][y1] = 0 self.board[x2][y2] = color self.board[(x1 - 1)][y1",
"test\"): board = [] w = 8 h = 8 turn = False",
"= 0 self.board[x2][y2] = color return def print_board(self): res = \"```\" for y",
"8 turn = False def __init__(self, bot): self.bot = bot @commands.command(name=\"chessreset\") @commands.cooldown(1, 5,",
"+ 1)][y1+sign] == opponent_color: self.board[x1][y1] = 0 self.board[x2][y2] = color self.board[(x1 + 1)][y1",
"+ str(self.board[x][y]) + \" \" res += \"\\n\" res = res + \"",
"y2 > self.h: return if self.board[x1][y1] != color or self.board[x2][y2] != 0: return",
"in range(self.w)] for y in range(self.h)] for y in range(0, 2): for x",
"msg = self.print_board() await ctx.send(msg) def move(self, x1, y1, x2, y2): if self.turn:",
"await ctx.send(str(left) + \" \" + str(top) + \" to \" + str(left_d)",
"< 0 or y2 < 0 or x2 > self.w or y2 >",
"return elif (y2 - y1) * sign == 1: self.board[x1][y1] = 0 self.board[x2][y2]",
"= 0 return else: return elif x2 - x1 == -2: if self.board[(x1",
"bot): self.bot = bot @commands.command(name=\"chessreset\") @commands.cooldown(1, 5, commands.BucketType.default) async def chessreset(self, ctx): self.board",
"x2 > self.w or y2 > self.h: return if self.board[x1][y1] != color or",
"x1 > self.w or y1 > self.h or x2 < 0 or y2",
"= left_d top = top_d self.turn = not self.turn msg = self.print_board() await",
"if x1 < 0 or y1 < 0 or x1 > self.w or",
"in range(0, 2): for x in range(y % 2, 8, 2): self.board[x][y] =",
"= \"```\" for y in range(0, 8): res = res + str(8-y) +",
"1 sign = 1 else: color = 1 opponent_color = 2 sign =",
"(int(arg1[1]) - 1) except KeyError as e: await ctx.send(\"incorrect input\") return for i",
"4, 'f': 5, 'g': 6, 'h': 7} class Chess(commands.Cog, name=\"chess test\"): board =",
"in range(0, 8): res = res + str(self.board[x][y]) + \" \" res +=",
"+ str(top) + \" to \" + str(left_d) + \" \" + str(top_d))",
"y1 > self.h or x2 < 0 or y2 < 0 or x2",
"2): self.board[x][y] = 1 msg = self.print_board() await ctx.send(msg) @commands.command(name=\"chess\") @commands.cooldown(1, 5, commands.BucketType.default)",
"ctx.send(\"incorrect input\") return for i in range(len(args)): try: left_d = POS[args[i][0]] top_d =",
"if x2 - x1 == 2: if self.board[(x1 + 1)][y1+sign] == opponent_color: self.board[x1][y1]",
"res + \" _______________\\n\" res = res + \" a b c d",
"3, 'e': 4, 'f': 5, 'g': 6, 'h': 7} class Chess(commands.Cog, name=\"chess test\"):",
"[[0 for x in range(self.w)] for y in range(self.h)] for y in range(0,",
"in range(y % 2, 8, 2): self.board[x][y] = 2 for y in range(6,",
"{'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g':",
"8): res = res + str(8-y) + \"| \" for x in range(0,",
"in range(6, 8): for x in range(y % 2, 8, 2): self.board[x][y] =",
"else: color = 1 opponent_color = 2 sign = -1 if x1 <",
"- y1) * sign == 1: self.board[x1][y1] = 0 self.board[x2][y2] = color return",
"if (y2 - y1) * sign == 2: if x2 - x1 ==",
"x2, y2): if self.turn: color = 2 opponent_color = 1 sign = 1",
"7} class Chess(commands.Cog, name=\"chess test\"): board = [] w = 8 h =",
"async def chessreset(self, ctx): self.board = [[0 for x in range(self.w)] for y",
"left_d, top_d) left = left_d top = top_d self.turn = not self.turn msg",
"i in range(len(args)): try: left_d = POS[args[i][0]] top_d = 7-(int(args[i][1])-1) except KeyError as",
"sign == 2: if x2 - x1 == 2: if self.board[(x1 + 1)][y1+sign]",
"== opponent_color: self.board[x1][y1] = 0 self.board[x2][y2] = color self.board[(x1 + 1)][y1 + sign]",
"as e: await ctx.send(\"incorrect input\") return for i in range(len(args)): try: left_d =",
"= False def __init__(self, bot): self.bot = bot @commands.command(name=\"chessreset\") @commands.cooldown(1, 5, commands.BucketType.default) async",
"top_d = 7-(int(args[i][1])-1) except KeyError as e: await ctx.send(\"incorrect input\") return await ctx.send(str(left)",
"= color self.board[(x1 - 1)][y1 + sign] = 0 return else: return elif",
"= self.print_board() await ctx.send(msg) @commands.command(name=\"chess\") @commands.cooldown(1, 5, commands.BucketType.default) async def chess(self, ctx, arg1,",
"< 0 or x1 > self.w or y1 > self.h or x2 <",
"top, left_d, top_d) left = left_d top = top_d self.turn = not self.turn",
"2, 8, 2): self.board[x][y] = 1 msg = self.print_board() await ctx.send(msg) @commands.command(name=\"chess\") @commands.cooldown(1,",
"opponent_color = 1 sign = 1 else: color = 1 opponent_color = 2",
"chess(self, ctx, arg1, *args): try: left = POS[arg1[0]] top = 7 - (int(arg1[1])",
"self.board[x2][y2] != 0: return if (y2 - y1) * sign == 2: if",
"\" to \" + str(left_d) + \" \" + str(top_d)) self.move(left, top, left_d,",
"self.board[(x1 + 1)][y1+sign] == opponent_color: self.board[x1][y1] = 0 self.board[x2][y2] = color self.board[(x1 +",
"for x in range(0, 8): res = res + str(self.board[x][y]) + \" \"",
"1)][y1+sign] == opponent_color: self.board[x1][y1] = 0 self.board[x2][y2] = color self.board[(x1 + 1)][y1 +",
"res = \"```\" for y in range(0, 8): res = res + str(8-y)",
"range(6, 8): for x in range(y % 2, 8, 2): self.board[x][y] = 1",
"- x1 == 2: if self.board[(x1 + 1)][y1+sign] == opponent_color: self.board[x1][y1] = 0",
"async def chess(self, ctx, arg1, *args): try: left = POS[arg1[0]] top = 7",
"str(top) + \" to \" + str(left_d) + \" \" + str(top_d)) self.move(left,",
"return else: return elif x2 - x1 == -2: if self.board[(x1 - 1)][y1+sign]",
"b c d e f g h\\n\" res += \"```\" return res def",
"0 or y1 < 0 or x1 > self.w or y1 > self.h",
"ctx.send(str(left) + \" \" + str(top) + \" to \" + str(left_d) +",
"x in range(y % 2, 8, 2): self.board[x][y] = 2 for y in",
"range(0, 8): res = res + str(self.board[x][y]) + \" \" res += \"\\n\"",
"res = res + str(self.board[x][y]) + \" \" res += \"\\n\" res =",
"= self.print_board() await ctx.send(msg) def move(self, x1, y1, x2, y2): if self.turn: color",
"turn = False def __init__(self, bot): self.bot = bot @commands.command(name=\"chessreset\") @commands.cooldown(1, 5, commands.BucketType.default)",
"\" a b c d e f g h\\n\" res += \"```\" return",
"@commands.command(name=\"chessreset\") @commands.cooldown(1, 5, commands.BucketType.default) async def chessreset(self, ctx): self.board = [[0 for x",
"= res + \" _______________\\n\" res = res + \" a b c",
"discord.ext import commands POS = {'a': 0, 'b': 1, 'c': 2, 'd': 3,",
"== 1: self.board[x1][y1] = 0 self.board[x2][y2] = color return def print_board(self): res =",
"= {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5,",
"in range(y % 2, 8, 2): self.board[x][y] = 1 msg = self.print_board() await",
"ctx.send(msg) @commands.command(name=\"chess\") @commands.cooldown(1, 5, commands.BucketType.default) async def chess(self, ctx, arg1, *args): try: left",
"0 self.board[x2][y2] = color self.board[(x1 - 1)][y1 + sign] = 0 return else:",
"\" for x in range(0, 8): res = res + str(self.board[x][y]) + \"",
"2 for y in range(6, 8): for x in range(y % 2, 8,",
"\"\\n\" res = res + \" _______________\\n\" res = res + \" a",
"1) except KeyError as e: await ctx.send(\"incorrect input\") return for i in range(len(args)):",
"x1 == 2: if self.board[(x1 + 1)][y1+sign] == opponent_color: self.board[x1][y1] = 0 self.board[x2][y2]",
"elif x2 - x1 == -2: if self.board[(x1 - 1)][y1+sign] == opponent_color: self.board[x1][y1]",
"range(len(args)): try: left_d = POS[args[i][0]] top_d = 7-(int(args[i][1])-1) except KeyError as e: await",
"= top_d self.turn = not self.turn msg = self.print_board() await ctx.send(msg) def move(self,",
"try: left_d = POS[args[i][0]] top_d = 7-(int(args[i][1])-1) except KeyError as e: await ctx.send(\"incorrect",
"def chess(self, ctx, arg1, *args): try: left = POS[arg1[0]] top = 7 -",
"x in range(self.w)] for y in range(self.h)] for y in range(0, 2): for",
"w = 8 h = 8 turn = False def __init__(self, bot): self.bot",
"or self.board[x2][y2] != 0: return if (y2 - y1) * sign == 2:",
"range(0, 2): for x in range(y % 2, 8, 2): self.board[x][y] = 2",
"return await ctx.send(str(left) + \" \" + str(top) + \" to \" +",
"'h': 7} class Chess(commands.Cog, name=\"chess test\"): board = [] w = 8 h",
"for y in range(0, 8): res = res + str(8-y) + \"| \"",
"5, 'g': 6, 'h': 7} class Chess(commands.Cog, name=\"chess test\"): board = [] w",
"ctx, arg1, *args): try: left = POS[arg1[0]] top = 7 - (int(arg1[1]) -",
"elif (y2 - y1) * sign == 1: self.board[x1][y1] = 0 self.board[x2][y2] =",
"res = res + str(8-y) + \"| \" for x in range(0, 8):",
"else: return elif x2 - x1 == -2: if self.board[(x1 - 1)][y1+sign] ==",
"Chess(commands.Cog, name=\"chess test\"): board = [] w = 8 h = 8 turn",
"self.print_board() await ctx.send(msg) @commands.command(name=\"chess\") @commands.cooldown(1, 5, commands.BucketType.default) async def chess(self, ctx, arg1, *args):",
"1 opponent_color = 2 sign = -1 if x1 < 0 or y1",
"- y1) * sign == 2: if x2 - x1 == 2: if",
"or y2 < 0 or x2 > self.w or y2 > self.h: return",
"for x in range(y % 2, 8, 2): self.board[x][y] = 2 for y",
"range(self.h)] for y in range(0, 2): for x in range(y % 2, 8,",
"left = left_d top = top_d self.turn = not self.turn msg = self.print_board()",
"for y in range(6, 8): for x in range(y % 2, 8, 2):",
"y in range(6, 8): for x in range(y % 2, 8, 2): self.board[x][y]"
] |
[
"assert '00' == eta_hms(0) assert '09' == eta_hms(9) assert '59' == eta_hms(59) assert",
"assert '0:00:09' == eta_hms(9, always_show_hours=True) assert '0:00:59' == eta_hms(59, always_show_hours=True) assert '0:01:00' ==",
"def test_always_show_hours_hours_leading_zero(): assert '00:00:00' == eta_hms(0, hours_leading_zero=True, always_show_hours=True) assert '00:00:09' == eta_hms(9, hours_leading_zero=True,",
"assert '1:00:01' == eta_hms(3601) assert '1:01:01' == eta_hms(3661) assert '167:59:59' == eta_hms(604799) assert",
"assert '168:00:01' == eta_hms(604801, always_show_hours=True) # The rest is mostly copy/pasted. ############################################ def",
"hours_leading_zero=True, always_show_minutes=True) assert '59:59' == eta_hms(3599, hours_leading_zero=True, always_show_minutes=True) assert '01:00:00' == eta_hms(3600, hours_leading_zero=True,",
"== eta_hms(60, always_show_hours=True) assert '0:01:01' == eta_hms(61, always_show_hours=True) assert '0:59:59' == eta_hms(3599, always_show_hours=True)",
"assert '1:00:00' == eta_hms(3600, always_show_minutes=True) assert '1:00:01' == eta_hms(3601, always_show_minutes=True) assert '1:01:01' ==",
"'59:59' == eta_hms(3599, hours_leading_zero=True, always_show_minutes=True) assert '01:00:00' == eta_hms(3600, hours_leading_zero=True, always_show_minutes=True) assert '01:00:01'",
"'1:00:01' == eta_hms(3601, always_show_minutes=True) assert '1:01:01' == eta_hms(3661, always_show_minutes=True) assert '167:59:59' == eta_hms(604799,",
"'01:01' == eta_hms(61, hours_leading_zero=True, always_show_minutes=True) assert '59:59' == eta_hms(3599, hours_leading_zero=True, always_show_minutes=True) assert '01:00:00'",
"assert '00:00' == eta_hms(0, always_show_minutes=True) assert '00:09' == eta_hms(9, always_show_minutes=True) assert '00:59' ==",
"always_show_hours=True) assert '0:00:59' == eta_hms(59, always_show_hours=True) assert '0:01:00' == eta_hms(60, always_show_hours=True) assert '0:01:01'",
"def test_hours_leading_zero(): assert '00' == eta_hms(0, hours_leading_zero=True) assert '09' == eta_hms(9, hours_leading_zero=True) assert",
"always_show_hours=True) assert '0:00:09' == eta_hms(9, always_show_hours=True) assert '0:00:59' == eta_hms(59, always_show_hours=True) assert '0:01:00'",
"'00' == eta_hms(0) assert '09' == eta_hms(9) assert '59' == eta_hms(59) assert '01:00'",
"hours_leading_zero=True) assert '59:59' == eta_hms(3599, hours_leading_zero=True) assert '01:00:00' == eta_hms(3600, hours_leading_zero=True) assert '01:00:01'",
"always_show_minutes=True) assert '168:00:00' == eta_hms(604800, always_show_minutes=True) assert '168:00:01' == eta_hms(604801, always_show_minutes=True) def test_always_show_hours():",
"eta_hms(604800, always_show_hours=True) assert '168:00:01' == eta_hms(604801, always_show_hours=True) # The rest is mostly copy/pasted.",
"eta_hms(3661, always_show_hours=True) assert '167:59:59' == eta_hms(604799, always_show_hours=True) assert '168:00:00' == eta_hms(604800, always_show_hours=True) assert",
"assert '59' == eta_hms(59) assert '01:00' == eta_hms(60) assert '01:01' == eta_hms(61) assert",
"assert '01:01:01' == eta_hms(3661, hours_leading_zero=True) assert '167:59:59' == eta_hms(604799, hours_leading_zero=True) assert '168:00:00' ==",
"== eta_hms(604800, hours_leading_zero=True, always_show_minutes=True) assert '168:00:01' == eta_hms(604801, hours_leading_zero=True, always_show_minutes=True) def test_always_show_hours_hours_leading_zero(): assert",
"== eta_hms(604801, hours_leading_zero=True, always_show_minutes=True) def test_always_show_hours_hours_leading_zero(): assert '00:00:00' == eta_hms(0, hours_leading_zero=True, always_show_hours=True) assert",
"== eta_hms(3599, always_show_minutes=True) assert '1:00:00' == eta_hms(3600, always_show_minutes=True) assert '1:00:01' == eta_hms(3601, always_show_minutes=True)",
"always_show_minutes=True) assert '167:59:59' == eta_hms(604799, always_show_minutes=True) assert '168:00:00' == eta_hms(604800, always_show_minutes=True) assert '168:00:01'",
"The rest is mostly copy/pasted. ############################################ def test_hours_leading_zero(): assert '00' == eta_hms(0, hours_leading_zero=True)",
"== eta_hms(3599, hours_leading_zero=True, always_show_minutes=True) assert '01:00:00' == eta_hms(3600, hours_leading_zero=True, always_show_minutes=True) assert '01:00:01' ==",
"== eta_hms(604799, always_show_minutes=True) assert '168:00:00' == eta_hms(604800, always_show_minutes=True) assert '168:00:01' == eta_hms(604801, always_show_minutes=True)",
"hours_leading_zero=True, always_show_minutes=True) assert '01:01' == eta_hms(61, hours_leading_zero=True, always_show_minutes=True) assert '59:59' == eta_hms(3599, hours_leading_zero=True,",
"assert '09' == eta_hms(9) assert '59' == eta_hms(59) assert '01:00' == eta_hms(60) assert",
"eta_hms(9, hours_leading_zero=True) assert '59' == eta_hms(59, hours_leading_zero=True) assert '01:00' == eta_hms(60, hours_leading_zero=True) assert",
"eta_hms(604799) assert '168:00:00' == eta_hms(604800) assert '168:00:01' == eta_hms(604801) def test_always_show_minutes(): assert '00:00'",
"== eta_hms(604801) def test_always_show_minutes(): assert '00:00' == eta_hms(0, always_show_minutes=True) assert '00:09' == eta_hms(9,",
"mostly copy/pasted. ############################################ def test_hours_leading_zero(): assert '00' == eta_hms(0, hours_leading_zero=True) assert '09' ==",
"== eta_hms(604800, always_show_minutes=True) assert '168:00:01' == eta_hms(604801, always_show_minutes=True) def test_always_show_hours(): assert '0:00:00' ==",
"assert '00:00' == eta_hms(0, hours_leading_zero=True, always_show_minutes=True) assert '00:09' == eta_hms(9, hours_leading_zero=True, always_show_minutes=True) assert",
"test_always_show_hours_hours_leading_zero(): assert '00:00:00' == eta_hms(0, hours_leading_zero=True, always_show_hours=True) assert '00:00:09' == eta_hms(9, hours_leading_zero=True, always_show_hours=True)",
"copy/pasted. ############################################ def test_hours_leading_zero(): assert '00' == eta_hms(0, hours_leading_zero=True) assert '09' == eta_hms(9,",
"eta_hms(604801, hours_leading_zero=True) def test_always_show_minutes_hours_leading_zero(): assert '00:00' == eta_hms(0, hours_leading_zero=True, always_show_minutes=True) assert '00:09' ==",
"always_show_minutes=True) assert '01:01' == eta_hms(61, always_show_minutes=True) assert '59:59' == eta_hms(3599, always_show_minutes=True) assert '1:00:00'",
"assert '01:01' == eta_hms(61, hours_leading_zero=True, always_show_minutes=True) assert '59:59' == eta_hms(3599, hours_leading_zero=True, always_show_minutes=True) assert",
"== eta_hms(3600, always_show_hours=True) assert '1:00:01' == eta_hms(3601, always_show_hours=True) assert '1:01:01' == eta_hms(3661, always_show_hours=True)",
"'0:00:00' == eta_hms(0, always_show_hours=True) assert '0:00:09' == eta_hms(9, always_show_hours=True) assert '0:00:59' == eta_hms(59,",
"eta_hms(59) assert '01:00' == eta_hms(60) assert '01:01' == eta_hms(61) assert '59:59' == eta_hms(3599)",
"'59:59' == eta_hms(3599, always_show_minutes=True) assert '1:00:00' == eta_hms(3600, always_show_minutes=True) assert '1:00:01' == eta_hms(3601,",
"== eta_hms(61, always_show_hours=True) assert '0:59:59' == eta_hms(3599, always_show_hours=True) assert '1:00:00' == eta_hms(3600, always_show_hours=True)",
"== eta_hms(604799, hours_leading_zero=True) assert '168:00:00' == eta_hms(604800, hours_leading_zero=True) assert '168:00:01' == eta_hms(604801, hours_leading_zero=True)",
"'168:00:01' == eta_hms(604801, hours_leading_zero=True) def test_always_show_minutes_hours_leading_zero(): assert '00:00' == eta_hms(0, hours_leading_zero=True, always_show_minutes=True) assert",
"== eta_hms(604799, always_show_hours=True) assert '168:00:00' == eta_hms(604800, always_show_hours=True) assert '168:00:01' == eta_hms(604801, always_show_hours=True)",
"assert '0:59:59' == eta_hms(3599, always_show_hours=True) assert '1:00:00' == eta_hms(3600, always_show_hours=True) assert '1:00:01' ==",
"assert '59:59' == eta_hms(3599, hours_leading_zero=True, always_show_minutes=True) assert '01:00:00' == eta_hms(3600, hours_leading_zero=True, always_show_minutes=True) assert",
"eta_hms(3600, always_show_minutes=True) assert '1:00:01' == eta_hms(3601, always_show_minutes=True) assert '1:01:01' == eta_hms(3661, always_show_minutes=True) assert",
"== eta_hms(3601, hours_leading_zero=True) assert '01:01:01' == eta_hms(3661, hours_leading_zero=True) assert '167:59:59' == eta_hms(604799, hours_leading_zero=True)",
"'00:59:59' == eta_hms(3599, hours_leading_zero=True, always_show_hours=True) assert '01:00:00' == eta_hms(3600, hours_leading_zero=True, always_show_hours=True) assert '01:00:01'",
"== eta_hms(61, always_show_minutes=True) assert '59:59' == eta_hms(3599, always_show_minutes=True) assert '1:00:00' == eta_hms(3600, always_show_minutes=True)",
"eta_hms(59, hours_leading_zero=True, always_show_hours=True) assert '00:01:00' == eta_hms(60, hours_leading_zero=True, always_show_hours=True) assert '00:01:01' == eta_hms(61,",
"always_show_minutes=True) assert '00:59' == eta_hms(59, hours_leading_zero=True, always_show_minutes=True) assert '01:00' == eta_hms(60, hours_leading_zero=True, always_show_minutes=True)",
"assert '01:00:00' == eta_hms(3600, hours_leading_zero=True, always_show_hours=True) assert '01:00:01' == eta_hms(3601, hours_leading_zero=True, always_show_hours=True) assert",
"hours_leading_zero=True, always_show_minutes=True) assert '00:09' == eta_hms(9, hours_leading_zero=True, always_show_minutes=True) assert '00:59' == eta_hms(59, hours_leading_zero=True,",
"always_show_hours=True) assert '1:00:00' == eta_hms(3600, always_show_hours=True) assert '1:00:01' == eta_hms(3601, always_show_hours=True) assert '1:01:01'",
"'01:00:00' == eta_hms(3600, hours_leading_zero=True, always_show_minutes=True) assert '01:00:01' == eta_hms(3601, hours_leading_zero=True, always_show_minutes=True) assert '01:01:01'",
"def test_always_show_minutes(): assert '00:00' == eta_hms(0, always_show_minutes=True) assert '00:09' == eta_hms(9, always_show_minutes=True) assert",
"assert '168:00:00' == eta_hms(604800, always_show_minutes=True) assert '168:00:01' == eta_hms(604801, always_show_minutes=True) def test_always_show_hours(): assert",
"always_show_hours=True) assert '01:01:01' == eta_hms(3661, hours_leading_zero=True, always_show_hours=True) assert '167:59:59' == eta_hms(604799, hours_leading_zero=True, always_show_hours=True)",
"eta_hms(61, always_show_hours=True) assert '0:59:59' == eta_hms(3599, always_show_hours=True) assert '1:00:00' == eta_hms(3600, always_show_hours=True) assert",
"assert '0:01:00' == eta_hms(60, always_show_hours=True) assert '0:01:01' == eta_hms(61, always_show_hours=True) assert '0:59:59' ==",
"'01:00:00' == eta_hms(3600, hours_leading_zero=True, always_show_hours=True) assert '01:00:01' == eta_hms(3601, hours_leading_zero=True, always_show_hours=True) assert '01:01:01'",
"eta_hms(61, hours_leading_zero=True, always_show_hours=True) assert '00:59:59' == eta_hms(3599, hours_leading_zero=True, always_show_hours=True) assert '01:00:00' == eta_hms(3600,",
"'01:00' == eta_hms(60) assert '01:01' == eta_hms(61) assert '59:59' == eta_hms(3599) assert '1:00:00'",
"'09' == eta_hms(9, hours_leading_zero=True) assert '59' == eta_hms(59, hours_leading_zero=True) assert '01:00' == eta_hms(60,",
"== eta_hms(61, hours_leading_zero=True) assert '59:59' == eta_hms(3599, hours_leading_zero=True) assert '01:00:00' == eta_hms(3600, hours_leading_zero=True)",
"assert '0:00:00' == eta_hms(0, always_show_hours=True) assert '0:00:09' == eta_hms(9, always_show_hours=True) assert '0:00:59' ==",
"always_show_minutes=True) assert '01:00' == eta_hms(60, always_show_minutes=True) assert '01:01' == eta_hms(61, always_show_minutes=True) assert '59:59'",
"== eta_hms(59, always_show_minutes=True) assert '01:00' == eta_hms(60, always_show_minutes=True) assert '01:01' == eta_hms(61, always_show_minutes=True)",
"== eta_hms(3661, hours_leading_zero=True, always_show_minutes=True) assert '167:59:59' == eta_hms(604799, hours_leading_zero=True, always_show_minutes=True) assert '168:00:00' ==",
"assert '168:00:00' == eta_hms(604800, hours_leading_zero=True, always_show_minutes=True) assert '168:00:01' == eta_hms(604801, hours_leading_zero=True, always_show_minutes=True) def",
"== eta_hms(3599, always_show_hours=True) assert '1:00:00' == eta_hms(3600, always_show_hours=True) assert '1:00:01' == eta_hms(3601, always_show_hours=True)",
"== eta_hms(3601, always_show_hours=True) assert '1:01:01' == eta_hms(3661, always_show_hours=True) assert '167:59:59' == eta_hms(604799, always_show_hours=True)",
"############################################ def test_hours_leading_zero(): assert '00' == eta_hms(0, hours_leading_zero=True) assert '09' == eta_hms(9, hours_leading_zero=True)",
"== eta_hms(3661, hours_leading_zero=True) assert '167:59:59' == eta_hms(604799, hours_leading_zero=True) assert '168:00:00' == eta_hms(604800, hours_leading_zero=True)",
"assert '00:00:09' == eta_hms(9, hours_leading_zero=True, always_show_hours=True) assert '00:00:59' == eta_hms(59, hours_leading_zero=True, always_show_hours=True) assert",
"assert '1:00:01' == eta_hms(3601, always_show_hours=True) assert '1:01:01' == eta_hms(3661, always_show_hours=True) assert '167:59:59' ==",
"always_show_hours=True) assert '1:01:01' == eta_hms(3661, always_show_hours=True) assert '167:59:59' == eta_hms(604799, always_show_hours=True) assert '168:00:00'",
"eta_hms(0, hours_leading_zero=True, always_show_minutes=True) assert '00:09' == eta_hms(9, hours_leading_zero=True, always_show_minutes=True) assert '00:59' == eta_hms(59,",
"'168:00:00' == eta_hms(604800, hours_leading_zero=True, always_show_minutes=True) assert '168:00:01' == eta_hms(604801, hours_leading_zero=True, always_show_minutes=True) def test_always_show_hours_hours_leading_zero():",
"== eta_hms(604799) assert '168:00:00' == eta_hms(604800) assert '168:00:01' == eta_hms(604801) def test_always_show_minutes(): assert",
"'00:00' == eta_hms(0, always_show_minutes=True) assert '00:09' == eta_hms(9, always_show_minutes=True) assert '00:59' == eta_hms(59,",
"assert '1:01:01' == eta_hms(3661, always_show_minutes=True) assert '167:59:59' == eta_hms(604799, always_show_minutes=True) assert '168:00:00' ==",
"== eta_hms(604801, always_show_hours=True) # The rest is mostly copy/pasted. ############################################ def test_hours_leading_zero(): assert",
"hours_leading_zero=True) assert '01:01:01' == eta_hms(3661, hours_leading_zero=True) assert '167:59:59' == eta_hms(604799, hours_leading_zero=True) assert '168:00:00'",
"== eta_hms(0, hours_leading_zero=True) assert '09' == eta_hms(9, hours_leading_zero=True) assert '59' == eta_hms(59, hours_leading_zero=True)",
"'167:59:59' == eta_hms(604799, hours_leading_zero=True, always_show_minutes=True) assert '168:00:00' == eta_hms(604800, hours_leading_zero=True, always_show_minutes=True) assert '168:00:01'",
"== eta_hms(60, hours_leading_zero=True, always_show_minutes=True) assert '01:01' == eta_hms(61, hours_leading_zero=True, always_show_minutes=True) assert '59:59' ==",
"eta_hms(9, always_show_hours=True) assert '0:00:59' == eta_hms(59, always_show_hours=True) assert '0:01:00' == eta_hms(60, always_show_hours=True) assert",
"== eta_hms(3600, always_show_minutes=True) assert '1:00:01' == eta_hms(3601, always_show_minutes=True) assert '1:01:01' == eta_hms(3661, always_show_minutes=True)",
"eta_hms(604801, always_show_minutes=True) def test_always_show_hours(): assert '0:00:00' == eta_hms(0, always_show_hours=True) assert '0:00:09' == eta_hms(9,",
"== eta_hms(59, always_show_hours=True) assert '0:01:00' == eta_hms(60, always_show_hours=True) assert '0:01:01' == eta_hms(61, always_show_hours=True)",
"'00:59' == eta_hms(59, always_show_minutes=True) assert '01:00' == eta_hms(60, always_show_minutes=True) assert '01:01' == eta_hms(61,",
"assert '167:59:59' == eta_hms(604799, always_show_hours=True) assert '168:00:00' == eta_hms(604800, always_show_hours=True) assert '168:00:01' ==",
"eta_hms(9, hours_leading_zero=True, always_show_minutes=True) assert '00:59' == eta_hms(59, hours_leading_zero=True, always_show_minutes=True) assert '01:00' == eta_hms(60,",
"'00:00' == eta_hms(0, hours_leading_zero=True, always_show_minutes=True) assert '00:09' == eta_hms(9, hours_leading_zero=True, always_show_minutes=True) assert '00:59'",
"always_show_hours=True) assert '1:00:01' == eta_hms(3601, always_show_hours=True) assert '1:01:01' == eta_hms(3661, always_show_hours=True) assert '167:59:59'",
"eta_hms(3661, hours_leading_zero=True) assert '167:59:59' == eta_hms(604799, hours_leading_zero=True) assert '168:00:00' == eta_hms(604800, hours_leading_zero=True) assert",
"hours_leading_zero=True) assert '01:01' == eta_hms(61, hours_leading_zero=True) assert '59:59' == eta_hms(3599, hours_leading_zero=True) assert '01:00:00'",
"assert '1:00:00' == eta_hms(3600, always_show_hours=True) assert '1:00:01' == eta_hms(3601, always_show_hours=True) assert '1:01:01' ==",
"eta_hms(3599, hours_leading_zero=True) assert '01:00:00' == eta_hms(3600, hours_leading_zero=True) assert '01:00:01' == eta_hms(3601, hours_leading_zero=True) assert",
"assert '168:00:00' == eta_hms(604800, always_show_hours=True) assert '168:00:01' == eta_hms(604801, always_show_hours=True) # The rest",
"is mostly copy/pasted. ############################################ def test_hours_leading_zero(): assert '00' == eta_hms(0, hours_leading_zero=True) assert '09'",
"'167:59:59' == eta_hms(604799, hours_leading_zero=True, always_show_hours=True) assert '168:00:00' == eta_hms(604800, hours_leading_zero=True, always_show_hours=True) assert '168:00:01'",
"eta_hms(9) assert '59' == eta_hms(59) assert '01:00' == eta_hms(60) assert '01:01' == eta_hms(61)",
"hours_leading_zero=True) def test_always_show_minutes_hours_leading_zero(): assert '00:00' == eta_hms(0, hours_leading_zero=True, always_show_minutes=True) assert '00:09' == eta_hms(9,",
"assert '01:00:01' == eta_hms(3601, hours_leading_zero=True, always_show_hours=True) assert '01:01:01' == eta_hms(3661, hours_leading_zero=True, always_show_hours=True) assert",
"'00:01:00' == eta_hms(60, hours_leading_zero=True, always_show_hours=True) assert '00:01:01' == eta_hms(61, hours_leading_zero=True, always_show_hours=True) assert '00:59:59'",
"assert '09' == eta_hms(9, hours_leading_zero=True) assert '59' == eta_hms(59, hours_leading_zero=True) assert '01:00' ==",
"hours_leading_zero=True, always_show_minutes=True) assert '168:00:00' == eta_hms(604800, hours_leading_zero=True, always_show_minutes=True) assert '168:00:01' == eta_hms(604801, hours_leading_zero=True,",
"eta_hms(3599, hours_leading_zero=True, always_show_hours=True) assert '01:00:00' == eta_hms(3600, hours_leading_zero=True, always_show_hours=True) assert '01:00:01' == eta_hms(3601,",
"test_always_show_minutes_hours_leading_zero(): assert '00:00' == eta_hms(0, hours_leading_zero=True, always_show_minutes=True) assert '00:09' == eta_hms(9, hours_leading_zero=True, always_show_minutes=True)",
"assert '00:00:59' == eta_hms(59, hours_leading_zero=True, always_show_hours=True) assert '00:01:00' == eta_hms(60, hours_leading_zero=True, always_show_hours=True) assert",
"always_show_hours=True) # The rest is mostly copy/pasted. ############################################ def test_hours_leading_zero(): assert '00' ==",
"eta_hms(604801, always_show_hours=True) # The rest is mostly copy/pasted. ############################################ def test_hours_leading_zero(): assert '00'",
"always_show_hours=True) assert '168:00:00' == eta_hms(604800, hours_leading_zero=True, always_show_hours=True) assert '168:00:01' == eta_hms(604801, hours_leading_zero=True, always_show_hours=True)",
"'0:01:01' == eta_hms(61, always_show_hours=True) assert '0:59:59' == eta_hms(3599, always_show_hours=True) assert '1:00:00' == eta_hms(3600,",
"eta_hms(3601, always_show_minutes=True) assert '1:01:01' == eta_hms(3661, always_show_minutes=True) assert '167:59:59' == eta_hms(604799, always_show_minutes=True) assert",
"== eta_hms(60, always_show_minutes=True) assert '01:01' == eta_hms(61, always_show_minutes=True) assert '59:59' == eta_hms(3599, always_show_minutes=True)",
"hours_leading_zero=True) assert '168:00:01' == eta_hms(604801, hours_leading_zero=True) def test_always_show_minutes_hours_leading_zero(): assert '00:00' == eta_hms(0, hours_leading_zero=True,",
"'00:09' == eta_hms(9, always_show_minutes=True) assert '00:59' == eta_hms(59, always_show_minutes=True) assert '01:00' == eta_hms(60,",
"'00:00:59' == eta_hms(59, hours_leading_zero=True, always_show_hours=True) assert '00:01:00' == eta_hms(60, hours_leading_zero=True, always_show_hours=True) assert '00:01:01'",
"eta_hms(3601, always_show_hours=True) assert '1:01:01' == eta_hms(3661, always_show_hours=True) assert '167:59:59' == eta_hms(604799, always_show_hours=True) assert",
"== eta_hms(604801, always_show_minutes=True) def test_always_show_hours(): assert '0:00:00' == eta_hms(0, always_show_hours=True) assert '0:00:09' ==",
"hours_leading_zero=True) assert '59' == eta_hms(59, hours_leading_zero=True) assert '01:00' == eta_hms(60, hours_leading_zero=True) assert '01:01'",
"hours_leading_zero=True, always_show_hours=True) assert '00:00:59' == eta_hms(59, hours_leading_zero=True, always_show_hours=True) assert '00:01:00' == eta_hms(60, hours_leading_zero=True,",
"# The rest is mostly copy/pasted. ############################################ def test_hours_leading_zero(): assert '00' == eta_hms(0,",
"always_show_minutes=True) assert '168:00:01' == eta_hms(604801, always_show_minutes=True) def test_always_show_hours(): assert '0:00:00' == eta_hms(0, always_show_hours=True)",
"eta_hms(61, hours_leading_zero=True) assert '59:59' == eta_hms(3599, hours_leading_zero=True) assert '01:00:00' == eta_hms(3600, hours_leading_zero=True) assert",
"eta_hms(3600, always_show_hours=True) assert '1:00:01' == eta_hms(3601, always_show_hours=True) assert '1:01:01' == eta_hms(3661, always_show_hours=True) assert",
"eta_hms(0, hours_leading_zero=True) assert '09' == eta_hms(9, hours_leading_zero=True) assert '59' == eta_hms(59, hours_leading_zero=True) assert",
"eta_hms(3600, hours_leading_zero=True) assert '01:00:01' == eta_hms(3601, hours_leading_zero=True) assert '01:01:01' == eta_hms(3661, hours_leading_zero=True) assert",
"== eta_hms(60, hours_leading_zero=True, always_show_hours=True) assert '00:01:01' == eta_hms(61, hours_leading_zero=True, always_show_hours=True) assert '00:59:59' ==",
"hours_leading_zero=True, always_show_hours=True) assert '01:01:01' == eta_hms(3661, hours_leading_zero=True, always_show_hours=True) assert '167:59:59' == eta_hms(604799, hours_leading_zero=True,",
"== eta_hms(3600, hours_leading_zero=True, always_show_minutes=True) assert '01:00:01' == eta_hms(3601, hours_leading_zero=True, always_show_minutes=True) assert '01:01:01' ==",
"== eta_hms(0) assert '09' == eta_hms(9) assert '59' == eta_hms(59) assert '01:00' ==",
"'01:00' == eta_hms(60, hours_leading_zero=True, always_show_minutes=True) assert '01:01' == eta_hms(61, hours_leading_zero=True, always_show_minutes=True) assert '59:59'",
"== eta_hms(604799, hours_leading_zero=True, always_show_hours=True) assert '168:00:00' == eta_hms(604800, hours_leading_zero=True, always_show_hours=True) assert '168:00:01' ==",
"== eta_hms(60) assert '01:01' == eta_hms(61) assert '59:59' == eta_hms(3599) assert '1:00:00' ==",
"always_show_minutes=True) def test_always_show_hours(): assert '0:00:00' == eta_hms(0, always_show_hours=True) assert '0:00:09' == eta_hms(9, always_show_hours=True)",
"'1:00:01' == eta_hms(3601, always_show_hours=True) assert '1:01:01' == eta_hms(3661, always_show_hours=True) assert '167:59:59' == eta_hms(604799,",
"assert '01:01' == eta_hms(61, hours_leading_zero=True) assert '59:59' == eta_hms(3599, hours_leading_zero=True) assert '01:00:00' ==",
"eta_hms(0) assert '09' == eta_hms(9) assert '59' == eta_hms(59) assert '01:00' == eta_hms(60)",
"eta_hms(604800, hours_leading_zero=True) assert '168:00:01' == eta_hms(604801, hours_leading_zero=True) def test_always_show_minutes_hours_leading_zero(): assert '00:00' == eta_hms(0,",
"def test_always_show_minutes_hours_leading_zero(): assert '00:00' == eta_hms(0, hours_leading_zero=True, always_show_minutes=True) assert '00:09' == eta_hms(9, hours_leading_zero=True,",
"eta_hms(3599, hours_leading_zero=True, always_show_minutes=True) assert '01:00:00' == eta_hms(3600, hours_leading_zero=True, always_show_minutes=True) assert '01:00:01' == eta_hms(3601,",
"== eta_hms(0, always_show_minutes=True) assert '00:09' == eta_hms(9, always_show_minutes=True) assert '00:59' == eta_hms(59, always_show_minutes=True)",
"assert '168:00:01' == eta_hms(604801) def test_always_show_minutes(): assert '00:00' == eta_hms(0, always_show_minutes=True) assert '00:09'",
"hours_leading_zero=True, always_show_hours=True) assert '168:00:00' == eta_hms(604800, hours_leading_zero=True, always_show_hours=True) assert '168:00:01' == eta_hms(604801, hours_leading_zero=True,",
"eta_hms(3661, always_show_minutes=True) assert '167:59:59' == eta_hms(604799, always_show_minutes=True) assert '168:00:00' == eta_hms(604800, always_show_minutes=True) assert",
"'01:00:01' == eta_hms(3601, hours_leading_zero=True, always_show_hours=True) assert '01:01:01' == eta_hms(3661, hours_leading_zero=True, always_show_hours=True) assert '167:59:59'",
"'01:00:00' == eta_hms(3600, hours_leading_zero=True) assert '01:00:01' == eta_hms(3601, hours_leading_zero=True) assert '01:01:01' == eta_hms(3661,",
"test_always_show_minutes(): assert '00:00' == eta_hms(0, always_show_minutes=True) assert '00:09' == eta_hms(9, always_show_minutes=True) assert '00:59'",
"hours_leading_zero=True, always_show_minutes=True) assert '01:00' == eta_hms(60, hours_leading_zero=True, always_show_minutes=True) assert '01:01' == eta_hms(61, hours_leading_zero=True,",
"hours_leading_zero=True) assert '09' == eta_hms(9, hours_leading_zero=True) assert '59' == eta_hms(59, hours_leading_zero=True) assert '01:00'",
"always_show_hours=True) assert '00:00:59' == eta_hms(59, hours_leading_zero=True, always_show_hours=True) assert '00:01:00' == eta_hms(60, hours_leading_zero=True, always_show_hours=True)",
"== eta_hms(3661) assert '167:59:59' == eta_hms(604799) assert '168:00:00' == eta_hms(604800) assert '168:00:01' ==",
"hours_leading_zero=True, always_show_hours=True) assert '01:00:01' == eta_hms(3601, hours_leading_zero=True, always_show_hours=True) assert '01:01:01' == eta_hms(3661, hours_leading_zero=True,",
"eta_hms(3601, hours_leading_zero=True, always_show_hours=True) assert '01:01:01' == eta_hms(3661, hours_leading_zero=True, always_show_hours=True) assert '167:59:59' == eta_hms(604799,",
"always_show_hours=True) assert '0:01:01' == eta_hms(61, always_show_hours=True) assert '0:59:59' == eta_hms(3599, always_show_hours=True) assert '1:00:00'",
"eta_hms(59, always_show_hours=True) assert '0:01:00' == eta_hms(60, always_show_hours=True) assert '0:01:01' == eta_hms(61, always_show_hours=True) assert",
"always_show_hours=True) assert '00:01:01' == eta_hms(61, hours_leading_zero=True, always_show_hours=True) assert '00:59:59' == eta_hms(3599, hours_leading_zero=True, always_show_hours=True)",
"'00:00:00' == eta_hms(0, hours_leading_zero=True, always_show_hours=True) assert '00:00:09' == eta_hms(9, hours_leading_zero=True, always_show_hours=True) assert '00:00:59'",
"hours_leading_zero=True, always_show_hours=True) assert '00:01:01' == eta_hms(61, hours_leading_zero=True, always_show_hours=True) assert '00:59:59' == eta_hms(3599, hours_leading_zero=True,",
"== eta_hms(604799, hours_leading_zero=True, always_show_minutes=True) assert '168:00:00' == eta_hms(604800, hours_leading_zero=True, always_show_minutes=True) assert '168:00:01' ==",
"assert '00:59:59' == eta_hms(3599, hours_leading_zero=True, always_show_hours=True) assert '01:00:00' == eta_hms(3600, hours_leading_zero=True, always_show_hours=True) assert",
"'168:00:01' == eta_hms(604801, always_show_minutes=True) def test_always_show_hours(): assert '0:00:00' == eta_hms(0, always_show_hours=True) assert '0:00:09'",
"'0:00:09' == eta_hms(9, always_show_hours=True) assert '0:00:59' == eta_hms(59, always_show_hours=True) assert '0:01:00' == eta_hms(60,",
"'01:01' == eta_hms(61, always_show_minutes=True) assert '59:59' == eta_hms(3599, always_show_minutes=True) assert '1:00:00' == eta_hms(3600,",
"assert '168:00:00' == eta_hms(604800) assert '168:00:01' == eta_hms(604801) def test_always_show_minutes(): assert '00:00' ==",
"== eta_hms(0, always_show_hours=True) assert '0:00:09' == eta_hms(9, always_show_hours=True) assert '0:00:59' == eta_hms(59, always_show_hours=True)",
"eta_hms def test(): assert '00' == eta_hms(0) assert '09' == eta_hms(9) assert '59'",
"always_show_minutes=True) assert '168:00:00' == eta_hms(604800, hours_leading_zero=True, always_show_minutes=True) assert '168:00:01' == eta_hms(604801, hours_leading_zero=True, always_show_minutes=True)",
"assert '168:00:00' == eta_hms(604800, hours_leading_zero=True) assert '168:00:01' == eta_hms(604801, hours_leading_zero=True) def test_always_show_minutes_hours_leading_zero(): assert",
"'0:59:59' == eta_hms(3599, always_show_hours=True) assert '1:00:00' == eta_hms(3600, always_show_hours=True) assert '1:00:01' == eta_hms(3601,",
"eta_hms(59, always_show_minutes=True) assert '01:00' == eta_hms(60, always_show_minutes=True) assert '01:01' == eta_hms(61, always_show_minutes=True) assert",
"always_show_minutes=True) assert '01:01:01' == eta_hms(3661, hours_leading_zero=True, always_show_minutes=True) assert '167:59:59' == eta_hms(604799, hours_leading_zero=True, always_show_minutes=True)",
"rest is mostly copy/pasted. ############################################ def test_hours_leading_zero(): assert '00' == eta_hms(0, hours_leading_zero=True) assert",
"eta_hms(604799, hours_leading_zero=True) assert '168:00:00' == eta_hms(604800, hours_leading_zero=True) assert '168:00:01' == eta_hms(604801, hours_leading_zero=True) def",
"eta_hms(60, always_show_hours=True) assert '0:01:01' == eta_hms(61, always_show_hours=True) assert '0:59:59' == eta_hms(3599, always_show_hours=True) assert",
"eta_hms(3601, hours_leading_zero=True, always_show_minutes=True) assert '01:01:01' == eta_hms(3661, hours_leading_zero=True, always_show_minutes=True) assert '167:59:59' == eta_hms(604799,",
"eta_hms(3599, always_show_hours=True) assert '1:00:00' == eta_hms(3600, always_show_hours=True) assert '1:00:01' == eta_hms(3601, always_show_hours=True) assert",
"eta_hms(3661, hours_leading_zero=True, always_show_hours=True) assert '167:59:59' == eta_hms(604799, hours_leading_zero=True, always_show_hours=True) assert '168:00:00' == eta_hms(604800,",
"'59:59' == eta_hms(3599) assert '1:00:00' == eta_hms(3600) assert '1:00:01' == eta_hms(3601) assert '1:01:01'",
"assert '0:01:01' == eta_hms(61, always_show_hours=True) assert '0:59:59' == eta_hms(3599, always_show_hours=True) assert '1:00:00' ==",
"'01:01' == eta_hms(61) assert '59:59' == eta_hms(3599) assert '1:00:00' == eta_hms(3600) assert '1:00:01'",
"test_hours_leading_zero(): assert '00' == eta_hms(0, hours_leading_zero=True) assert '09' == eta_hms(9, hours_leading_zero=True) assert '59'",
"eta_hms(604800) assert '168:00:01' == eta_hms(604801) def test_always_show_minutes(): assert '00:00' == eta_hms(0, always_show_minutes=True) assert",
"hours_leading_zero=True) assert '01:00:00' == eta_hms(3600, hours_leading_zero=True) assert '01:00:01' == eta_hms(3601, hours_leading_zero=True) assert '01:01:01'",
"'59' == eta_hms(59) assert '01:00' == eta_hms(60) assert '01:01' == eta_hms(61) assert '59:59'",
"hours_leading_zero=True) assert '01:00' == eta_hms(60, hours_leading_zero=True) assert '01:01' == eta_hms(61, hours_leading_zero=True) assert '59:59'",
"assert '01:01:01' == eta_hms(3661, hours_leading_zero=True, always_show_minutes=True) assert '167:59:59' == eta_hms(604799, hours_leading_zero=True, always_show_minutes=True) assert",
"assert '168:00:01' == eta_hms(604801, hours_leading_zero=True) def test_always_show_minutes_hours_leading_zero(): assert '00:00' == eta_hms(0, hours_leading_zero=True, always_show_minutes=True)",
"'0:01:00' == eta_hms(60, always_show_hours=True) assert '0:01:01' == eta_hms(61, always_show_hours=True) assert '0:59:59' == eta_hms(3599,",
"assert '0:00:59' == eta_hms(59, always_show_hours=True) assert '0:01:00' == eta_hms(60, always_show_hours=True) assert '0:01:01' ==",
"'01:01:01' == eta_hms(3661, hours_leading_zero=True, always_show_minutes=True) assert '167:59:59' == eta_hms(604799, hours_leading_zero=True, always_show_minutes=True) assert '168:00:00'",
"'168:00:00' == eta_hms(604800, hours_leading_zero=True) assert '168:00:01' == eta_hms(604801, hours_leading_zero=True) def test_always_show_minutes_hours_leading_zero(): assert '00:00'",
"test(): assert '00' == eta_hms(0) assert '09' == eta_hms(9) assert '59' == eta_hms(59)",
"assert '00:59' == eta_hms(59, hours_leading_zero=True, always_show_minutes=True) assert '01:00' == eta_hms(60, hours_leading_zero=True, always_show_minutes=True) assert",
"'00' == eta_hms(0, hours_leading_zero=True) assert '09' == eta_hms(9, hours_leading_zero=True) assert '59' == eta_hms(59,",
"assert '01:00:00' == eta_hms(3600, hours_leading_zero=True, always_show_minutes=True) assert '01:00:01' == eta_hms(3601, hours_leading_zero=True, always_show_minutes=True) assert",
"'167:59:59' == eta_hms(604799, hours_leading_zero=True) assert '168:00:00' == eta_hms(604800, hours_leading_zero=True) assert '168:00:01' == eta_hms(604801,",
"eta_hms(61, always_show_minutes=True) assert '59:59' == eta_hms(3599, always_show_minutes=True) assert '1:00:00' == eta_hms(3600, always_show_minutes=True) assert",
"'01:00' == eta_hms(60, always_show_minutes=True) assert '01:01' == eta_hms(61, always_show_minutes=True) assert '59:59' == eta_hms(3599,",
"== eta_hms(61) assert '59:59' == eta_hms(3599) assert '1:00:00' == eta_hms(3600) assert '1:00:01' ==",
"'168:00:01' == eta_hms(604801, hours_leading_zero=True, always_show_minutes=True) def test_always_show_hours_hours_leading_zero(): assert '00:00:00' == eta_hms(0, hours_leading_zero=True, always_show_hours=True)",
"assert '01:00' == eta_hms(60, hours_leading_zero=True) assert '01:01' == eta_hms(61, hours_leading_zero=True) assert '59:59' ==",
"always_show_hours=True) assert '167:59:59' == eta_hms(604799, always_show_hours=True) assert '168:00:00' == eta_hms(604800, always_show_hours=True) assert '168:00:01'",
"assert '00:59' == eta_hms(59, always_show_minutes=True) assert '01:00' == eta_hms(60, always_show_minutes=True) assert '01:01' ==",
"import eta_hms def test(): assert '00' == eta_hms(0) assert '09' == eta_hms(9) assert",
"== eta_hms(60, hours_leading_zero=True) assert '01:01' == eta_hms(61, hours_leading_zero=True) assert '59:59' == eta_hms(3599, hours_leading_zero=True)",
"eta_hms(3600, hours_leading_zero=True, always_show_minutes=True) assert '01:00:01' == eta_hms(3601, hours_leading_zero=True, always_show_minutes=True) assert '01:01:01' == eta_hms(3661,",
"'168:00:00' == eta_hms(604800, always_show_hours=True) assert '168:00:01' == eta_hms(604801, always_show_hours=True) # The rest is",
"eta_hms(3661) assert '167:59:59' == eta_hms(604799) assert '168:00:00' == eta_hms(604800) assert '168:00:01' == eta_hms(604801)",
"assert '59:59' == eta_hms(3599, always_show_minutes=True) assert '1:00:00' == eta_hms(3600, always_show_minutes=True) assert '1:00:01' ==",
"assert '00:00:00' == eta_hms(0, hours_leading_zero=True, always_show_hours=True) assert '00:00:09' == eta_hms(9, hours_leading_zero=True, always_show_hours=True) assert",
"'1:01:01' == eta_hms(3661, always_show_hours=True) assert '167:59:59' == eta_hms(604799, always_show_hours=True) assert '168:00:00' == eta_hms(604800,",
"eta_hms(3600, hours_leading_zero=True, always_show_hours=True) assert '01:00:01' == eta_hms(3601, hours_leading_zero=True, always_show_hours=True) assert '01:01:01' == eta_hms(3661,",
"'59:59' == eta_hms(3599, hours_leading_zero=True) assert '01:00:00' == eta_hms(3600, hours_leading_zero=True) assert '01:00:01' == eta_hms(3601,",
"assert '167:59:59' == eta_hms(604799, hours_leading_zero=True, always_show_hours=True) assert '168:00:00' == eta_hms(604800, hours_leading_zero=True, always_show_hours=True) assert",
"== eta_hms(61, hours_leading_zero=True, always_show_minutes=True) assert '59:59' == eta_hms(3599, hours_leading_zero=True, always_show_minutes=True) assert '01:00:00' ==",
"assert '167:59:59' == eta_hms(604799) assert '168:00:00' == eta_hms(604800) assert '168:00:01' == eta_hms(604801) def",
"eta_hms(59, hours_leading_zero=True) assert '01:00' == eta_hms(60, hours_leading_zero=True) assert '01:01' == eta_hms(61, hours_leading_zero=True) assert",
"== eta_hms(3601, always_show_minutes=True) assert '1:01:01' == eta_hms(3661, always_show_minutes=True) assert '167:59:59' == eta_hms(604799, always_show_minutes=True)",
"hours_leading_zero=True, always_show_hours=True) assert '167:59:59' == eta_hms(604799, hours_leading_zero=True, always_show_hours=True) assert '168:00:00' == eta_hms(604800, hours_leading_zero=True,",
"== eta_hms(604800, hours_leading_zero=True) assert '168:00:01' == eta_hms(604801, hours_leading_zero=True) def test_always_show_minutes_hours_leading_zero(): assert '00:00' ==",
"assert '59:59' == eta_hms(3599, hours_leading_zero=True) assert '01:00:00' == eta_hms(3600, hours_leading_zero=True) assert '01:00:01' ==",
"hours_leading_zero=True, always_show_hours=True) assert '00:59:59' == eta_hms(3599, hours_leading_zero=True, always_show_hours=True) assert '01:00:00' == eta_hms(3600, hours_leading_zero=True,",
"== eta_hms(3600, hours_leading_zero=True) assert '01:00:01' == eta_hms(3601, hours_leading_zero=True) assert '01:01:01' == eta_hms(3661, hours_leading_zero=True)",
"eta_hms(3601) assert '1:01:01' == eta_hms(3661) assert '167:59:59' == eta_hms(604799) assert '168:00:00' == eta_hms(604800)",
"always_show_hours=True) assert '0:01:00' == eta_hms(60, always_show_hours=True) assert '0:01:01' == eta_hms(61, always_show_hours=True) assert '0:59:59'",
"'00:00:09' == eta_hms(9, hours_leading_zero=True, always_show_hours=True) assert '00:00:59' == eta_hms(59, hours_leading_zero=True, always_show_hours=True) assert '00:01:00'",
"always_show_minutes=True) assert '01:00:01' == eta_hms(3601, hours_leading_zero=True, always_show_minutes=True) assert '01:01:01' == eta_hms(3661, hours_leading_zero=True, always_show_minutes=True)",
"'1:00:01' == eta_hms(3601) assert '1:01:01' == eta_hms(3661) assert '167:59:59' == eta_hms(604799) assert '168:00:00'",
"eta_hms(59, hours_leading_zero=True, always_show_minutes=True) assert '01:00' == eta_hms(60, hours_leading_zero=True, always_show_minutes=True) assert '01:01' == eta_hms(61,",
"eta_hms(604799, hours_leading_zero=True, always_show_minutes=True) assert '168:00:00' == eta_hms(604800, hours_leading_zero=True, always_show_minutes=True) assert '168:00:01' == eta_hms(604801,",
"assert '167:59:59' == eta_hms(604799, hours_leading_zero=True) assert '168:00:00' == eta_hms(604800, hours_leading_zero=True) assert '168:00:01' ==",
"always_show_minutes=True) assert '168:00:01' == eta_hms(604801, hours_leading_zero=True, always_show_minutes=True) def test_always_show_hours_hours_leading_zero(): assert '00:00:00' == eta_hms(0,",
"assert '1:01:01' == eta_hms(3661) assert '167:59:59' == eta_hms(604799) assert '168:00:00' == eta_hms(604800) assert",
"eta_hms(3601, hours_leading_zero=True) assert '01:01:01' == eta_hms(3661, hours_leading_zero=True) assert '167:59:59' == eta_hms(604799, hours_leading_zero=True) assert",
"always_show_hours=True) assert '167:59:59' == eta_hms(604799, hours_leading_zero=True, always_show_hours=True) assert '168:00:00' == eta_hms(604800, hours_leading_zero=True, always_show_hours=True)",
"eta_hms(3599) assert '1:00:00' == eta_hms(3600) assert '1:00:01' == eta_hms(3601) assert '1:01:01' == eta_hms(3661)",
"== eta_hms(9, hours_leading_zero=True) assert '59' == eta_hms(59, hours_leading_zero=True) assert '01:00' == eta_hms(60, hours_leading_zero=True)",
"eta_hms(60, hours_leading_zero=True) assert '01:01' == eta_hms(61, hours_leading_zero=True) assert '59:59' == eta_hms(3599, hours_leading_zero=True) assert",
"assert '00:01:00' == eta_hms(60, hours_leading_zero=True, always_show_hours=True) assert '00:01:01' == eta_hms(61, hours_leading_zero=True, always_show_hours=True) assert",
"== eta_hms(3661, always_show_minutes=True) assert '167:59:59' == eta_hms(604799, always_show_minutes=True) assert '168:00:00' == eta_hms(604800, always_show_minutes=True)",
"eta_hms(604799, hours_leading_zero=True, always_show_hours=True) assert '168:00:00' == eta_hms(604800, hours_leading_zero=True, always_show_hours=True) assert '168:00:01' == eta_hms(604801,",
"always_show_minutes=True) assert '01:00:00' == eta_hms(3600, hours_leading_zero=True, always_show_minutes=True) assert '01:00:01' == eta_hms(3601, hours_leading_zero=True, always_show_minutes=True)",
"assert '167:59:59' == eta_hms(604799, always_show_minutes=True) assert '168:00:00' == eta_hms(604800, always_show_minutes=True) assert '168:00:01' ==",
"eta_hms(3600) assert '1:00:01' == eta_hms(3601) assert '1:01:01' == eta_hms(3661) assert '167:59:59' == eta_hms(604799)",
"'01:01:01' == eta_hms(3661, hours_leading_zero=True, always_show_hours=True) assert '167:59:59' == eta_hms(604799, hours_leading_zero=True, always_show_hours=True) assert '168:00:00'",
"always_show_minutes=True) assert '00:09' == eta_hms(9, always_show_minutes=True) assert '00:59' == eta_hms(59, always_show_minutes=True) assert '01:00'",
"eta_hms(61, hours_leading_zero=True, always_show_minutes=True) assert '59:59' == eta_hms(3599, hours_leading_zero=True, always_show_minutes=True) assert '01:00:00' == eta_hms(3600,",
"'01:00:01' == eta_hms(3601, hours_leading_zero=True) assert '01:01:01' == eta_hms(3661, hours_leading_zero=True) assert '167:59:59' == eta_hms(604799,",
"eta_hms(0, always_show_hours=True) assert '0:00:09' == eta_hms(9, always_show_hours=True) assert '0:00:59' == eta_hms(59, always_show_hours=True) assert",
"== eta_hms(59) assert '01:00' == eta_hms(60) assert '01:01' == eta_hms(61) assert '59:59' ==",
"assert '01:01' == eta_hms(61, always_show_minutes=True) assert '59:59' == eta_hms(3599, always_show_minutes=True) assert '1:00:00' ==",
"def test(): assert '00' == eta_hms(0) assert '09' == eta_hms(9) assert '59' ==",
"'01:01' == eta_hms(61, hours_leading_zero=True) assert '59:59' == eta_hms(3599, hours_leading_zero=True) assert '01:00:00' == eta_hms(3600,",
"== eta_hms(3661, hours_leading_zero=True, always_show_hours=True) assert '167:59:59' == eta_hms(604799, hours_leading_zero=True, always_show_hours=True) assert '168:00:00' ==",
"hours_leading_zero=True, always_show_minutes=True) assert '168:00:01' == eta_hms(604801, hours_leading_zero=True, always_show_minutes=True) def test_always_show_hours_hours_leading_zero(): assert '00:00:00' ==",
"'1:01:01' == eta_hms(3661) assert '167:59:59' == eta_hms(604799) assert '168:00:00' == eta_hms(604800) assert '168:00:01'",
"hours_leading_zero=True, always_show_minutes=True) def test_always_show_hours_hours_leading_zero(): assert '00:00:00' == eta_hms(0, hours_leading_zero=True, always_show_hours=True) assert '00:00:09' ==",
"always_show_minutes=True) assert '00:09' == eta_hms(9, hours_leading_zero=True, always_show_minutes=True) assert '00:59' == eta_hms(59, hours_leading_zero=True, always_show_minutes=True)",
"'01:00' == eta_hms(60, hours_leading_zero=True) assert '01:01' == eta_hms(61, hours_leading_zero=True) assert '59:59' == eta_hms(3599,",
"'0:00:59' == eta_hms(59, always_show_hours=True) assert '0:01:00' == eta_hms(60, always_show_hours=True) assert '0:01:01' == eta_hms(61,",
"eta_hms(604801, hours_leading_zero=True, always_show_minutes=True) def test_always_show_hours_hours_leading_zero(): assert '00:00:00' == eta_hms(0, hours_leading_zero=True, always_show_hours=True) assert '00:00:09'",
"hours_leading_zero=True, always_show_minutes=True) assert '00:59' == eta_hms(59, hours_leading_zero=True, always_show_minutes=True) assert '01:00' == eta_hms(60, hours_leading_zero=True,",
"== eta_hms(0, hours_leading_zero=True, always_show_minutes=True) assert '00:09' == eta_hms(9, hours_leading_zero=True, always_show_minutes=True) assert '00:59' ==",
"'167:59:59' == eta_hms(604799, always_show_minutes=True) assert '168:00:00' == eta_hms(604800, always_show_minutes=True) assert '168:00:01' == eta_hms(604801,",
"assert '59' == eta_hms(59, hours_leading_zero=True) assert '01:00' == eta_hms(60, hours_leading_zero=True) assert '01:01' ==",
"always_show_hours=True) assert '01:00:00' == eta_hms(3600, hours_leading_zero=True, always_show_hours=True) assert '01:00:01' == eta_hms(3601, hours_leading_zero=True, always_show_hours=True)",
"'01:01:01' == eta_hms(3661, hours_leading_zero=True) assert '167:59:59' == eta_hms(604799, hours_leading_zero=True) assert '168:00:00' == eta_hms(604800,",
"'167:59:59' == eta_hms(604799) assert '168:00:00' == eta_hms(604800) assert '168:00:01' == eta_hms(604801) def test_always_show_minutes():",
"== eta_hms(9, always_show_minutes=True) assert '00:59' == eta_hms(59, always_show_minutes=True) assert '01:00' == eta_hms(60, always_show_minutes=True)",
"always_show_hours=True) assert '00:00:09' == eta_hms(9, hours_leading_zero=True, always_show_hours=True) assert '00:00:59' == eta_hms(59, hours_leading_zero=True, always_show_hours=True)",
"eta_hms(60, hours_leading_zero=True, always_show_minutes=True) assert '01:01' == eta_hms(61, hours_leading_zero=True, always_show_minutes=True) assert '59:59' == eta_hms(3599,",
"assert '01:00:00' == eta_hms(3600, hours_leading_zero=True) assert '01:00:01' == eta_hms(3601, hours_leading_zero=True) assert '01:01:01' ==",
"'00:59' == eta_hms(59, hours_leading_zero=True, always_show_minutes=True) assert '01:00' == eta_hms(60, hours_leading_zero=True, always_show_minutes=True) assert '01:01'",
"'59' == eta_hms(59, hours_leading_zero=True) assert '01:00' == eta_hms(60, hours_leading_zero=True) assert '01:01' == eta_hms(61,",
"== eta_hms(3600) assert '1:00:01' == eta_hms(3601) assert '1:01:01' == eta_hms(3661) assert '167:59:59' ==",
"etaprogress.components.eta_conversions import eta_hms def test(): assert '00' == eta_hms(0) assert '09' == eta_hms(9)",
"always_show_hours=True) assert '168:00:00' == eta_hms(604800, always_show_hours=True) assert '168:00:01' == eta_hms(604801, always_show_hours=True) # The",
"always_show_minutes=True) assert '00:59' == eta_hms(59, always_show_minutes=True) assert '01:00' == eta_hms(60, always_show_minutes=True) assert '01:01'",
"== eta_hms(3601, hours_leading_zero=True, always_show_minutes=True) assert '01:01:01' == eta_hms(3661, hours_leading_zero=True, always_show_minutes=True) assert '167:59:59' ==",
"'168:00:00' == eta_hms(604800) assert '168:00:01' == eta_hms(604801) def test_always_show_minutes(): assert '00:00' == eta_hms(0,",
"hours_leading_zero=True) assert '01:00:01' == eta_hms(3601, hours_leading_zero=True) assert '01:01:01' == eta_hms(3661, hours_leading_zero=True) assert '167:59:59'",
"== eta_hms(59, hours_leading_zero=True, always_show_hours=True) assert '00:01:00' == eta_hms(60, hours_leading_zero=True, always_show_hours=True) assert '00:01:01' ==",
"== eta_hms(0, hours_leading_zero=True, always_show_hours=True) assert '00:00:09' == eta_hms(9, hours_leading_zero=True, always_show_hours=True) assert '00:00:59' ==",
"'01:00:01' == eta_hms(3601, hours_leading_zero=True, always_show_minutes=True) assert '01:01:01' == eta_hms(3661, hours_leading_zero=True, always_show_minutes=True) assert '167:59:59'",
"eta_hms(604800, hours_leading_zero=True, always_show_minutes=True) assert '168:00:01' == eta_hms(604801, hours_leading_zero=True, always_show_minutes=True) def test_always_show_hours_hours_leading_zero(): assert '00:00:00'",
"hours_leading_zero=True) assert '168:00:00' == eta_hms(604800, hours_leading_zero=True) assert '168:00:01' == eta_hms(604801, hours_leading_zero=True) def test_always_show_minutes_hours_leading_zero():",
"hours_leading_zero=True, always_show_hours=True) assert '01:00:00' == eta_hms(3600, hours_leading_zero=True, always_show_hours=True) assert '01:00:01' == eta_hms(3601, hours_leading_zero=True,",
"'00:01:01' == eta_hms(61, hours_leading_zero=True, always_show_hours=True) assert '00:59:59' == eta_hms(3599, hours_leading_zero=True, always_show_hours=True) assert '01:00:00'",
"always_show_hours=True) assert '168:00:01' == eta_hms(604801, always_show_hours=True) # The rest is mostly copy/pasted. ############################################",
"hours_leading_zero=True, always_show_minutes=True) assert '01:01:01' == eta_hms(3661, hours_leading_zero=True, always_show_minutes=True) assert '167:59:59' == eta_hms(604799, hours_leading_zero=True,",
"eta_hms(604800, always_show_minutes=True) assert '168:00:01' == eta_hms(604801, always_show_minutes=True) def test_always_show_hours(): assert '0:00:00' == eta_hms(0,",
"== eta_hms(3599, hours_leading_zero=True) assert '01:00:00' == eta_hms(3600, hours_leading_zero=True) assert '01:00:01' == eta_hms(3601, hours_leading_zero=True)",
"hours_leading_zero=True, always_show_minutes=True) assert '01:00:00' == eta_hms(3600, hours_leading_zero=True, always_show_minutes=True) assert '01:00:01' == eta_hms(3601, hours_leading_zero=True,",
"always_show_hours=True) assert '01:00:01' == eta_hms(3601, hours_leading_zero=True, always_show_hours=True) assert '01:01:01' == eta_hms(3661, hours_leading_zero=True, always_show_hours=True)",
"eta_hms(9, hours_leading_zero=True, always_show_hours=True) assert '00:00:59' == eta_hms(59, hours_leading_zero=True, always_show_hours=True) assert '00:01:00' == eta_hms(60,",
"== eta_hms(604800) assert '168:00:01' == eta_hms(604801) def test_always_show_minutes(): assert '00:00' == eta_hms(0, always_show_minutes=True)",
"always_show_minutes=True) def test_always_show_hours_hours_leading_zero(): assert '00:00:00' == eta_hms(0, hours_leading_zero=True, always_show_hours=True) assert '00:00:09' == eta_hms(9,",
"always_show_minutes=True) assert '1:00:00' == eta_hms(3600, always_show_minutes=True) assert '1:00:01' == eta_hms(3601, always_show_minutes=True) assert '1:01:01'",
"assert '168:00:01' == eta_hms(604801, always_show_minutes=True) def test_always_show_hours(): assert '0:00:00' == eta_hms(0, always_show_hours=True) assert",
"assert '1:00:00' == eta_hms(3600) assert '1:00:01' == eta_hms(3601) assert '1:01:01' == eta_hms(3661) assert",
"eta_hms(0, always_show_minutes=True) assert '00:09' == eta_hms(9, always_show_minutes=True) assert '00:59' == eta_hms(59, always_show_minutes=True) assert",
"assert '01:00' == eta_hms(60) assert '01:01' == eta_hms(61) assert '59:59' == eta_hms(3599) assert",
"eta_hms(3661, hours_leading_zero=True, always_show_minutes=True) assert '167:59:59' == eta_hms(604799, hours_leading_zero=True, always_show_minutes=True) assert '168:00:00' == eta_hms(604800,",
"assert '01:00:01' == eta_hms(3601, hours_leading_zero=True) assert '01:01:01' == eta_hms(3661, hours_leading_zero=True) assert '167:59:59' ==",
"eta_hms(604801) def test_always_show_minutes(): assert '00:00' == eta_hms(0, always_show_minutes=True) assert '00:09' == eta_hms(9, always_show_minutes=True)",
"assert '01:00' == eta_hms(60, hours_leading_zero=True, always_show_minutes=True) assert '01:01' == eta_hms(61, hours_leading_zero=True, always_show_minutes=True) assert",
"'1:01:01' == eta_hms(3661, always_show_minutes=True) assert '167:59:59' == eta_hms(604799, always_show_minutes=True) assert '168:00:00' == eta_hms(604800,",
"assert '00:01:01' == eta_hms(61, hours_leading_zero=True, always_show_hours=True) assert '00:59:59' == eta_hms(3599, hours_leading_zero=True, always_show_hours=True) assert",
"always_show_minutes=True) assert '59:59' == eta_hms(3599, always_show_minutes=True) assert '1:00:00' == eta_hms(3600, always_show_minutes=True) assert '1:00:01'",
"hours_leading_zero=True, always_show_hours=True) assert '00:01:00' == eta_hms(60, hours_leading_zero=True, always_show_hours=True) assert '00:01:01' == eta_hms(61, hours_leading_zero=True,",
"assert '01:00:01' == eta_hms(3601, hours_leading_zero=True, always_show_minutes=True) assert '01:01:01' == eta_hms(3661, hours_leading_zero=True, always_show_minutes=True) assert",
"always_show_minutes=True) assert '01:01' == eta_hms(61, hours_leading_zero=True, always_show_minutes=True) assert '59:59' == eta_hms(3599, hours_leading_zero=True, always_show_minutes=True)",
"always_show_hours=True) assert '0:59:59' == eta_hms(3599, always_show_hours=True) assert '1:00:00' == eta_hms(3600, always_show_hours=True) assert '1:00:01'",
"== eta_hms(59, hours_leading_zero=True, always_show_minutes=True) assert '01:00' == eta_hms(60, hours_leading_zero=True, always_show_minutes=True) assert '01:01' ==",
"always_show_hours=True) assert '00:01:00' == eta_hms(60, hours_leading_zero=True, always_show_hours=True) assert '00:01:01' == eta_hms(61, hours_leading_zero=True, always_show_hours=True)",
"eta_hms(60, hours_leading_zero=True, always_show_hours=True) assert '00:01:01' == eta_hms(61, hours_leading_zero=True, always_show_hours=True) assert '00:59:59' == eta_hms(3599,",
"assert '167:59:59' == eta_hms(604799, hours_leading_zero=True, always_show_minutes=True) assert '168:00:00' == eta_hms(604800, hours_leading_zero=True, always_show_minutes=True) assert",
"eta_hms(60, always_show_minutes=True) assert '01:01' == eta_hms(61, always_show_minutes=True) assert '59:59' == eta_hms(3599, always_show_minutes=True) assert",
"assert '00:09' == eta_hms(9, hours_leading_zero=True, always_show_minutes=True) assert '00:59' == eta_hms(59, hours_leading_zero=True, always_show_minutes=True) assert",
"== eta_hms(9, hours_leading_zero=True, always_show_minutes=True) assert '00:59' == eta_hms(59, hours_leading_zero=True, always_show_minutes=True) assert '01:00' ==",
"== eta_hms(604800, always_show_hours=True) assert '168:00:01' == eta_hms(604801, always_show_hours=True) # The rest is mostly",
"eta_hms(9, always_show_minutes=True) assert '00:59' == eta_hms(59, always_show_minutes=True) assert '01:00' == eta_hms(60, always_show_minutes=True) assert",
"assert '01:01' == eta_hms(61) assert '59:59' == eta_hms(3599) assert '1:00:00' == eta_hms(3600) assert",
"== eta_hms(59, hours_leading_zero=True) assert '01:00' == eta_hms(60, hours_leading_zero=True) assert '01:01' == eta_hms(61, hours_leading_zero=True)",
"'09' == eta_hms(9) assert '59' == eta_hms(59) assert '01:00' == eta_hms(60) assert '01:01'",
"assert '00:09' == eta_hms(9, always_show_minutes=True) assert '00:59' == eta_hms(59, always_show_minutes=True) assert '01:00' ==",
"'1:00:00' == eta_hms(3600) assert '1:00:01' == eta_hms(3601) assert '1:01:01' == eta_hms(3661) assert '167:59:59'",
"hours_leading_zero=True, always_show_minutes=True) assert '167:59:59' == eta_hms(604799, hours_leading_zero=True, always_show_minutes=True) assert '168:00:00' == eta_hms(604800, hours_leading_zero=True,",
"== eta_hms(604801, hours_leading_zero=True) def test_always_show_minutes_hours_leading_zero(): assert '00:00' == eta_hms(0, hours_leading_zero=True, always_show_minutes=True) assert '00:09'",
"== eta_hms(9) assert '59' == eta_hms(59) assert '01:00' == eta_hms(60) assert '01:01' ==",
"test_always_show_hours(): assert '0:00:00' == eta_hms(0, always_show_hours=True) assert '0:00:09' == eta_hms(9, always_show_hours=True) assert '0:00:59'",
"'1:00:00' == eta_hms(3600, always_show_minutes=True) assert '1:00:01' == eta_hms(3601, always_show_minutes=True) assert '1:01:01' == eta_hms(3661,",
"'00:09' == eta_hms(9, hours_leading_zero=True, always_show_minutes=True) assert '00:59' == eta_hms(59, hours_leading_zero=True, always_show_minutes=True) assert '01:00'",
"assert '168:00:01' == eta_hms(604801, hours_leading_zero=True, always_show_minutes=True) def test_always_show_hours_hours_leading_zero(): assert '00:00:00' == eta_hms(0, hours_leading_zero=True,",
"assert '59:59' == eta_hms(3599) assert '1:00:00' == eta_hms(3600) assert '1:00:01' == eta_hms(3601) assert",
"== eta_hms(3601) assert '1:01:01' == eta_hms(3661) assert '167:59:59' == eta_hms(604799) assert '168:00:00' ==",
"hours_leading_zero=True, always_show_hours=True) assert '00:00:09' == eta_hms(9, hours_leading_zero=True, always_show_hours=True) assert '00:00:59' == eta_hms(59, hours_leading_zero=True,",
"assert '01:00' == eta_hms(60, always_show_minutes=True) assert '01:01' == eta_hms(61, always_show_minutes=True) assert '59:59' ==",
"always_show_minutes=True) assert '1:00:01' == eta_hms(3601, always_show_minutes=True) assert '1:01:01' == eta_hms(3661, always_show_minutes=True) assert '167:59:59'",
"== eta_hms(9, always_show_hours=True) assert '0:00:59' == eta_hms(59, always_show_hours=True) assert '0:01:00' == eta_hms(60, always_show_hours=True)",
"from etaprogress.components.eta_conversions import eta_hms def test(): assert '00' == eta_hms(0) assert '09' ==",
"'1:00:00' == eta_hms(3600, always_show_hours=True) assert '1:00:01' == eta_hms(3601, always_show_hours=True) assert '1:01:01' == eta_hms(3661,",
"always_show_minutes=True) assert '167:59:59' == eta_hms(604799, hours_leading_zero=True, always_show_minutes=True) assert '168:00:00' == eta_hms(604800, hours_leading_zero=True, always_show_minutes=True)",
"== eta_hms(3600, hours_leading_zero=True, always_show_hours=True) assert '01:00:01' == eta_hms(3601, hours_leading_zero=True, always_show_hours=True) assert '01:01:01' ==",
"eta_hms(3599, always_show_minutes=True) assert '1:00:00' == eta_hms(3600, always_show_minutes=True) assert '1:00:01' == eta_hms(3601, always_show_minutes=True) assert",
"'168:00:01' == eta_hms(604801) def test_always_show_minutes(): assert '00:00' == eta_hms(0, always_show_minutes=True) assert '00:09' ==",
"eta_hms(60) assert '01:01' == eta_hms(61) assert '59:59' == eta_hms(3599) assert '1:00:00' == eta_hms(3600)",
"'168:00:00' == eta_hms(604800, always_show_minutes=True) assert '168:00:01' == eta_hms(604801, always_show_minutes=True) def test_always_show_hours(): assert '0:00:00'",
"<filename>tests/test_components_eta_hms.py from etaprogress.components.eta_conversions import eta_hms def test(): assert '00' == eta_hms(0) assert '09'",
"eta_hms(0, hours_leading_zero=True, always_show_hours=True) assert '00:00:09' == eta_hms(9, hours_leading_zero=True, always_show_hours=True) assert '00:00:59' == eta_hms(59,",
"eta_hms(604799, always_show_minutes=True) assert '168:00:00' == eta_hms(604800, always_show_minutes=True) assert '168:00:01' == eta_hms(604801, always_show_minutes=True) def",
"always_show_minutes=True) assert '1:01:01' == eta_hms(3661, always_show_minutes=True) assert '167:59:59' == eta_hms(604799, always_show_minutes=True) assert '168:00:00'",
"== eta_hms(9, hours_leading_zero=True, always_show_hours=True) assert '00:00:59' == eta_hms(59, hours_leading_zero=True, always_show_hours=True) assert '00:01:00' ==",
"hours_leading_zero=True, always_show_minutes=True) assert '01:00:01' == eta_hms(3601, hours_leading_zero=True, always_show_minutes=True) assert '01:01:01' == eta_hms(3661, hours_leading_zero=True,",
"assert '00' == eta_hms(0, hours_leading_zero=True) assert '09' == eta_hms(9, hours_leading_zero=True) assert '59' ==",
"assert '1:00:01' == eta_hms(3601, always_show_minutes=True) assert '1:01:01' == eta_hms(3661, always_show_minutes=True) assert '167:59:59' ==",
"== eta_hms(3599) assert '1:00:00' == eta_hms(3600) assert '1:00:01' == eta_hms(3601) assert '1:01:01' ==",
"always_show_minutes=True) assert '01:00' == eta_hms(60, hours_leading_zero=True, always_show_minutes=True) assert '01:01' == eta_hms(61, hours_leading_zero=True, always_show_minutes=True)",
"assert '1:01:01' == eta_hms(3661, always_show_hours=True) assert '167:59:59' == eta_hms(604799, always_show_hours=True) assert '168:00:00' ==",
"always_show_hours=True) assert '00:59:59' == eta_hms(3599, hours_leading_zero=True, always_show_hours=True) assert '01:00:00' == eta_hms(3600, hours_leading_zero=True, always_show_hours=True)",
"assert '01:01:01' == eta_hms(3661, hours_leading_zero=True, always_show_hours=True) assert '167:59:59' == eta_hms(604799, hours_leading_zero=True, always_show_hours=True) assert",
"== eta_hms(3599, hours_leading_zero=True, always_show_hours=True) assert '01:00:00' == eta_hms(3600, hours_leading_zero=True, always_show_hours=True) assert '01:00:01' ==",
"'167:59:59' == eta_hms(604799, always_show_hours=True) assert '168:00:00' == eta_hms(604800, always_show_hours=True) assert '168:00:01' == eta_hms(604801,",
"eta_hms(604799, always_show_hours=True) assert '168:00:00' == eta_hms(604800, always_show_hours=True) assert '168:00:01' == eta_hms(604801, always_show_hours=True) #",
"def test_always_show_hours(): assert '0:00:00' == eta_hms(0, always_show_hours=True) assert '0:00:09' == eta_hms(9, always_show_hours=True) assert",
"== eta_hms(61, hours_leading_zero=True, always_show_hours=True) assert '00:59:59' == eta_hms(3599, hours_leading_zero=True, always_show_hours=True) assert '01:00:00' ==",
"hours_leading_zero=True) assert '167:59:59' == eta_hms(604799, hours_leading_zero=True) assert '168:00:00' == eta_hms(604800, hours_leading_zero=True) assert '168:00:01'",
"eta_hms(61) assert '59:59' == eta_hms(3599) assert '1:00:00' == eta_hms(3600) assert '1:00:01' == eta_hms(3601)",
"== eta_hms(3601, hours_leading_zero=True, always_show_hours=True) assert '01:01:01' == eta_hms(3661, hours_leading_zero=True, always_show_hours=True) assert '167:59:59' ==",
"'168:00:01' == eta_hms(604801, always_show_hours=True) # The rest is mostly copy/pasted. ############################################ def test_hours_leading_zero():",
"== eta_hms(3661, always_show_hours=True) assert '167:59:59' == eta_hms(604799, always_show_hours=True) assert '168:00:00' == eta_hms(604800, always_show_hours=True)",
"always_show_minutes=True) assert '59:59' == eta_hms(3599, hours_leading_zero=True, always_show_minutes=True) assert '01:00:00' == eta_hms(3600, hours_leading_zero=True, always_show_minutes=True)"
] |
[
"chosen metric. Parameters ---------- scores : pandas.DataFrame Scores containing the `epoch` column and",
"training and validation scores will be plotted for the chosen metric. Parameters ----------",
"\"\"\"Display a metric vs. epochs plot. Both the training and validation scores will",
"scores[f'val_{metric}'].values.tolist(), 'b', label=f'Validation {metric}') plt.title(f'Training and Validation {metric.title()} for ' f'Iteration {nth_iter} Fold",
"such as `acc`, `loss`, `val_acc`, and `val_loss`. metric : string The metric to",
"random search iteration. nth_fold : int The current k-fold fold. Returns ------- None",
"or 'acc' (note that `val_` is also appended automatically and should not be",
"nth_iter, nth_fold): \"\"\"Display a metric vs. epochs plot. Both the training and validation",
"string The metric to display, such as 'loss' or 'acc' (note that `val_`",
"display, such as 'loss' or 'acc' (note that `val_` is also appended automatically",
"plt.title(f'Training and Validation {metric.title()} for ' f'Iteration {nth_iter} Fold {nth_fold}') plt.legend() plt.ylabel(metric.title()) plt.xlabel('Number",
"fold. Returns ------- None \"\"\" metric_fold_scores = scores[metric].values.tolist() epochs = range(1, len(metric_fold_scores) +",
": string The metric to display, such as 'loss' or 'acc' (note that",
"plt.figure(figsize=(6,4)) plt.plot(epochs, metric_fold_scores, 'bo', label=f'Training {metric}') plt.plot(epochs, scores[f'val_{metric}'].values.tolist(), 'b', label=f'Validation {metric}') plt.title(f'Training and",
"'loss' or 'acc' (note that `val_` is also appended automatically and should not",
"`val_` is also appended automatically and should not be provided). nth_iter : int",
"vs. epochs plot. Both the training and validation scores will be plotted for",
"`acc`, `loss`, `val_acc`, and `val_loss`. metric : string The metric to display, such",
"scores[metric].values.tolist() epochs = range(1, len(metric_fold_scores) + 1) plt.figure(figsize=(6,4)) plt.plot(epochs, metric_fold_scores, 'bo', label=f'Training {metric}')",
"The metric to display, such as 'loss' or 'acc' (note that `val_` is",
"label=f'Training {metric}') plt.plot(epochs, scores[f'val_{metric}'].values.tolist(), 'b', label=f'Validation {metric}') plt.title(f'Training and Validation {metric.title()} for '",
"and Validation {metric.title()} for ' f'Iteration {nth_iter} Fold {nth_fold}') plt.legend() plt.ylabel(metric.title()) plt.xlabel('Number of",
"such as 'loss' or 'acc' (note that `val_` is also appended automatically and",
": int The current random search iteration. nth_fold : int The current k-fold",
"should not be provided). nth_iter : int The current random search iteration. nth_fold",
"validation scores will be plotted for the chosen metric. Parameters ---------- scores :",
"the training and validation scores will be plotted for the chosen metric. Parameters",
"label=f'Validation {metric}') plt.title(f'Training and Validation {metric.title()} for ' f'Iteration {nth_iter} Fold {nth_fold}') plt.legend()",
"column and metric columns such as `acc`, `loss`, `val_acc`, and `val_loss`. metric :",
"iteration. nth_fold : int The current k-fold fold. Returns ------- None \"\"\" metric_fold_scores",
"None \"\"\" metric_fold_scores = scores[metric].values.tolist() epochs = range(1, len(metric_fold_scores) + 1) plt.figure(figsize=(6,4)) plt.plot(epochs,",
"Parameters ---------- scores : pandas.DataFrame Scores containing the `epoch` column and metric columns",
"Scores containing the `epoch` column and metric columns such as `acc`, `loss`, `val_acc`,",
"plotted for the chosen metric. Parameters ---------- scores : pandas.DataFrame Scores containing the",
"metric, nth_iter, nth_fold): \"\"\"Display a metric vs. epochs plot. Both the training and",
"be plotted for the chosen metric. Parameters ---------- scores : pandas.DataFrame Scores containing",
"also appended automatically and should not be provided). nth_iter : int The current",
"Returns ------- None \"\"\" metric_fold_scores = scores[metric].values.tolist() epochs = range(1, len(metric_fold_scores) + 1)",
"len(metric_fold_scores) + 1) plt.figure(figsize=(6,4)) plt.plot(epochs, metric_fold_scores, 'bo', label=f'Training {metric}') plt.plot(epochs, scores[f'val_{metric}'].values.tolist(), 'b', label=f'Validation",
"epochs plot. Both the training and validation scores will be plotted for the",
"and validation scores will be plotted for the chosen metric. Parameters ---------- scores",
"as `acc`, `loss`, `val_acc`, and `val_loss`. metric : string The metric to display,",
"int The current k-fold fold. Returns ------- None \"\"\" metric_fold_scores = scores[metric].values.tolist() epochs",
"search iteration. nth_fold : int The current k-fold fold. Returns ------- None \"\"\"",
"not be provided). nth_iter : int The current random search iteration. nth_fold :",
"The current random search iteration. nth_fold : int The current k-fold fold. Returns",
"metric columns such as `acc`, `loss`, `val_acc`, and `val_loss`. metric : string The",
"a metric vs. epochs plot. Both the training and validation scores will be",
"metric_fold_scores, 'bo', label=f'Training {metric}') plt.plot(epochs, scores[f'val_{metric}'].values.tolist(), 'b', label=f'Validation {metric}') plt.title(f'Training and Validation {metric.title()}",
"containing the `epoch` column and metric columns such as `acc`, `loss`, `val_acc`, and",
"'bo', label=f'Training {metric}') plt.plot(epochs, scores[f'val_{metric}'].values.tolist(), 'b', label=f'Validation {metric}') plt.title(f'Training and Validation {metric.title()} for",
"import matplotlib.pyplot as plt def display_metric_vs_epochs_plot(scores, metric, nth_iter, nth_fold): \"\"\"Display a metric vs.",
"scores will be plotted for the chosen metric. Parameters ---------- scores : pandas.DataFrame",
"provided). nth_iter : int The current random search iteration. nth_fold : int The",
"the chosen metric. Parameters ---------- scores : pandas.DataFrame Scores containing the `epoch` column",
"---------- scores : pandas.DataFrame Scores containing the `epoch` column and metric columns such",
"plt def display_metric_vs_epochs_plot(scores, metric, nth_iter, nth_fold): \"\"\"Display a metric vs. epochs plot. Both",
"automatically and should not be provided). nth_iter : int The current random search",
": int The current k-fold fold. Returns ------- None \"\"\" metric_fold_scores = scores[metric].values.tolist()",
"will be plotted for the chosen metric. Parameters ---------- scores : pandas.DataFrame Scores",
"+ 1) plt.figure(figsize=(6,4)) plt.plot(epochs, metric_fold_scores, 'bo', label=f'Training {metric}') plt.plot(epochs, scores[f'val_{metric}'].values.tolist(), 'b', label=f'Validation {metric}')",
"`loss`, `val_acc`, and `val_loss`. metric : string The metric to display, such as",
"appended automatically and should not be provided). nth_iter : int The current random",
"as plt def display_metric_vs_epochs_plot(scores, metric, nth_iter, nth_fold): \"\"\"Display a metric vs. epochs plot.",
"`val_loss`. metric : string The metric to display, such as 'loss' or 'acc'",
": pandas.DataFrame Scores containing the `epoch` column and metric columns such as `acc`,",
"------- None \"\"\" metric_fold_scores = scores[metric].values.tolist() epochs = range(1, len(metric_fold_scores) + 1) plt.figure(figsize=(6,4))",
"and metric columns such as `acc`, `loss`, `val_acc`, and `val_loss`. metric : string",
"metric vs. epochs plot. Both the training and validation scores will be plotted",
"`epoch` column and metric columns such as `acc`, `loss`, `val_acc`, and `val_loss`. metric",
"range(1, len(metric_fold_scores) + 1) plt.figure(figsize=(6,4)) plt.plot(epochs, metric_fold_scores, 'bo', label=f'Training {metric}') plt.plot(epochs, scores[f'val_{metric}'].values.tolist(), 'b',",
"to display, such as 'loss' or 'acc' (note that `val_` is also appended",
"display_metric_vs_epochs_plot(scores, metric, nth_iter, nth_fold): \"\"\"Display a metric vs. epochs plot. Both the training",
"epochs = range(1, len(metric_fold_scores) + 1) plt.figure(figsize=(6,4)) plt.plot(epochs, metric_fold_scores, 'bo', label=f'Training {metric}') plt.plot(epochs,",
"k-fold fold. Returns ------- None \"\"\" metric_fold_scores = scores[metric].values.tolist() epochs = range(1, len(metric_fold_scores)",
"nth_iter : int The current random search iteration. nth_fold : int The current",
"{metric}') plt.title(f'Training and Validation {metric.title()} for ' f'Iteration {nth_iter} Fold {nth_fold}') plt.legend() plt.ylabel(metric.title())",
"metric to display, such as 'loss' or 'acc' (note that `val_` is also",
"as 'loss' or 'acc' (note that `val_` is also appended automatically and should",
"the `epoch` column and metric columns such as `acc`, `loss`, `val_acc`, and `val_loss`.",
"and `val_loss`. metric : string The metric to display, such as 'loss' or",
"nth_fold): \"\"\"Display a metric vs. epochs plot. Both the training and validation scores",
"is also appended automatically and should not be provided). nth_iter : int The",
"plt.plot(epochs, scores[f'val_{metric}'].values.tolist(), 'b', label=f'Validation {metric}') plt.title(f'Training and Validation {metric.title()} for ' f'Iteration {nth_iter}",
"= scores[metric].values.tolist() epochs = range(1, len(metric_fold_scores) + 1) plt.figure(figsize=(6,4)) plt.plot(epochs, metric_fold_scores, 'bo', label=f'Training",
"plot. Both the training and validation scores will be plotted for the chosen",
"int The current random search iteration. nth_fold : int The current k-fold fold.",
"'acc' (note that `val_` is also appended automatically and should not be provided).",
"scores : pandas.DataFrame Scores containing the `epoch` column and metric columns such as",
"Validation {metric.title()} for ' f'Iteration {nth_iter} Fold {nth_fold}') plt.legend() plt.ylabel(metric.title()) plt.xlabel('Number of Epochs')",
"matplotlib.pyplot as plt def display_metric_vs_epochs_plot(scores, metric, nth_iter, nth_fold): \"\"\"Display a metric vs. epochs",
"(note that `val_` is also appended automatically and should not be provided). nth_iter",
"{metric.title()} for ' f'Iteration {nth_iter} Fold {nth_fold}') plt.legend() plt.ylabel(metric.title()) plt.xlabel('Number of Epochs') plt.show()",
"'b', label=f'Validation {metric}') plt.title(f'Training and Validation {metric.title()} for ' f'Iteration {nth_iter} Fold {nth_fold}')",
"metric_fold_scores = scores[metric].values.tolist() epochs = range(1, len(metric_fold_scores) + 1) plt.figure(figsize=(6,4)) plt.plot(epochs, metric_fold_scores, 'bo',",
"that `val_` is also appended automatically and should not be provided). nth_iter :",
"and should not be provided). nth_iter : int The current random search iteration.",
"The current k-fold fold. Returns ------- None \"\"\" metric_fold_scores = scores[metric].values.tolist() epochs =",
"1) plt.figure(figsize=(6,4)) plt.plot(epochs, metric_fold_scores, 'bo', label=f'Training {metric}') plt.plot(epochs, scores[f'val_{metric}'].values.tolist(), 'b', label=f'Validation {metric}') plt.title(f'Training",
"Both the training and validation scores will be plotted for the chosen metric.",
"plt.plot(epochs, metric_fold_scores, 'bo', label=f'Training {metric}') plt.plot(epochs, scores[f'val_{metric}'].values.tolist(), 'b', label=f'Validation {metric}') plt.title(f'Training and Validation",
"nth_fold : int The current k-fold fold. Returns ------- None \"\"\" metric_fold_scores =",
"metric : string The metric to display, such as 'loss' or 'acc' (note",
"def display_metric_vs_epochs_plot(scores, metric, nth_iter, nth_fold): \"\"\"Display a metric vs. epochs plot. Both the",
"pandas.DataFrame Scores containing the `epoch` column and metric columns such as `acc`, `loss`,",
"columns such as `acc`, `loss`, `val_acc`, and `val_loss`. metric : string The metric",
"= range(1, len(metric_fold_scores) + 1) plt.figure(figsize=(6,4)) plt.plot(epochs, metric_fold_scores, 'bo', label=f'Training {metric}') plt.plot(epochs, scores[f'val_{metric}'].values.tolist(),",
"be provided). nth_iter : int The current random search iteration. nth_fold : int",
"metric. Parameters ---------- scores : pandas.DataFrame Scores containing the `epoch` column and metric",
"`val_acc`, and `val_loss`. metric : string The metric to display, such as 'loss'",
"{metric}') plt.plot(epochs, scores[f'val_{metric}'].values.tolist(), 'b', label=f'Validation {metric}') plt.title(f'Training and Validation {metric.title()} for ' f'Iteration",
"current k-fold fold. Returns ------- None \"\"\" metric_fold_scores = scores[metric].values.tolist() epochs = range(1,",
"current random search iteration. nth_fold : int The current k-fold fold. Returns -------",
"\"\"\" metric_fold_scores = scores[metric].values.tolist() epochs = range(1, len(metric_fold_scores) + 1) plt.figure(figsize=(6,4)) plt.plot(epochs, metric_fold_scores,",
"for the chosen metric. Parameters ---------- scores : pandas.DataFrame Scores containing the `epoch`"
] |
[
"asset self.amount = amount @classmethod def get_fields(cls): return { 1: ('source_account', p.UnicodeType, 0),",
"('source_account', p.UnicodeType, 0), 2: ('destination_account', p.UnicodeType, 0), 3: ('asset', StellarAssetType, 0), 4: ('amount',",
"StellarAssetType class StellarPaymentOp(p.MessageType): MESSAGE_WIRE_TYPE = 211 def __init__( self, source_account: str = None,",
"0), 2: ('destination_account', p.UnicodeType, 0), 3: ('asset', StellarAssetType, 0), 4: ('amount', p.SVarintType, 0),",
"1: ('source_account', p.UnicodeType, 0), 2: ('destination_account', p.UnicodeType, 0), 3: ('asset', StellarAssetType, 0), 4:",
"@classmethod def get_fields(cls): return { 1: ('source_account', p.UnicodeType, 0), 2: ('destination_account', p.UnicodeType, 0),",
"= source_account self.destination_account = destination_account self.asset = asset self.amount = amount @classmethod def",
"-> None: self.source_account = source_account self.destination_account = destination_account self.asset = asset self.amount =",
"{ 1: ('source_account', p.UnicodeType, 0), 2: ('destination_account', p.UnicodeType, 0), 3: ('asset', StellarAssetType, 0),",
"self.amount = amount @classmethod def get_fields(cls): return { 1: ('source_account', p.UnicodeType, 0), 2:",
"None, ) -> None: self.source_account = source_account self.destination_account = destination_account self.asset = asset",
"None: self.source_account = source_account self.destination_account = destination_account self.asset = asset self.amount = amount",
"source_account: str = None, destination_account: str = None, asset: StellarAssetType = None, amount:",
"by pb2py # fmt: off import protobuf as p from .StellarAssetType import StellarAssetType",
"= 211 def __init__( self, source_account: str = None, destination_account: str = None,",
"from .StellarAssetType import StellarAssetType class StellarPaymentOp(p.MessageType): MESSAGE_WIRE_TYPE = 211 def __init__( self, source_account:",
"= None, asset: StellarAssetType = None, amount: int = None, ) -> None:",
"as p from .StellarAssetType import StellarAssetType class StellarPaymentOp(p.MessageType): MESSAGE_WIRE_TYPE = 211 def __init__(",
"self.destination_account = destination_account self.asset = asset self.amount = amount @classmethod def get_fields(cls): return",
"self.asset = asset self.amount = amount @classmethod def get_fields(cls): return { 1: ('source_account',",
"= None, amount: int = None, ) -> None: self.source_account = source_account self.destination_account",
"Automatically generated by pb2py # fmt: off import protobuf as p from .StellarAssetType",
"StellarAssetType = None, amount: int = None, ) -> None: self.source_account = source_account",
".StellarAssetType import StellarAssetType class StellarPaymentOp(p.MessageType): MESSAGE_WIRE_TYPE = 211 def __init__( self, source_account: str",
"int = None, ) -> None: self.source_account = source_account self.destination_account = destination_account self.asset",
"p.UnicodeType, 0), 2: ('destination_account', p.UnicodeType, 0), 3: ('asset', StellarAssetType, 0), 4: ('amount', p.SVarintType,",
"StellarPaymentOp(p.MessageType): MESSAGE_WIRE_TYPE = 211 def __init__( self, source_account: str = None, destination_account: str",
"amount: int = None, ) -> None: self.source_account = source_account self.destination_account = destination_account",
"# fmt: off import protobuf as p from .StellarAssetType import StellarAssetType class StellarPaymentOp(p.MessageType):",
"2: ('destination_account', p.UnicodeType, 0), 3: ('asset', StellarAssetType, 0), 4: ('amount', p.SVarintType, 0), }",
"class StellarPaymentOp(p.MessageType): MESSAGE_WIRE_TYPE = 211 def __init__( self, source_account: str = None, destination_account:",
"str = None, asset: StellarAssetType = None, amount: int = None, ) ->",
"source_account self.destination_account = destination_account self.asset = asset self.amount = amount @classmethod def get_fields(cls):",
"def get_fields(cls): return { 1: ('source_account', p.UnicodeType, 0), 2: ('destination_account', p.UnicodeType, 0), 3:",
"str = None, destination_account: str = None, asset: StellarAssetType = None, amount: int",
"generated by pb2py # fmt: off import protobuf as p from .StellarAssetType import",
"None, destination_account: str = None, asset: StellarAssetType = None, amount: int = None,",
"destination_account: str = None, asset: StellarAssetType = None, amount: int = None, )",
"= None, ) -> None: self.source_account = source_account self.destination_account = destination_account self.asset =",
"self.source_account = source_account self.destination_account = destination_account self.asset = asset self.amount = amount @classmethod",
"MESSAGE_WIRE_TYPE = 211 def __init__( self, source_account: str = None, destination_account: str =",
"= destination_account self.asset = asset self.amount = amount @classmethod def get_fields(cls): return {",
"import StellarAssetType class StellarPaymentOp(p.MessageType): MESSAGE_WIRE_TYPE = 211 def __init__( self, source_account: str =",
"__init__( self, source_account: str = None, destination_account: str = None, asset: StellarAssetType =",
"off import protobuf as p from .StellarAssetType import StellarAssetType class StellarPaymentOp(p.MessageType): MESSAGE_WIRE_TYPE =",
"self, source_account: str = None, destination_account: str = None, asset: StellarAssetType = None,",
"None, amount: int = None, ) -> None: self.source_account = source_account self.destination_account =",
"# Automatically generated by pb2py # fmt: off import protobuf as p from",
"= amount @classmethod def get_fields(cls): return { 1: ('source_account', p.UnicodeType, 0), 2: ('destination_account',",
"get_fields(cls): return { 1: ('source_account', p.UnicodeType, 0), 2: ('destination_account', p.UnicodeType, 0), 3: ('asset',",
"destination_account self.asset = asset self.amount = amount @classmethod def get_fields(cls): return { 1:",
"None, asset: StellarAssetType = None, amount: int = None, ) -> None: self.source_account",
"return { 1: ('source_account', p.UnicodeType, 0), 2: ('destination_account', p.UnicodeType, 0), 3: ('asset', StellarAssetType,",
"= asset self.amount = amount @classmethod def get_fields(cls): return { 1: ('source_account', p.UnicodeType,",
"= None, destination_account: str = None, asset: StellarAssetType = None, amount: int =",
") -> None: self.source_account = source_account self.destination_account = destination_account self.asset = asset self.amount",
"amount @classmethod def get_fields(cls): return { 1: ('source_account', p.UnicodeType, 0), 2: ('destination_account', p.UnicodeType,",
"211 def __init__( self, source_account: str = None, destination_account: str = None, asset:",
"def __init__( self, source_account: str = None, destination_account: str = None, asset: StellarAssetType",
"asset: StellarAssetType = None, amount: int = None, ) -> None: self.source_account =",
"fmt: off import protobuf as p from .StellarAssetType import StellarAssetType class StellarPaymentOp(p.MessageType): MESSAGE_WIRE_TYPE",
"pb2py # fmt: off import protobuf as p from .StellarAssetType import StellarAssetType class",
"import protobuf as p from .StellarAssetType import StellarAssetType class StellarPaymentOp(p.MessageType): MESSAGE_WIRE_TYPE = 211",
"protobuf as p from .StellarAssetType import StellarAssetType class StellarPaymentOp(p.MessageType): MESSAGE_WIRE_TYPE = 211 def",
"p from .StellarAssetType import StellarAssetType class StellarPaymentOp(p.MessageType): MESSAGE_WIRE_TYPE = 211 def __init__( self,"
] |
[
"dp or len(dp[newSkills]) > len(team) + 1: dp[newSkills] = team + [i] return",
"p: if s in table: curr |= table[s] for skills, team in list(dp.items()):",
"i) for i, skill in enumerate(req_skills)} dp = {0 : []} for i,",
"s in p: if s in table: curr |= table[s] for skills, team",
"in table: curr |= table[s] for skills, team in list(dp.items()): newSkills = skills",
"List[str], people: List[List[str]]) -> List[int]: table = {skill : (1 << i) for",
"= {0 : []} for i, p in enumerate(people): curr = 0 for",
"= 0 for s in p: if s in table: curr |= table[s]",
"|= table[s] for skills, team in list(dp.items()): newSkills = skills | curr if",
"table[s] for skills, team in list(dp.items()): newSkills = skills | curr if newSkills",
"curr if newSkills != skills: if newSkills not in dp or len(dp[newSkills]) >",
"> len(team) + 1: dp[newSkills] = team + [i] return dp[(1 << len(req_skills))",
"+ 1: dp[newSkills] = team + [i] return dp[(1 << len(req_skills)) - 1]",
"s in table: curr |= table[s] for skills, team in list(dp.items()): newSkills =",
"table: curr |= table[s] for skills, team in list(dp.items()): newSkills = skills |",
"skills: if newSkills not in dp or len(dp[newSkills]) > len(team) + 1: dp[newSkills]",
"in enumerate(req_skills)} dp = {0 : []} for i, p in enumerate(people): curr",
"in dp or len(dp[newSkills]) > len(team) + 1: dp[newSkills] = team + [i]",
"table = {skill : (1 << i) for i, skill in enumerate(req_skills)} dp",
": (1 << i) for i, skill in enumerate(req_skills)} dp = {0 :",
"in p: if s in table: curr |= table[s] for skills, team in",
"{0 : []} for i, p in enumerate(people): curr = 0 for s",
"List[int]: table = {skill : (1 << i) for i, skill in enumerate(req_skills)}",
"len(dp[newSkills]) > len(team) + 1: dp[newSkills] = team + [i] return dp[(1 <<",
"newSkills not in dp or len(dp[newSkills]) > len(team) + 1: dp[newSkills] = team",
"for i, skill in enumerate(req_skills)} dp = {0 : []} for i, p",
"in list(dp.items()): newSkills = skills | curr if newSkills != skills: if newSkills",
"people: List[List[str]]) -> List[int]: table = {skill : (1 << i) for i,",
"Solution: def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]: table = {skill :",
"= {skill : (1 << i) for i, skill in enumerate(req_skills)} dp =",
"def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]: table = {skill : (1",
"skills | curr if newSkills != skills: if newSkills not in dp or",
"not in dp or len(dp[newSkills]) > len(team) + 1: dp[newSkills] = team +",
"team in list(dp.items()): newSkills = skills | curr if newSkills != skills: if",
"| curr if newSkills != skills: if newSkills not in dp or len(dp[newSkills])",
"enumerate(req_skills)} dp = {0 : []} for i, p in enumerate(people): curr =",
"0 for s in p: if s in table: curr |= table[s] for",
"<gh_stars>10-100 class Solution: def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]: table =",
"enumerate(people): curr = 0 for s in p: if s in table: curr",
"p in enumerate(people): curr = 0 for s in p: if s in",
"for s in p: if s in table: curr |= table[s] for skills,",
"skill in enumerate(req_skills)} dp = {0 : []} for i, p in enumerate(people):",
"<< i) for i, skill in enumerate(req_skills)} dp = {0 : []} for",
"for i, p in enumerate(people): curr = 0 for s in p: if",
"req_skills: List[str], people: List[List[str]]) -> List[int]: table = {skill : (1 << i)",
"newSkills != skills: if newSkills not in dp or len(dp[newSkills]) > len(team) +",
"if newSkills not in dp or len(dp[newSkills]) > len(team) + 1: dp[newSkills] =",
"!= skills: if newSkills not in dp or len(dp[newSkills]) > len(team) + 1:",
"skills, team in list(dp.items()): newSkills = skills | curr if newSkills != skills:",
"i, skill in enumerate(req_skills)} dp = {0 : []} for i, p in",
"smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]: table = {skill : (1 <<",
"or len(dp[newSkills]) > len(team) + 1: dp[newSkills] = team + [i] return dp[(1",
"(1 << i) for i, skill in enumerate(req_skills)} dp = {0 : []}",
"if newSkills != skills: if newSkills not in dp or len(dp[newSkills]) > len(team)",
"{skill : (1 << i) for i, skill in enumerate(req_skills)} dp = {0",
"curr = 0 for s in p: if s in table: curr |=",
"curr |= table[s] for skills, team in list(dp.items()): newSkills = skills | curr",
"in enumerate(people): curr = 0 for s in p: if s in table:",
"newSkills = skills | curr if newSkills != skills: if newSkills not in",
": []} for i, p in enumerate(people): curr = 0 for s in",
"i, p in enumerate(people): curr = 0 for s in p: if s",
"for skills, team in list(dp.items()): newSkills = skills | curr if newSkills !=",
"len(team) + 1: dp[newSkills] = team + [i] return dp[(1 << len(req_skills)) -",
"dp = {0 : []} for i, p in enumerate(people): curr = 0",
"class Solution: def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]: table = {skill",
"[]} for i, p in enumerate(people): curr = 0 for s in p:",
"-> List[int]: table = {skill : (1 << i) for i, skill in",
"list(dp.items()): newSkills = skills | curr if newSkills != skills: if newSkills not",
"List[List[str]]) -> List[int]: table = {skill : (1 << i) for i, skill",
"= skills | curr if newSkills != skills: if newSkills not in dp",
"if s in table: curr |= table[s] for skills, team in list(dp.items()): newSkills"
] |
[
"for x in line.split(', ')] # data = [x for x in line]",
"in enumerate(fileinput.input()): line = line.strip() # data = [x for x in line.split(',",
"# product('ABCD', repeat=2) AA AB AC AD BA BB BC BD CA CB",
"permutations('ABCD', 2) AB AC AD BA BC BD CA CB CD DA DB",
"DD # permutations('ABCD', 2) AB AC AD BA BC BD CA CB CD",
"total = 0 result = [] table = new_table(None, width=2, height=4) for i,",
"AB AC AD BC BD CD # combinations_with_replacement('ABCD', 2) AA AB AC AD",
"x in line.split(', ')] # data = [x for x in line] #",
"# NOQA from itertools import count, product, permutations, combinations, combinations_with_replacement # NOQA from",
"permutations, combinations, combinations_with_replacement # NOQA from utils import parse_line, mul, factors, memoize, primes,",
"x in line.split()] # data = re.findall(r'(\\w+)', line) data = parse_line(r'', line) if",
"BD CA CB CD DA DB DC # combinations('ABCD', 2) AB AC AD",
"memoize, primes, new_table, Point # NOQA # Itertools Functions: # product('ABCD', repeat=2) AA",
"from collections import Counter, deque, namedtuple # NOQA from itertools import count, product,",
"# data = [x for x in line.split(', ')] # data = [x",
"BD CA CB CC CD DA DB DC DD # permutations('ABCD', 2) AB",
"utils import parse_line, mul, factors, memoize, primes, new_table, Point # NOQA # Itertools",
"CD DD total = 0 result = [] table = new_table(None, width=2, height=4)",
"AB AC AD BA BC BD CA CB CD DA DB DC #",
"namedtuple # NOQA from itertools import count, product, permutations, combinations, combinations_with_replacement # NOQA",
"BC BD CA CB CC CD DA DB DC DD # permutations('ABCD', 2)",
"factors, memoize, primes, new_table, Point # NOQA # Itertools Functions: # product('ABCD', repeat=2)",
"2) AA AB AC AD BB BC BD CC CD DD total =",
"Functions: # product('ABCD', repeat=2) AA AB AC AD BA BB BC BD CA",
"')] # data = [x for x in line] # data = [int(x)",
"BC BD CA CB CD DA DB DC # combinations('ABCD', 2) AB AC",
"os # NOQA import sys # NOQA import re # NOQA import math",
"# NOQA import re # NOQA import math # NOQA import fileinput from",
"import parse_line, mul, factors, memoize, primes, new_table, Point # NOQA # Itertools Functions:",
"# data = [int(x) for x in line.split()] # data = re.findall(r'(\\w+)', line)",
"import count, product, permutations, combinations, combinations_with_replacement # NOQA from utils import parse_line, mul,",
"from utils import parse_line, mul, factors, memoize, primes, new_table, Point # NOQA #",
"# combinations('ABCD', 2) AB AC AD BC BD CD # combinations_with_replacement('ABCD', 2) AA",
"CD # combinations_with_replacement('ABCD', 2) AA AB AC AD BB BC BD CC CD",
"new_table, Point # NOQA # Itertools Functions: # product('ABCD', repeat=2) AA AB AC",
"NOQA import math # NOQA import fileinput from collections import Counter, deque, namedtuple",
"product('ABCD', repeat=2) AA AB AC AD BA BB BC BD CA CB CC",
"CB CD DA DB DC # combinations('ABCD', 2) AB AC AD BC BD",
"CC CD DD total = 0 result = [] table = new_table(None, width=2,",
"for x in line] # data = [int(x) for x in line.split()] #",
"BB BC BD CA CB CC CD DA DB DC DD # permutations('ABCD',",
"Itertools Functions: # product('ABCD', repeat=2) AA AB AC AD BA BB BC BD",
"combinations_with_replacement('ABCD', 2) AA AB AC AD BB BC BD CC CD DD total",
"= 0 result = [] table = new_table(None, width=2, height=4) for i, line",
"[x for x in line] # data = [int(x) for x in line.split()]",
"NOQA import sys # NOQA import re # NOQA import math # NOQA",
"BB BC BD CC CD DD total = 0 result = [] table",
"for x in line.split()] # data = re.findall(r'(\\w+)', line) data = parse_line(r'', line)",
"= [x for x in line.split(', ')] # data = [x for x",
"NOQA # Itertools Functions: # product('ABCD', repeat=2) AA AB AC AD BA BB",
"data = [x for x in line] # data = [int(x) for x",
"[int(x) for x in line.split()] # data = re.findall(r'(\\w+)', line) data = parse_line(r'',",
"[] table = new_table(None, width=2, height=4) for i, line in enumerate(fileinput.input()): line =",
"Point # NOQA # Itertools Functions: # product('ABCD', repeat=2) AA AB AC AD",
"line] # data = [int(x) for x in line.split()] # data = re.findall(r'(\\w+)',",
"line.split(', ')] # data = [x for x in line] # data =",
"CA CB CD DA DB DC # combinations('ABCD', 2) AB AC AD BC",
"sys # NOQA import re # NOQA import math # NOQA import fileinput",
"# NOQA import math # NOQA import fileinput from collections import Counter, deque,",
"from itertools import count, product, permutations, combinations, combinations_with_replacement # NOQA from utils import",
"AA AB AC AD BA BB BC BD CA CB CC CD DA",
"AD BA BB BC BD CA CB CC CD DA DB DC DD",
"enumerate(fileinput.input()): line = line.strip() # data = [x for x in line.split(', ')]",
"result = [] table = new_table(None, width=2, height=4) for i, line in enumerate(fileinput.input()):",
"= line.strip() # data = [x for x in line.split(', ')] # data",
"i, line in enumerate(fileinput.input()): line = line.strip() # data = [x for x",
"# Itertools Functions: # product('ABCD', repeat=2) AA AB AC AD BA BB BC",
"BA BC BD CA CB CD DA DB DC # combinations('ABCD', 2) AB",
"BC BD CC CD DD total = 0 result = [] table =",
"in line.split()] # data = re.findall(r'(\\w+)', line) data = parse_line(r'', line) if i",
"table = new_table(None, width=2, height=4) for i, line in enumerate(fileinput.input()): line = line.strip()",
"data = [x for x in line.split(', ')] # data = [x for",
"# NOQA from utils import parse_line, mul, factors, memoize, primes, new_table, Point #",
"parse_line, mul, factors, memoize, primes, new_table, Point # NOQA # Itertools Functions: #",
"CD DA DB DC # combinations('ABCD', 2) AB AC AD BC BD CD",
"line.split()] # data = re.findall(r'(\\w+)', line) data = parse_line(r'', line) if i ==",
"import fileinput from collections import Counter, deque, namedtuple # NOQA from itertools import",
"AD BB BC BD CC CD DD total = 0 result = []",
"2) AB AC AD BC BD CD # combinations_with_replacement('ABCD', 2) AA AB AC",
"count, product, permutations, combinations, combinations_with_replacement # NOQA from utils import parse_line, mul, factors,",
"# NOQA import fileinput from collections import Counter, deque, namedtuple # NOQA from",
"deque, namedtuple # NOQA from itertools import count, product, permutations, combinations, combinations_with_replacement #",
"AC AD BA BC BD CA CB CD DA DB DC # combinations('ABCD',",
"CB CC CD DA DB DC DD # permutations('ABCD', 2) AB AC AD",
"CC CD DA DB DC DD # permutations('ABCD', 2) AB AC AD BA",
"DA DB DC # combinations('ABCD', 2) AB AC AD BC BD CD #",
"# NOQA import sys # NOQA import re # NOQA import math #",
"DB DC DD # permutations('ABCD', 2) AB AC AD BA BC BD CA",
"= [x for x in line] # data = [int(x) for x in",
"CA CB CC CD DA DB DC DD # permutations('ABCD', 2) AB AC",
"line in enumerate(fileinput.input()): line = line.strip() # data = [x for x in",
"# data = [x for x in line] # data = [int(x) for",
"# NOQA # Itertools Functions: # product('ABCD', repeat=2) AA AB AC AD BA",
"re # NOQA import math # NOQA import fileinput from collections import Counter,",
"import os # NOQA import sys # NOQA import re # NOQA import",
"AC AD BA BB BC BD CA CB CC CD DA DB DC",
"width=2, height=4) for i, line in enumerate(fileinput.input()): line = line.strip() # data =",
"NOQA import fileinput from collections import Counter, deque, namedtuple # NOQA from itertools",
"BD CC CD DD total = 0 result = [] table = new_table(None,",
"# permutations('ABCD', 2) AB AC AD BA BC BD CA CB CD DA",
"in line] # data = [int(x) for x in line.split()] # data =",
"repeat=2) AA AB AC AD BA BB BC BD CA CB CC CD",
"= [int(x) for x in line.split()] # data = re.findall(r'(\\w+)', line) data =",
"primes, new_table, Point # NOQA # Itertools Functions: # product('ABCD', repeat=2) AA AB",
"import re # NOQA import math # NOQA import fileinput from collections import",
"CD DA DB DC DD # permutations('ABCD', 2) AB AC AD BA BC",
"DB DC # combinations('ABCD', 2) AB AC AD BC BD CD # combinations_with_replacement('ABCD',",
"BD CD # combinations_with_replacement('ABCD', 2) AA AB AC AD BB BC BD CC",
"NOQA import re # NOQA import math # NOQA import fileinput from collections",
"combinations_with_replacement # NOQA from utils import parse_line, mul, factors, memoize, primes, new_table, Point",
"mul, factors, memoize, primes, new_table, Point # NOQA # Itertools Functions: # product('ABCD',",
"DC # combinations('ABCD', 2) AB AC AD BC BD CD # combinations_with_replacement('ABCD', 2)",
"BC BD CD # combinations_with_replacement('ABCD', 2) AA AB AC AD BB BC BD",
"# combinations_with_replacement('ABCD', 2) AA AB AC AD BB BC BD CC CD DD",
"AA AB AC AD BB BC BD CC CD DD total = 0",
"AB AC AD BB BC BD CC CD DD total = 0 result",
"data = [int(x) for x in line.split()] # data = re.findall(r'(\\w+)', line) data",
"NOQA from itertools import count, product, permutations, combinations, combinations_with_replacement # NOQA from utils",
"itertools import count, product, permutations, combinations, combinations_with_replacement # NOQA from utils import parse_line,",
"product, permutations, combinations, combinations_with_replacement # NOQA from utils import parse_line, mul, factors, memoize,",
"0 result = [] table = new_table(None, width=2, height=4) for i, line in",
"= [] table = new_table(None, width=2, height=4) for i, line in enumerate(fileinput.input()): line",
"2) AB AC AD BA BC BD CA CB CD DA DB DC",
"# data = re.findall(r'(\\w+)', line) data = parse_line(r'', line) if i == 0:",
"AD BC BD CD # combinations_with_replacement('ABCD', 2) AA AB AC AD BB BC",
"fileinput from collections import Counter, deque, namedtuple # NOQA from itertools import count,",
"= new_table(None, width=2, height=4) for i, line in enumerate(fileinput.input()): line = line.strip() #",
"NOQA from utils import parse_line, mul, factors, memoize, primes, new_table, Point # NOQA",
"[x for x in line.split(', ')] # data = [x for x in",
"x in line] # data = [int(x) for x in line.split()] # data",
"AC AD BC BD CD # combinations_with_replacement('ABCD', 2) AA AB AC AD BB",
"import sys # NOQA import re # NOQA import math # NOQA import",
"BA BB BC BD CA CB CC CD DA DB DC DD #",
"AB AC AD BA BB BC BD CA CB CC CD DA DB",
"for i, line in enumerate(fileinput.input()): line = line.strip() # data = [x for",
"line = line.strip() # data = [x for x in line.split(', ')] #",
"new_table(None, width=2, height=4) for i, line in enumerate(fileinput.input()): line = line.strip() # data",
"collections import Counter, deque, namedtuple # NOQA from itertools import count, product, permutations,",
"line.strip() # data = [x for x in line.split(', ')] # data =",
"in line.split(', ')] # data = [x for x in line] # data",
"import math # NOQA import fileinput from collections import Counter, deque, namedtuple #",
"AD BA BC BD CA CB CD DA DB DC # combinations('ABCD', 2)",
"math # NOQA import fileinput from collections import Counter, deque, namedtuple # NOQA",
"AC AD BB BC BD CC CD DD total = 0 result =",
"height=4) for i, line in enumerate(fileinput.input()): line = line.strip() # data = [x",
"data = re.findall(r'(\\w+)', line) data = parse_line(r'', line) if i == 0: print(data)",
"DA DB DC DD # permutations('ABCD', 2) AB AC AD BA BC BD",
"combinations('ABCD', 2) AB AC AD BC BD CD # combinations_with_replacement('ABCD', 2) AA AB",
"combinations, combinations_with_replacement # NOQA from utils import parse_line, mul, factors, memoize, primes, new_table,",
"DD total = 0 result = [] table = new_table(None, width=2, height=4) for",
"DC DD # permutations('ABCD', 2) AB AC AD BA BC BD CA CB",
"Counter, deque, namedtuple # NOQA from itertools import count, product, permutations, combinations, combinations_with_replacement",
"import Counter, deque, namedtuple # NOQA from itertools import count, product, permutations, combinations,"
] |
[
"- STN.Y_ijt (batch sizes, float) - STN.Y_st (stored material quantities, float) - STN.Y_st_inflow",
"self.P = np.array([[0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0,",
"solved, transform the solution dictionaries (self.x_ijt, self.y_ijt) into np.arrays for easier inspection/plotting. The",
"80] ) return constraint_kondili def construct_objective(self): \"\"\" Objective encodes c'*(y_s(t=end)-y_s(t=0)), i.e., value of",
"column = task self.J_i = np.array([[1, 0, 0, 0, 0], [0, 1, 1,",
"0, 0]) # objective to maximize (revenue from the states) self.c = np.array([0,",
"nominal schedule. :return: None \"\"\" plot_stn_schedule(self, self.Y_ijt, color=color, style=style) # imported with plotting",
"solution with # constraints.append(self.construct_konidili_solution_enforce()) constraints = sum(constraints, []) # Objective # --------- objective",
"self.C_min = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0]) # objective",
"products minus cost of the input feeds. :return: cvx.Objective \"\"\" return - sum(",
"0, 0, 0, 1]]) # Recipes and timing # fractions of input state",
"0, 2, 0, 0, 2, 0], [0, 0, 0, 0, 0, 0, 1,",
"range(I): for j in range(J): for t in range(T): constraint_allocation.append( self.x_ijt[i,j,t]*(1-self.J_i[i,j]) == 0",
"the nominal schedule. :return: None \"\"\" plot_stn_schedule(self, self.Y_ijt, color=color, style=style) # imported with",
"be added/removed here. :return: None \"\"\" # Constraints # ----------- constraints = []",
"0, 0, 0, 0, 0, 0, 0, 0], [0, 0.5, 0.5, 0, 0,",
"50, 50, 50, 50], [200, 200, 200, 200, 200]]) self.V_min = np.array([[0, 0,",
"0, 1]]) # total execution time of task j (row-wise max of P)",
"box constraints on x_ijt and y_ijt; useful for testing with continuous variables instead",
"j in range(J): for t in range(T): constraint_box.append(self.x_ijt[i,j,t] >= 0) constraint_box.append(self.x_ijt[i,j,t] <= 1)",
"i (row) to process task j (column), in e.g. kg self.V_max = np.array([[100,",
"solution as in the paper (the objective is unaffected) :return: list of cvx.Constraint",
"= [] constraint_kondili.append( [self.y_ijt[0,0,1] == 52] ) constraint_kondili.append( [self.y_ijt[1,1,0] == 80] ) return",
"= data['G'][:,range_cont_ix] self.b_ineq = data['h'] self.b_ineq = data['h'] self.m_eq = self.A_eq.shape[0] self.m_ineq =",
"0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 0,",
"tasks should be started # early enough such that they are completed within",
"'Feed B', 'Feed C', 'Hot A', 'Intermediate AB', 'Intermediate BC', 'Impure E', 'Product",
"self.S = self.states.__len__() self.T = self.horizon # Units capability (what tasks can be",
"[0, 0.5, 0.5, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0.4,",
"# 2) units can only perform tasks that are compatible with self.J_i, and",
"# Recipes and timing # fractions of input state s (column) required to",
"= self.x_ijt[i,j,t].value self.Y_ijt[i,j,t] = self.y_ijt[i,j,t].value for t in range(self.T): for s in range(self.S):",
"axis=1) # Capacities # max capacity of unit i (row) to process task",
"100], [80, 80, 80, 80, 80], [50, 50, 50, 50, 50], [200, 200,",
"produce output state s (column) from task j (row) self.P = np.array([[0, 0,",
"are compatible with self.J_i, and tasks should be started # early enough such",
"of of steps # Aliases self.I = self.units.__len__() self.J = self.tasks.__len__() self.S =",
"= {} # batch size [kg] self.y_s = {} # state quantity [kg]",
"= ['Heat', 'Rea. 1', 'Rea. 2', 'Rea. 3', 'Sep.'] self.states = ['Feed A',",
":return: optimal value (float) \"\"\" print 'Constructing nominal model...' self.construct_nominal_model() print 'Solving...' self.model.solve(verbose=True,",
"0, 0, 0, 1, 0, 0]]) # fractions of output state s (column)",
"'Rea. 3', 'Sep.'] self.states = ['Feed A', 'Feed B', 'Feed C', 'Hot A',",
"/ output state starts with a quantity of 0 kg for s in",
"the matrices of te standard model: data = self.model.get_problem_data('ECOS_BB') self.retrieve_standard_model(data) def retrieve_standard_model(self, data):",
"and can be accessed from there once the method is executed. :return: None",
"Capacities # max capacity of unit i (row) to process task j (column),",
"creation of x_ijt and y_ijt in two loops, so that the optimization variables",
"A_eq*x + B_eq*y = b_eq # A_ineq*x + B_ineq*y <= b_ineq # x",
"structure (cvx.Problem type) self.model = 0 # Optimization Variables # ---------------------- self.x_ijt =",
"within the instance attributes - STN.X_ijt (assignments, bool) - STN.Y_ijt (batch sizes, float)",
"self.model.solve(verbose=True, solver='GUROBI') self.unpack_results() return self.model.value def unpack_results(self): \"\"\" Once model is solved, transform",
"(batch sizes, float) - STN.Y_st (material quantities, float) - STN.Y_st_inflow and Y_st_outflow (material",
"for t in range(self.T): constraint_capacity.append( self.x_ijt[i,j,t]*self.V_min[i,j] <= self.y_ijt[i,j,t] ) constraint_capacity.append( self.y_ijt[i,j,t] <= self.x_ijt[i,j,t]*self.V_max[i,j]",
"in range(T): constraint_allocation.append( self.x_ijt[i,j,t]*(1-self.J_i[i,j]) == 0 ) if t >= T-self.P_j[j]: constraint_allocation.append( self.x_ijt[i,j,t]",
"sizes, float) - STN.Y_st (material quantities, float) - STN.Y_st_inflow and Y_st_outflow (material flows,",
"constraints = sum(constraints, []) # Objective # --------- objective = cvx.Minimize(self.construct_objective()) # Model",
"We pack everything in a class to avoid having to implement functions (now",
"0 self.B_eq = 0 self.B_ineq = 0 self.b_eq = 0 self.b_ineq = 0",
"+ (sum([self.y_st_inflow[s,tt].value for tt in range(t+1)]) - sum([self.y_st_outflow[s,tt].value for tt in range(t+1)])) def",
"self.y_st_outflow[s,t].value self.Y_st[s,t] = self.y_s[s].value + (sum([self.y_st_inflow[s,tt].value for tt in range(t+1)]) - sum([self.y_st_outflow[s,tt].value for",
"state s (column) required to execute task j (row) self.rho_in = np.array([[1, 0,",
"Constructs and solved the nominal STN model. The solution is stored in the",
"+ B_eq*y = b_eq # A_ineq*x + B_ineq*y <= b_ineq # x \\in",
"0, 0.4, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0], [0,",
"with self.J_i, and tasks should be started # early enough such that they",
"# Definition of the STN (order in the list matters!) self.units = ['Heater',",
"0 ) return constraint_allocation def construct_box_constraint(self): \"\"\" Construct box constraints on x_ijt and",
"0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 2, 0,",
"state starts with a quantity of 0 kg for s in range(self.S): if",
"range(t,t+self.P_j[j])], [] ) ) <= self.P_j[j]*BIG_M*(1 - self.x_ijt[(i,j,t)]) + 1 ) # 2)",
"name y_s for s in range(self.S): self.y_s[s] = cvx.Variable() # auxiliary expressions used",
"tt in range(t+1)] )) return constraint_state_eq def construct_konidili_solution_enforce(self): \"\"\" The nominal model with",
"t in range(self.T)]) - sum([self.y_st_outflow[s,t] for t in range(self.T)])) for s in range(self.S)]",
"and STN.Y_st_outflow (material flows, float), and can be accessed from there once the",
") - sum( [self.y_st_outflow[(s,tt)] for tt in range(t+1)] )) constraint_state_eq.append( self.C_max[s] >= self.y_s[s]",
"= self.tasks.__len__() S = self.states.__len__() T = self.T # TODO BIG-M for allocation",
"Objective # --------- objective = cvx.Minimize(self.construct_objective()) # Model # ----- self.model = cvx.Problem(objective,",
"s (column) required to execute task j (row) self.rho_in = np.array([[1, 0, 0,",
"0], [0, 0, 0.2, 0, 0.8, 0, 0, 0, 0], [0, 0, 0,",
"tt in range(t+1)] )) constraint_state_eq.append( self.C_max[s] >= self.y_s[s] + sum( [self.y_st_inflow[(s,tt)] for tt",
"in range(J): for t in range(T): constraint_allocation.append( self.x_ijt[i,j,t]*(1-self.J_i[i,j]) == 0 ) if t",
"perform tasks that are compatible with self.J_i :return: list of cvx.Constraint \"\"\" I",
"# of steps) required to produce output state s (column) from task j",
"etc) with ordered columns. :param data: dictionary, as returned by cvx.Problem.get_problem_data('ECOS_BB') :return: None",
"0 self.A_eq = 0 self.A_ineq = 0 self.B_eq = 0 self.B_ineq = 0",
"0], [0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0,",
"self.Y_st_outflow = np.zeros((self.S,self.T)) # to store the standard model # min c_x'*x +",
"# state equations are eliminated to allow for the robust counterpart. We only",
"= self.units.__len__() self.J = self.tasks.__len__() self.S = self.states.__len__() self.T = self.horizon # Units",
"The np.arrays are saved within the instance attributes - STN.X_ijt (assignments, bool) -",
"STN.Y_st (stored material quantities, float) - STN.Y_st_inflow and STN.Y_st_outflow (material flows, float), and",
"state quantity [kg] for i in range(self.I): for j in range(self.J): for t",
"i is processing at most one task j at each t 2) units",
"constraint_allocation def construct_box_constraint(self): \"\"\" Construct box constraints on x_ijt and y_ijt; useful for",
"t 2) units can only perform tasks that are compatible with self.J_i :return:",
"0, 0, 0.4, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0],",
"most one task j at each t 2) units can only perform tasks",
"matrices (A_eq, B_eq, b_eq, etc) with ordered columns. :param data: dictionary, as returned",
"'robin' \"\"\" Implementation of a scheduling system based on the STN model. The",
"= data['A'][:,range_cont_ix] self.b_eq = data['b'] self.A_ineq = data['G'][:,range_bool_ix] self.B_ineq = data['G'][:,range_cont_ix] self.b_ineq =",
"scheduling system based on the STN model. The data of the problem is",
"steps) required to produce output state s (column) from task j (row) self.P",
"x \\in {0,1} self.c_x = 0 self.c_y = 0 self.A_eq = 0 self.A_ineq",
"np.array([[100, 100, 100, 100, 100], [80, 80, 80, 80, 80], [50, 50, 50,",
"= np.array([[100, 100, 100, 100, 100], [80, 80, 80, 80, 80], [50, 50,",
"1, 0, 0]]) # fractions of output state s (column) produced by task",
"constraint_kondili.append( [self.y_ijt[0,0,1] == 52] ) constraint_kondili.append( [self.y_ijt[1,1,0] == 80] ) return constraint_kondili def",
"of the problem is in the __init__() method, and can be changed. Additional",
"that are compatible with self.J_i :return: list of cvx.Constraint \"\"\" I = self.units.__len__()",
"Constraints # ----------- constraints = [] constraints.append(self.construct_allocation_constraint()) constraints.append(self.construct_units_capacity_constraint()) constraints.append(self.construct_state_equations_and_storage_constraint()) # can force Kondili's",
"in range(self.T): self.y_ijt[i,j,t] = cvx.Variable() # state equations are eliminated to allow for",
") def construct_nominal_model(self): \"\"\" Constructs the nominal STN model, and saves it in",
"# total execution time of task j (row-wise max of P) self.P_j =",
"0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0]])",
"starts with a quantity of 0 kg for s in range(self.S): if s",
"self.x_ijt[i,j,t]*self.V_min[i,j] <= self.y_ijt[i,j,t] ) constraint_capacity.append( self.y_ijt[i,j,t] <= self.x_ijt[i,j,t]*self.V_max[i,j] ) return constraint_capacity def construct_state_equations_and_storage_constraint(self):",
"to store results self.X_ijt = np.zeros((self.I,self.J,self.T)) self.Y_ijt = np.zeros((self.I,self.J,self.T)) self.Y_st = np.zeros((self.S,self.T)) self.Y_st_inflow",
"0, 0, 1]]) # total execution time of task j (row-wise max of",
"+= self.rho_out[j,s]*self.y_ijt[i,j,t-self.P[j,s]] # set outflows self.y_st_outflow[s,t] += self.rho_in[j,s]*self.y_ijt[i,j,t] constraint_state_eq.append( self.C_min[s] <= self.y_s[s] +",
"Constructs the nominal STN model, and saves it in the class attribute self.model",
"(stored material quantities, float) - STN.Y_st_inflow and STN.Y_st_outflow (material flows, float), and can",
"self.y_s[s].value + (sum([self.y_st_inflow[s,tt].value for tt in range(t+1)]) - sum([self.y_st_outflow[s,tt].value for tt in range(t+1)]))",
"stored in the np.arrays - STN.X_ijt (assignments, bool) - STN.Y_ijt (batch sizes, float)",
"0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0,",
"= self.tasks.__len__() T = self.T constraint_box = [] for i in range(I): for",
"'Product 2'] self.input_states = [0, 1, 2] # indices of the input states",
"data: dictionary, as returned by cvx.Problem.get_problem_data('ECOS_BB') :return: None \"\"\" n = data['c'].shape[0] self.bool_ix",
"range(self.J): for i in range(self.I): self.X_ijt[i,j,t] = self.x_ijt[i,j,t].value self.Y_ijt[i,j,t] = self.y_ijt[i,j,t].value for t",
"sum( [[self.x_ijt[(i,jj,tt)] for jj in range(J)] for tt in range(t,t+self.P_j[j])], [] ) )",
"+ c_y'*y # s.t. A_eq*x + B_eq*y = b_eq # A_ineq*x + B_ineq*y",
"self.J_i[i,j]: # set inflows if (t-self.P[j,s] >= 0): self.y_st_inflow[s,t] += self.rho_out[j,s]*self.y_ijt[i,j,t-self.P[j,s]] # set",
"of the batches to be processed are within unit constraints. :return: list of",
"signatures. \"\"\" import numpy as np import cvxpy as cvx from plotting import",
"self.y_st_inflow[s,t] += self.rho_out[j,s]*self.y_ijt[i,j,t-self.P[j,s]] # set outflows self.y_st_outflow[s,t] += self.rho_in[j,s]*self.y_ijt[i,j,t] constraint_state_eq.append( self.C_min[s] <= self.y_s[s]",
"standard model: data = self.model.get_problem_data('ECOS_BB') self.retrieve_standard_model(data) def retrieve_standard_model(self, data): \"\"\" Here we store",
"construct the allocation constraints: 1) each unit i is processing at most one",
"of 0 kg for s in range(self.S): if s not in self.input_states: constraint_state_eq.append(",
"0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0.1, 0,",
"(cvx.Problem type) self.model = 0 # Optimization Variables # ---------------------- self.x_ijt = {}",
"constraints can be included as functions that return cvx.Constraints, and added in the",
"[] # 1) each unit i is processing at most one task j",
"in range(self.I): for j in range(self.J): if self.J_i[i,j]: # set inflows if (t-self.P[j,s]",
"0, 0], [0, 0.5, 0.5, 0, 0, 0, 0, 0, 0], [0, 0,",
"0 self.m_eq = 0 self.m_ineq = 0 def construct_allocation_constraint(self): \"\"\" construct the allocation",
"= self.A_ineq.shape[0] def solve(self): \"\"\" Constructs and solved the nominal STN model. The",
"Units capability (what tasks can be processed on which unit) # row =",
"0, 0, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0],",
"0 self.bool_ix = 0 self.cont_ix = 0 self.m_eq = 0 self.m_ineq = 0",
"it in the class attribute self.model as a cvx.Problem type. Constraints can be",
"self.P_j[j]*BIG_M*(1 - self.x_ijt[(i,j,t)]) + 1 ) # 2) units can only perform tasks",
":return: list of cvx.Constraint \"\"\" constraint_state_eq = [] # 1) every intermediate /",
">= T-self.P_j[j]: constraint_allocation.append( self.x_ijt[i,j,t] == 0 ) return constraint_allocation def construct_box_constraint(self): \"\"\" Construct",
"easier inspection/plotting. The np.arrays are saved within the instance attributes - STN.X_ijt (assignments,",
"self.Y_st_outflow[s,t] = self.y_st_outflow[s,t].value self.Y_st[s,t] = self.y_s[s].value + (sum([self.y_st_inflow[s,tt].value for tt in range(t+1)]) -",
"0, 0, 0.4, 0, 0.6, 0, 0, 0], [0, 0, 0.2, 0, 0.8,",
"range(T): constraint_box.append(self.x_ijt[i,j,t] >= 0) constraint_box.append(self.x_ijt[i,j,t] <= 1) constraint_box.append(self.y_ijt[i,j,t] >= 0) constraint_box.append(self.y_ijt[i,j,t] <= 1)",
"= range(self.n_x, self.n_x+self.n_y) self.c_x = data['c'][range_bool_ix] self.c_y = data['c'][range_cont_ix] self.A_eq = data['A'][:,range_bool_ix] self.B_eq",
">= 0) constraint_box.append(self.y_ijt[i,j,t] <= 1) return constraint_box def construct_units_capacity_constraint(self): \"\"\" Ensure maximum and",
"for i in range(self.I): for j in range(self.J): for t in range(self.T): self.y_ijt[i,j,t]",
"= range(self.n_x) range_cont_ix = range(self.n_x, self.n_x+self.n_y) self.c_x = data['c'][range_bool_ix] self.c_y = data['c'][range_cont_ix] self.A_eq",
"a class to avoid having to implement functions (now the class methods) with",
"for tt in range(t+1)] )) return constraint_state_eq def construct_konidili_solution_enforce(self): \"\"\" The nominal model",
"(row) self.rho_out = np.array([[0, 0, 0, 1, 0, 0, 0, 0, 0], [0,",
"(material flows, float) :return: optimal value (float) \"\"\" print 'Constructing nominal model...' self.construct_nominal_model()",
"pack everything in a class to avoid having to implement functions (now the",
"in range(self.S): if s not in self.input_states: constraint_state_eq.append( self.y_s[s] == 0 ) #",
"(now the class methods) with exceedingly long signatures. \"\"\" import numpy as np",
"B_ineq*y <= b_ineq # x \\in {0,1} self.c_x = 0 self.c_y = 0",
"# TODO BIG-M for allocation BIG_M = 40 constraint_allocation = [] # 1)",
"task j at each t 2) units can only perform tasks that are",
"== 80] ) return constraint_kondili def construct_objective(self): \"\"\" Objective encodes c'*(y_s(t=end)-y_s(t=0)), i.e., value",
"minimum sizes of the batches to be processed are within unit constraints. :return:",
"for s in range(self.S)] ) def construct_nominal_model(self): \"\"\" Constructs the nominal STN model,",
"t in range(T-self.P_j[j]+1): constraint_allocation.append( sum ( sum( [[self.x_ijt[(i,jj,tt)] for jj in range(J)] for",
"self.model = cvx.Problem(objective, constraints) # Also store the matrices of te standard model:",
"j in range(self.J): if self.J_i[i,j]: # set inflows if (t-self.P[j,s] >= 0): self.y_st_inflow[s,t]",
"['Heat', 'Rea. 1', 'Rea. 2', 'Rea. 3', 'Sep.'] self.states = ['Feed A', 'Feed",
"[]) # Objective # --------- objective = cvx.Minimize(self.construct_objective()) # Model # ----- self.model",
"two loops, so that the optimization variables # in the standard model do",
"we store the problem matrices (A_eq, B_eq, b_eq, etc) with ordered columns. :param",
"self.units.__len__() J = self.tasks.__len__() S = self.states.__len__() T = self.T # TODO BIG-M",
"# Aliases self.I = self.units.__len__() self.J = self.tasks.__len__() self.S = self.states.__len__() self.T =",
"constraints. :return: list of cvx.Constraint \"\"\" constraint_capacity = [] for i in range(self.I):",
"and added in the STN.construst_nominal_model() method. We pack everything in a class to",
"\"\"\" for t in range(self.T): for j in range(self.J): for i in range(self.I):",
"i is processing at most one task j at each t for i",
">= self.y_s[s] + sum( [self.y_st_inflow[(s,tt)] for tt in range(t+1)] ) - sum( [self.y_st_outflow[(s,tt)]",
"range(self.T): for s in range(self.S): self.Y_st_inflow[s,t] = self.y_st_inflow[s,t].value self.Y_st_outflow[s,t] = self.y_st_outflow[s,t].value self.Y_st[s,t] =",
"# Optimization Variables # ---------------------- self.x_ijt = {} # allocation variable (bool) self.y_ijt",
"'Sep.'] self.states = ['Feed A', 'Feed B', 'Feed C', 'Hot A', 'Intermediate AB',",
"80, 80, 80, 80], [50, 50, 50, 50, 50], [200, 200, 200, 200,",
"methods) with exceedingly long signatures. \"\"\" import numpy as np import cvxpy as",
":return: list of cvx.Constraint \"\"\" I = self.units.__len__() J = self.tasks.__len__() T =",
"0 self.b_ineq = 0 self.bool_ix = 0 self.cont_ix = 0 self.m_eq = 0",
"for t in range(self.T): self.x_ijt[i,j,t] = cvx.Bool() # we separate creation of x_ijt",
"s not in self.input_states: constraint_state_eq.append( self.y_s[s] == 0 ) # 2) state equations",
")) constraint_state_eq.append( self.C_max[s] >= self.y_s[s] + sum( [self.y_st_inflow[(s,tt)] for tt in range(t+1)] )",
"c'*(y_s(t=end)-y_s(t=0)), i.e., value of the final products minus cost of the input feeds.",
"constraint_box.append(self.x_ijt[i,j,t] >= 0) constraint_box.append(self.x_ijt[i,j,t] <= 1) constraint_box.append(self.y_ijt[i,j,t] >= 0) constraint_box.append(self.y_ijt[i,j,t] <= 1) return",
"2', 'Rea. 3', 'Sep.'] self.states = ['Feed A', 'Feed B', 'Feed C', 'Hot",
"0, 0, 0, 0], [0, 0, 0, 0.4, 0, 0.6, 0, 0, 0],",
"tt in range(t+1)]) - sum([self.y_st_outflow[s,tt].value for tt in range(t+1)])) def plot_schedule(self, color='red', style='ggplot'):",
"0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 2, 0, 0,",
"no tasks can start after T-P_j for i in range(I): for j in",
"the list matters!) self.units = ['Heater', 'Reactor 1', 'Reactor 2', 'Column'] self.tasks =",
"# batch size [kg] self.y_s = {} # state quantity [kg] for i",
"I = self.units.__len__() J = self.tasks.__len__() S = self.states.__len__() T = self.T #",
"executed. :return: None \"\"\" for t in range(self.T): for j in range(self.J): for",
"# time (in # of steps) required to produce output state s (column)",
"is unaffected) :return: list of cvx.Constraint \"\"\" constraint_kondili = [] constraint_kondili.append( [self.y_ijt[0,0,1] ==",
"in range(self.I): for j in range(self.J): for t in range(self.T): self.y_ijt[i,j,t] = cvx.Variable()",
"self.x_ijt = {} # allocation variable (bool) self.y_ijt = {} # batch size",
"(column), in e.g. kg self.V_max = np.array([[100, 100, 100, 100, 100], [80, 80,",
"into np.arrays for easier inspection/plotting. The np.arrays are saved within the instance attributes",
"data of Kondili's paper has several optimizers. The following constraints force the exact",
"constraint_box.append(self.y_ijt[i,j,t] <= 1) return constraint_box def construct_units_capacity_constraint(self): \"\"\" Ensure maximum and minimum sizes",
"self.horizon = 11 # horizon in number of of steps # Aliases self.I",
"0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0,",
"# Also store the matrices of te standard model: data = self.model.get_problem_data('ECOS_BB') self.retrieve_standard_model(data)",
"range(self.S): self.y_st_inflow[s,t] = cvx.Constant(0) self.y_st_outflow[s,t] = cvx.Constant(0) for i in range(self.I): for j",
"each unit i is processing at most one task j at each t",
"= [] for i in range(I): for j in range(J): for t in",
"range(self.T): for s in range(self.S): self.y_st_inflow[s,t] = cvx.Constant(0) self.y_st_outflow[s,t] = cvx.Constant(0) for i",
"kg self.V_max = np.array([[100, 100, 100, 100, 100], [80, 80, 80, 80, 80],",
"0, 0, 2, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0],",
"for i in range(self.I): for j in range(self.J): if self.J_i[i,j]: # set inflows",
"0, 0, 0, 0, 0]) # objective to maximize (revenue from the states)",
"problem structure (cvx.Problem type) self.model = 0 # Optimization Variables # ---------------------- self.x_ijt",
") return constraint_capacity def construct_state_equations_and_storage_constraint(self): \"\"\" Implementation of state equations, and states capacities",
"store the problem matrices (A_eq, B_eq, b_eq, etc) with ordered columns. :param data:",
"the class methods) with exceedingly long signatures. \"\"\" import numpy as np import",
"= self.tasks.__len__() self.S = self.states.__len__() self.T = self.horizon # Units capability (what tasks",
"self.y_s[s] == 0 ) # 2) state equations and storage capacities for t",
"if __name__ == '__main__': # example usage of the class model = STN()",
"with exceedingly long signatures. \"\"\" import numpy as np import cvxpy as cvx",
"if (t-self.P[j,s] >= 0): self.y_st_inflow[s,t] += self.rho_out[j,s]*self.y_ijt[i,j,t-self.P[j,s]] # set outflows self.y_st_outflow[s,t] += self.rho_in[j,s]*self.y_ijt[i,j,t]",
"Recipes and timing # fractions of input state s (column) required to execute",
"0, 1, 0, 0, 0], [0, 0, 0, 0, 0.6, 0, 0, 0.4,",
"process task j (column), in e.g. kg self.V_max = np.array([[100, 100, 100, 100,",
"the class attribute self.model as a cvx.Problem type. Constraints can be added/removed here.",
"np.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0,",
"t in range(self.T): self.y_ijt[i,j,t] = cvx.Variable() # state equations are eliminated to allow",
"t in range(self.T): for s in range(self.S): self.Y_st_inflow[s,t] = self.y_st_inflow[s,t].value self.Y_st_outflow[s,t] = self.y_st_outflow[s,t].value",
"state y_s(t=0), which we name y_s for s in range(self.S): self.y_s[s] = cvx.Variable()",
"state equations and storage capacities for t in range(self.T): for s in range(self.S):",
"matrices of te standard model: data = self.model.get_problem_data('ECOS_BB') self.retrieve_standard_model(data) def retrieve_standard_model(self, data): \"\"\"",
"state s self.C_max = np.array([np.infty, np.infty, np.infty, 100, 200, 150, 100, np.infty, np.infty])",
"[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]) # storage capacity",
"STN.Y_st_inflow and Y_st_outflow (material flows, float) :return: optimal value (float) \"\"\" print 'Constructing",
"s (column) produced by task j (row) self.rho_out = np.array([[0, 0, 0, 1,",
"for t in range(self.T): self.y_ijt[i,j,t] = cvx.Variable() # state equations are eliminated to",
"plotting if __name__ == '__main__': # example usage of the class model =",
"added in the STN.construst_nominal_model() method. We pack everything in a class to avoid",
"range(self.I): for j in range(self.J): for t in range(self.T): self.y_ijt[i,j,t] = cvx.Variable() #",
"0, 2, 0, 0, 0, 1]]) # total execution time of task j",
"STN model. The solution is stored in the np.arrays - STN.X_ijt (assignments, bool)",
"range(t+1)]) - sum([self.y_st_outflow[s,tt].value for tt in range(t+1)])) def plot_schedule(self, color='red', style='ggplot'): \"\"\" Plot",
"construct_state_equations_and_storage_constraint(self): \"\"\" Implementation of state equations, and states capacities (storages) :return: list of",
"can be processed on which unit) # row = unit, column = task",
"loops, so that the optimization variables # in the standard model do not",
"= {} self.y_st_outflow = {} # Attributes # ---------- # to store results",
"print 'Solving...' self.model.solve(verbose=True, solver='GUROBI') self.unpack_results() return self.model.value def unpack_results(self): \"\"\" Once model is",
"# horizon in number of of steps # Aliases self.I = self.units.__len__() self.J",
"model with the data of Kondili's paper has several optimizers. The following constraints",
"STN(object): def __init__(self): # Data # ---- # Definition of the STN (order",
"1) every intermediate / output state starts with a quantity of 0 kg",
"self.Y_st_inflow[s,t] = self.y_st_inflow[s,t].value self.Y_st_outflow[s,t] = self.y_st_outflow[s,t].value self.Y_st[s,t] = self.y_s[s].value + (sum([self.y_st_inflow[s,tt].value for tt",
"0, 0, 0, 0, 0, 1, 0, 0]]) # fractions of output state",
"# ---------- # to store results self.X_ijt = np.zeros((self.I,self.J,self.T)) self.Y_ijt = np.zeros((self.I,self.J,self.T)) self.Y_st",
"constraint_capacity.append( self.y_ijt[i,j,t] <= self.x_ijt[i,j,t]*self.V_max[i,j] ) return constraint_capacity def construct_state_equations_and_storage_constraint(self): \"\"\" Implementation of state",
"class to avoid having to implement functions (now the class methods) with exceedingly",
"constraints on x_ijt and y_ijt; useful for testing with continuous variables instead of",
"0.5, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0.4, 0, 0.6,",
"self.model.value def unpack_results(self): \"\"\" Once model is solved, transform the solution dictionaries (self.x_ijt,",
"# min c_x'*x + c_y'*y # s.t. A_eq*x + B_eq*y = b_eq #",
"# s.t. A_eq*x + B_eq*y = b_eq # A_ineq*x + B_ineq*y <= b_ineq",
"model. The solution is stored in the np.arrays - STN.X_ijt (assignments, bool) -",
"= {} # Attributes # ---------- # to store results self.X_ijt = np.zeros((self.I,self.J,self.T))",
"color='red', style='ggplot'): \"\"\" Plot the nominal schedule. :return: None \"\"\" plot_stn_schedule(self, self.Y_ijt, color=color,",
"None \"\"\" n = data['c'].shape[0] self.bool_ix = data['bool_vars_idx'] self.cont_ix = list(set(range(n)) - set(data['bool_vars_idx']))",
"= self.T # TODO BIG-M for allocation BIG_M = 40 constraint_allocation = []",
"Here we store the problem matrices (A_eq, B_eq, b_eq, etc) with ordered columns.",
"store the standard model # min c_x'*x + c_y'*y # s.t. A_eq*x +",
"\"\"\" return - sum( [self.c[s]*( sum([self.y_st_inflow[s,t] for t in range(self.T)]) - sum([self.y_st_outflow[s,t] for",
"unit i is processing at most one task j at each t for",
"= data['h'] self.b_ineq = data['h'] self.m_eq = self.A_eq.shape[0] self.m_ineq = self.A_ineq.shape[0] def solve(self):",
"# imported with plotting if __name__ == '__main__': # example usage of the",
"- self.x_ijt[(i,j,t)]) + 1 ) # 2) units can only perform tasks that",
"range(J)] for tt in range(t,t+self.P_j[j])], [] ) ) <= self.P_j[j]*BIG_M*(1 - self.x_ijt[(i,j,t)]) +",
"(column) required to execute task j (row) self.rho_in = np.array([[1, 0, 0, 0,",
"S = self.states.__len__() T = self.T # TODO BIG-M for allocation BIG_M =",
"capacity of unit i (row) to process task j (column), in e.g. kg",
"(the objective is unaffected) :return: list of cvx.Constraint \"\"\" constraint_kondili = [] constraint_kondili.append(",
"[0, 1, 1, 1, 0], [0, 0, 0, 0, 1]]) # Recipes and",
"__name__ == '__main__': # example usage of the class model = STN() model.solve()",
"from task j (row) self.P = np.array([[0, 0, 0, 1, 0, 0, 0,",
"= np.zeros((self.S,self.T)) self.Y_st_inflow = np.zeros((self.S,self.T)) self.Y_st_outflow = np.zeros((self.S,self.T)) # to store the standard",
"j in range(J): for t in range(T): constraint_allocation.append( self.x_ijt[i,j,t]*(1-self.J_i[i,j]) == 0 ) if",
"Variables # ---------------------- self.x_ijt = {} # allocation variable (bool) self.y_ijt = {}",
"construct_objective(self): \"\"\" Objective encodes c'*(y_s(t=end)-y_s(t=0)), i.e., value of the final products minus cost",
"is processing at most one task j at each t for i in",
"The data of the problem is in the __init__() method, and can be",
"for j in range(self.J): for t in range(self.T): self.x_ijt[i,j,t] = cvx.Bool() # we",
"cvx from plotting import * class STN(object): def __init__(self): # Data # ----",
"def construct_state_equations_and_storage_constraint(self): \"\"\" Implementation of state equations, and states capacities (storages) :return: list",
"are compatible with self.J_i :return: list of cvx.Constraint \"\"\" I = self.units.__len__() J",
"cvx.Problem type. Constraints can be added/removed here. :return: None \"\"\" # Constraints #",
"optimal value (float) \"\"\" print 'Constructing nominal model...' self.construct_nominal_model() print 'Solving...' self.model.solve(verbose=True, solver='GUROBI')",
"0, 0, 0, 0, 2, 0, 0, 0], [0, 0, 0, 0, 2,",
"added/removed here. :return: None \"\"\" # Constraints # ----------- constraints = [] constraints.append(self.construct_allocation_constraint())",
"equations self.y_st_inflow = {} self.y_st_outflow = {} # Attributes # ---------- # to",
"that the optimization variables # in the standard model do not get mixed",
"system based on the STN model. The data of the problem is in",
"s in range(self.S): self.y_s[s] = cvx.Variable() # auxiliary expressions used in the state",
"be processed on which unit) # row = unit, column = task self.J_i",
"self.cont_ix = list(set(range(n)) - set(data['bool_vars_idx'])) self.n_x = self.bool_ix.__len__() self.n_y = self.cont_ix.__len__() range_bool_ix =",
"type) self.model = 0 # Optimization Variables # ---------------------- self.x_ijt = {} #",
"0], [0, 0, 0, 0, 2, 0, 0, 2, 0], [0, 0, 0,",
"0, 0.6, 0, 0, 0], [0, 0, 0.2, 0, 0.8, 0, 0, 0,",
"Constraints can be added/removed here. :return: None \"\"\" # Constraints # ----------- constraints",
"self.tasks = ['Heat', 'Rea. 1', 'Rea. 2', 'Rea. 3', 'Sep.'] self.states = ['Feed",
"row = unit, column = task self.J_i = np.array([[1, 0, 0, 0, 0],",
"Ensure maximum and minimum sizes of the batches to be processed are within",
"<= self.y_ijt[i,j,t] ) constraint_capacity.append( self.y_ijt[i,j,t] <= self.x_ijt[i,j,t]*self.V_max[i,j] ) return constraint_capacity def construct_state_equations_and_storage_constraint(self): \"\"\"",
"unpack_results(self): \"\"\" Once model is solved, transform the solution dictionaries (self.x_ijt, self.y_ijt) into",
"0, 1, 0, 0], [0, 0, 0, 0, 2, 0, 0, 0, 1]])",
"'Feed C', 'Hot A', 'Intermediate AB', 'Intermediate BC', 'Impure E', 'Product 1', 'Product",
"can be changed. Additional constraints can be included as functions that return cvx.Constraints,",
"self.c_y = 0 self.A_eq = 0 self.A_ineq = 0 self.B_eq = 0 self.B_ineq",
"that return cvx.Constraints, and added in the STN.construst_nominal_model() method. We pack everything in",
"compatible with self.J_i, and tasks should be started # early enough such that",
"# Constraints # ----------- constraints = [] constraints.append(self.construct_allocation_constraint()) constraints.append(self.construct_units_capacity_constraint()) constraints.append(self.construct_state_equations_and_storage_constraint()) # can force",
"Implementation of a scheduling system based on the STN model. The data of",
"for j in range(J): for t in range(T): constraint_box.append(self.x_ijt[i,j,t] >= 0) constraint_box.append(self.x_ijt[i,j,t] <=",
"jj in range(J)] for tt in range(t,t+self.P_j[j])], [] ) ) <= self.P_j[j]*BIG_M*(1 -",
"state s (column) from task j (row) self.P = np.array([[0, 0, 0, 1,",
"constraints: 1) each unit i is processing at most one task j at",
"self.y_ijt[i,j,t] ) constraint_capacity.append( self.y_ijt[i,j,t] <= self.x_ijt[i,j,t]*self.V_max[i,j] ) return constraint_capacity def construct_state_equations_and_storage_constraint(self): \"\"\" Implementation",
"[self.y_ijt[0,0,1] == 52] ) constraint_kondili.append( [self.y_ijt[1,1,0] == 80] ) return constraint_kondili def construct_objective(self):",
"The nominal model with the data of Kondili's paper has several optimizers. The",
"def unpack_results(self): \"\"\" Once model is solved, transform the solution dictionaries (self.x_ijt, self.y_ijt)",
"sum( [self.x_ijt[(i,j,t)] for j in range(J)] ) <= 1 ) for j in",
"for allocation BIG_M = 40 constraint_allocation = [] # 1) each unit i",
"[50, 50, 50, 50, 50], [200, 200, 200, 200, 200]]) self.V_min = np.array([[0,",
"BIG-M for allocation BIG_M = 40 constraint_allocation = [] # 1) each unit",
"np.array([[1, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 1, 1,",
"attribute self.model as a cvx.Problem type. Constraints can be added/removed here. :return: None",
"0.4, 0, 0.6, 0, 0, 0], [0, 0, 0.2, 0, 0.8, 0, 0,",
"one task j at each t for i in range(I): for t in",
"0, 0], [0, 0, 0, 0, 0.6, 0, 0, 0.4, 0], [0, 0,",
"to be processed are within unit constraints. :return: list of cvx.Constraint \"\"\" constraint_capacity",
"None \"\"\" for t in range(self.T): for j in range(self.J): for i in",
"Optimization problem structure (cvx.Problem type) self.model = 0 # Optimization Variables # ----------------------",
"sum([self.y_st_outflow[s,t] for t in range(self.T)])) for s in range(self.S)] ) def construct_nominal_model(self): \"\"\"",
"----------- constraints = [] constraints.append(self.construct_allocation_constraint()) constraints.append(self.construct_units_capacity_constraint()) constraints.append(self.construct_state_equations_and_storage_constraint()) # can force Kondili's solution with",
"0, 0, 0, 0.6, 0, 0, 0.4, 0], [0, 0, 0, 0, 0,",
"t in range(T): constraint_box.append(self.x_ijt[i,j,t] >= 0) constraint_box.append(self.x_ijt[i,j,t] <= 1) constraint_box.append(self.y_ijt[i,j,t] >= 0) constraint_box.append(self.y_ijt[i,j,t]",
"range(self.T): self.y_ijt[i,j,t] = cvx.Variable() # state equations are eliminated to allow for the",
"data['h'] self.m_eq = self.A_eq.shape[0] self.m_ineq = self.A_ineq.shape[0] def solve(self): \"\"\" Constructs and solved",
"{} # allocation variable (bool) self.y_ijt = {} # batch size [kg] self.y_s",
"\\in {0,1} self.c_x = 0 self.c_y = 0 self.A_eq = 0 self.A_ineq =",
"0.5, 0.5, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0.4, 0,",
"variable (bool) self.y_ijt = {} # batch size [kg] self.y_s = {} #",
"t in range(self.T): constraint_capacity.append( self.x_ijt[i,j,t]*self.V_min[i,j] <= self.y_ijt[i,j,t] ) constraint_capacity.append( self.y_ijt[i,j,t] <= self.x_ijt[i,j,t]*self.V_max[i,j] )",
"== 0 ) # 2) state equations and storage capacities for t in",
"# objective to maximize (revenue from the states) self.c = np.array([0, 0, 0,",
"style='ggplot'): \"\"\" Plot the nominal schedule. :return: None \"\"\" plot_stn_schedule(self, self.Y_ijt, color=color, style=style)",
") <= self.P_j[j]*BIG_M*(1 - self.x_ijt[(i,j,t)]) + 1 ) # 2) units can only",
"method. We pack everything in a class to avoid having to implement functions",
"each t for i in range(I): for t in range(T): constraint_allocation.append( sum( [self.x_ijt[(i,j,t)]",
"based on the STN model. The data of the problem is in the",
"in the class attribute self.model as a cvx.Problem type. Constraints can be added/removed",
"= data['h'] self.m_eq = self.A_eq.shape[0] self.m_ineq = self.A_ineq.shape[0] def solve(self): \"\"\" Constructs and",
"'Column'] self.tasks = ['Heat', 'Rea. 1', 'Rea. 2', 'Rea. 3', 'Sep.'] self.states =",
"for t in range(self.T)]) - sum([self.y_st_outflow[s,t] for t in range(self.T)])) for s in",
"(material quantities, float) - STN.Y_st_inflow and Y_st_outflow (material flows, float) :return: optimal value",
"-1, 10, 10]) # Optimization problem structure (cvx.Problem type) self.model = 0 #",
"[0, 0, 0, 0, 2, 0, 0, 2, 0], [0, 0, 0, 0,",
"np.zeros((self.S,self.T)) self.Y_st_outflow = np.zeros((self.S,self.T)) # to store the standard model # min c_x'*x",
"numpy as np import cvxpy as cvx from plotting import * class STN(object):",
"STN.X_ijt (assignments, bool) - STN.Y_ijt (batch sizes, float) - STN.Y_st (stored material quantities,",
"list of cvx.Constraint \"\"\" I = self.units.__len__() J = self.tasks.__len__() T = self.T",
"np.arrays for easier inspection/plotting. The np.arrays are saved within the instance attributes -",
"range_cont_ix = range(self.n_x, self.n_x+self.n_y) self.c_x = data['c'][range_bool_ix] self.c_y = data['c'][range_cont_ix] self.A_eq = data['A'][:,range_bool_ix]",
"for j in range(self.J): for t in range(self.T): constraint_capacity.append( self.x_ijt[i,j,t]*self.V_min[i,j] <= self.y_ijt[i,j,t] )",
"range(self.I): for j in range(self.J): for t in range(self.T): constraint_capacity.append( self.x_ijt[i,j,t]*self.V_min[i,j] <= self.y_ijt[i,j,t]",
"in range(self.I): for j in range(self.J): for t in range(self.T): self.x_ijt[i,j,t] = cvx.Bool()",
"in range(T-self.P_j[j]+1): constraint_allocation.append( sum ( sum( [[self.x_ijt[(i,jj,tt)] for jj in range(J)] for tt",
"self.x_ijt[i,j,t]*(1-self.J_i[i,j]) == 0 ) if t >= T-self.P_j[j]: constraint_allocation.append( self.x_ijt[i,j,t] == 0 )",
"for s in range(self.S): self.y_st_inflow[s,t] = cvx.Constant(0) self.y_st_outflow[s,t] = cvx.Constant(0) for i in",
"cvx.Problem(objective, constraints) # Also store the matrices of te standard model: data =",
"- set(data['bool_vars_idx'])) self.n_x = self.bool_ix.__len__() self.n_y = self.cont_ix.__len__() range_bool_ix = range(self.n_x) range_cont_ix =",
"1]]) # total execution time of task j (row-wise max of P) self.P_j",
"[] constraint_kondili.append( [self.y_ijt[0,0,1] == 52] ) constraint_kondili.append( [self.y_ijt[1,1,0] == 80] ) return constraint_kondili",
"self.y_s[s] + sum( [self.y_st_inflow[(s,tt)] for tt in range(t+1)] ) - sum( [self.y_st_outflow[(s,tt)] for",
"\"\"\" constraint_state_eq = [] # 1) every intermediate / output state starts with",
"constraints.append(self.construct_allocation_constraint()) constraints.append(self.construct_units_capacity_constraint()) constraints.append(self.construct_state_equations_and_storage_constraint()) # can force Kondili's solution with # constraints.append(self.construct_konidili_solution_enforce()) constraints =",
"= unit, column = task self.J_i = np.array([[1, 0, 0, 0, 0], [0,",
"= list(set(range(n)) - set(data['bool_vars_idx'])) self.n_x = self.bool_ix.__len__() self.n_y = self.cont_ix.__len__() range_bool_ix = range(self.n_x)",
"for i in range(I): for j in range(J): for t in range(T): constraint_allocation.append(",
"processing at most one task j at each t 2) units can only",
"compatible with self.J_i :return: list of cvx.Constraint \"\"\" I = self.units.__len__() J =",
"----- self.model = cvx.Problem(objective, constraints) # Also store the matrices of te standard",
"[self.y_ijt[1,1,0] == 80] ) return constraint_kondili def construct_objective(self): \"\"\" Objective encodes c'*(y_s(t=end)-y_s(t=0)), i.e.,",
"y_ijt; useful for testing with continuous variables instead of bools. :return: list of",
"self.X_ijt = np.zeros((self.I,self.J,self.T)) self.Y_ijt = np.zeros((self.I,self.J,self.T)) self.Y_st = np.zeros((self.S,self.T)) self.Y_st_inflow = np.zeros((self.S,self.T)) self.Y_st_outflow",
"def construct_allocation_constraint(self): \"\"\" construct the allocation constraints: 1) each unit i is processing",
"maximize (revenue from the states) self.c = np.array([0, 0, 0, -1, -1, -1,",
"0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0]]) #",
"final products minus cost of the input feeds. :return: cvx.Objective \"\"\" return -",
"0, 0], [0, 0, 0, 0, 0]]) # storage capacity for state s",
"in number of of steps # Aliases self.I = self.units.__len__() self.J = self.tasks.__len__()",
"range(self.I): for j in range(self.J): if self.J_i[i,j]: # set inflows if (t-self.P[j,s] >=",
"can be added/removed here. :return: None \"\"\" # Constraints # ----------- constraints =",
"that they are completed within T, i.e., no tasks can start after T-P_j",
"self.Y_st[s,t] = self.y_s[s].value + (sum([self.y_st_inflow[s,tt].value for tt in range(t+1)]) - sum([self.y_st_outflow[s,tt].value for tt",
"for i in range(I): for t in range(T): constraint_allocation.append( sum( [self.x_ijt[(i,j,t)] for j",
"range(t+1)] ) - sum( [self.y_st_outflow[(s,tt)] for tt in range(t+1)] )) return constraint_state_eq def",
"[0, 0, 0, 0.4, 0, 0.6, 0, 0, 0], [0, 0, 0.2, 0,",
"of state equations, and states capacities (storages) :return: list of cvx.Constraint \"\"\" constraint_state_eq",
"get mixed up for i in range(self.I): for j in range(self.J): for t",
"0, 0], [0, 0, 0, 0.4, 0, 0.6, 0, 0, 0], [0, 0,",
"i in range(I): for j in range(J): for t in range(T): constraint_box.append(self.x_ijt[i,j,t] >=",
"STN (order in the list matters!) self.units = ['Heater', 'Reactor 1', 'Reactor 2',",
"Optimization Variables # ---------------------- self.x_ijt = {} # allocation variable (bool) self.y_ijt =",
"of cvx.Constraint \"\"\" constraint_kondili = [] constraint_kondili.append( [self.y_ijt[0,0,1] == 52] ) constraint_kondili.append( [self.y_ijt[1,1,0]",
"by task j (row) self.rho_out = np.array([[0, 0, 0, 1, 0, 0, 0,",
"in range(t+1)] )) constraint_state_eq.append( self.C_max[s] >= self.y_s[s] + sum( [self.y_st_inflow[(s,tt)] for tt in",
"self.y_s[s] = cvx.Variable() # auxiliary expressions used in the state equations self.y_st_inflow =",
"j in range(J): for t in range(T-self.P_j[j]+1): constraint_allocation.append( sum ( sum( [[self.x_ijt[(i,jj,tt)] for",
"material quantities, float) - STN.Y_st_inflow and STN.Y_st_outflow (material flows, float), and can be",
"with self.J_i :return: list of cvx.Constraint \"\"\" I = self.units.__len__() J = self.tasks.__len__()",
"1', 'Reactor 2', 'Column'] self.tasks = ['Heat', 'Rea. 1', 'Rea. 2', 'Rea. 3',",
"80, 80, 80], [50, 50, 50, 50, 50], [200, 200, 200, 200, 200]])",
"functions that return cvx.Constraints, and added in the STN.construst_nominal_model() method. We pack everything",
"T-P_j for i in range(I): for j in range(J): for t in range(T):",
"constraints) # Also store the matrices of te standard model: data = self.model.get_problem_data('ECOS_BB')",
"1, 1, 0], [0, 0, 0, 0, 1]]) # Recipes and timing #",
"[] ) ) <= self.P_j[j]*BIG_M*(1 - self.x_ijt[(i,j,t)]) + 1 ) # 2) units",
"in range(self.J): if self.J_i[i,j]: # set inflows if (t-self.P[j,s] >= 0): self.y_st_inflow[s,t] +=",
":return: None \"\"\" for t in range(self.T): for j in range(self.J): for i",
"range(J): for t in range(T-self.P_j[j]+1): constraint_allocation.append( sum ( sum( [[self.x_ijt[(i,jj,tt)] for jj in",
"minus cost of the input feeds. :return: cvx.Objective \"\"\" return - sum( [self.c[s]*(",
"T-self.P_j[j]: constraint_allocation.append( self.x_ijt[i,j,t] == 0 ) return constraint_allocation def construct_box_constraint(self): \"\"\" Construct box",
"= self.states.__len__() self.T = self.horizon # Units capability (what tasks can be processed",
"t in range(self.T)])) for s in range(self.S)] ) def construct_nominal_model(self): \"\"\" Constructs the",
"store results self.X_ijt = np.zeros((self.I,self.J,self.T)) self.Y_ijt = np.zeros((self.I,self.J,self.T)) self.Y_st = np.zeros((self.S,self.T)) self.Y_st_inflow =",
"0, 0], [0, 0, 0.2, 0, 0.8, 0, 0, 0, 0], [0, 0,",
"i.e., value of the final products minus cost of the input feeds. :return:",
"self.V_max = np.array([[100, 100, 100, 100, 100], [80, 80, 80, 80, 80], [50,",
"self.model as a cvx.Problem type. Constraints can be added/removed here. :return: None \"\"\"",
"the robust counterpart. We only store # the initial state y_s(t=0), which we",
"y_s for s in range(self.S): self.y_s[s] = cvx.Variable() # auxiliary expressions used in",
"1, 0], [0, 0, 0, 0, 1]]) # Recipes and timing # fractions",
"self.x_ijt[i,j,t].value self.Y_ijt[i,j,t] = self.y_ijt[i,j,t].value for t in range(self.T): for s in range(self.S): self.Y_st_inflow[s,t]",
"= self.units.__len__() J = self.tasks.__len__() T = self.T constraint_box = [] for i",
"tasks can be processed on which unit) # row = unit, column =",
"n = data['c'].shape[0] self.bool_ix = data['bool_vars_idx'] self.cont_ix = list(set(range(n)) - set(data['bool_vars_idx'])) self.n_x =",
"nominal model...' self.construct_nominal_model() print 'Solving...' self.model.solve(verbose=True, solver='GUROBI') self.unpack_results() return self.model.value def unpack_results(self): \"\"\"",
"and can be changed. Additional constraints can be included as functions that return",
"<= self.P_j[j]*BIG_M*(1 - self.x_ijt[(i,j,t)]) + 1 ) # 2) units can only perform",
"dictionaries (self.x_ijt, self.y_ijt) into np.arrays for easier inspection/plotting. The np.arrays are saved within",
"STN.Y_ijt (batch sizes, float) - STN.Y_st (material quantities, float) - STN.Y_st_inflow and Y_st_outflow",
"self.tasks.__len__() S = self.states.__len__() T = self.T # TODO BIG-M for allocation BIG_M",
"standard model # min c_x'*x + c_y'*y # s.t. A_eq*x + B_eq*y =",
"np.array([0, 0, 0, 0, 0, 0, 0, 0, 0]) # objective to maximize",
"exceedingly long signatures. \"\"\" import numpy as np import cvxpy as cvx from",
"solution is stored in the np.arrays - STN.X_ijt (assignments, bool) - STN.Y_ijt (batch",
"= np.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0,",
"attributes - STN.X_ijt (assignments, bool) - STN.Y_ijt (batch sizes, float) - STN.Y_st (stored",
"to implement functions (now the class methods) with exceedingly long signatures. \"\"\" import",
"TODO BIG-M for allocation BIG_M = 40 constraint_allocation = [] # 1) each",
"i in range(I): for t in range(T): constraint_allocation.append( sum( [self.x_ijt[(i,j,t)] for j in",
"be changed. Additional constraints can be included as functions that return cvx.Constraints, and",
"inflows if (t-self.P[j,s] >= 0): self.y_st_inflow[s,t] += self.rho_out[j,s]*self.y_ijt[i,j,t-self.P[j,s]] # set outflows self.y_st_outflow[s,t] +=",
"[0, 0, 0, 0, 0, 2, 0, 0, 0], [0, 0, 0, 0,",
"= self.cont_ix.__len__() range_bool_ix = range(self.n_x) range_cont_ix = range(self.n_x, self.n_x+self.n_y) self.c_x = data['c'][range_bool_ix] self.c_y",
"= self.units.__len__() J = self.tasks.__len__() S = self.states.__len__() T = self.T # TODO",
"(assignments, bool) - STN.Y_ijt (batch sizes, float) - STN.Y_st (stored material quantities, float)",
"in range(self.T): self.x_ijt[i,j,t] = cvx.Bool() # we separate creation of x_ijt and y_ijt",
"in range(I): for j in range(J): for t in range(T): constraint_allocation.append( self.x_ijt[i,j,t]*(1-self.J_i[i,j]) ==",
"\"\"\" I = self.units.__len__() J = self.tasks.__len__() T = self.T constraint_box = []",
"be processed are within unit constraints. :return: list of cvx.Constraint \"\"\" constraint_capacity =",
"model is solved, transform the solution dictionaries (self.x_ijt, self.y_ijt) into np.arrays for easier",
"avoid having to implement functions (now the class methods) with exceedingly long signatures.",
"range(T): constraint_allocation.append( sum( [self.x_ijt[(i,j,t)] for j in range(J)] ) <= 1 ) for",
"= cvx.Variable() # state equations are eliminated to allow for the robust counterpart.",
"cvx.Constraint \"\"\" constraint_kondili = [] constraint_kondili.append( [self.y_ijt[0,0,1] == 52] ) constraint_kondili.append( [self.y_ijt[1,1,0] ==",
"self.c_x = data['c'][range_bool_ix] self.c_y = data['c'][range_cont_ix] self.A_eq = data['A'][:,range_bool_ix] self.B_eq = data['A'][:,range_cont_ix] self.b_eq",
"with plotting if __name__ == '__main__': # example usage of the class model",
"as functions that return cvx.Constraints, and added in the STN.construst_nominal_model() method. We pack",
"testing with continuous variables instead of bools. :return: list of cvx.Constraint \"\"\" I",
"0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0], [0,",
"for testing with continuous variables instead of bools. :return: list of cvx.Constraint \"\"\"",
"= {} # allocation variable (bool) self.y_ijt = {} # batch size [kg]",
"color=color, style=style) # imported with plotting if __name__ == '__main__': # example usage",
"(column) produced by task j (row) self.rho_out = np.array([[0, 0, 0, 1, 0,",
"range(self.T): constraint_capacity.append( self.x_ijt[i,j,t]*self.V_min[i,j] <= self.y_ijt[i,j,t] ) constraint_capacity.append( self.y_ijt[i,j,t] <= self.x_ijt[i,j,t]*self.V_max[i,j] ) return constraint_capacity",
"-1, -1, -1, -1, 10, 10]) # Optimization problem structure (cvx.Problem type) self.model",
"np.infty]) self.C_min = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0]) #",
"2, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0,",
"the initial state y_s(t=0), which we name y_s for s in range(self.S): self.y_s[s]",
"list matters!) self.units = ['Heater', 'Reactor 1', 'Reactor 2', 'Column'] self.tasks = ['Heat',",
"'Product 1', 'Product 2'] self.input_states = [0, 1, 2] # indices of the",
"[] for i in range(I): for j in range(J): for t in range(T):",
"\"\"\" plot_stn_schedule(self, self.Y_ijt, color=color, style=style) # imported with plotting if __name__ == '__main__':",
"STN model. The data of the problem is in the __init__() method, and",
"model. The data of the problem is in the __init__() method, and can",
"'Reactor 1', 'Reactor 2', 'Column'] self.tasks = ['Heat', 'Rea. 1', 'Rea. 2', 'Rea.",
"2) units can only perform tasks that are compatible with self.J_i :return: list",
"total execution time of task j (row-wise max of P) self.P_j = np.amax(self.P,",
"return self.model.value def unpack_results(self): \"\"\" Once model is solved, transform the solution dictionaries",
"= self.T constraint_box = [] for i in range(I): for j in range(J):",
"0, 0.9]]) # time (in # of steps) required to produce output state",
"in range(self.J): for t in range(self.T): constraint_capacity.append( self.x_ijt[i,j,t]*self.V_min[i,j] <= self.y_ijt[i,j,t] ) constraint_capacity.append( self.y_ijt[i,j,t]",
"plot_schedule(self, color='red', style='ggplot'): \"\"\" Plot the nominal schedule. :return: None \"\"\" plot_stn_schedule(self, self.Y_ijt,",
"range(self.I): for j in range(self.J): for t in range(self.T): self.x_ijt[i,j,t] = cvx.Bool() #",
"200, 200, 200, 200]]) self.V_min = np.array([[0, 0, 0, 0, 0], [0, 0,",
"import numpy as np import cvxpy as cvx from plotting import * class",
"0, 1, 0, 0], [0, 0, 0, 0, 0.1, 0, 0, 0, 0.9]])",
"(row) to process task j (column), in e.g. kg self.V_max = np.array([[100, 100,",
"plotting import * class STN(object): def __init__(self): # Data # ---- # Definition",
"def solve(self): \"\"\" Constructs and solved the nominal STN model. The solution is",
"data['G'][:,range_bool_ix] self.B_ineq = data['G'][:,range_cont_ix] self.b_ineq = data['h'] self.b_ineq = data['h'] self.m_eq = self.A_eq.shape[0]",
"STN.Y_st_outflow (material flows, float), and can be accessed from there once the method",
"t in range(self.T): for j in range(self.J): for i in range(self.I): self.X_ijt[i,j,t] =",
"(A_eq, B_eq, b_eq, etc) with ordered columns. :param data: dictionary, as returned by",
"- STN.Y_ijt (batch sizes, float) - STN.Y_st (material quantities, float) - STN.Y_st_inflow and",
"= 0 self.B_eq = 0 self.B_ineq = 0 self.b_eq = 0 self.b_ineq =",
"0 self.B_ineq = 0 self.b_eq = 0 self.b_ineq = 0 self.bool_ix = 0",
"the data of Kondili's paper has several optimizers. The following constraints force the",
"as cvx from plotting import * class STN(object): def __init__(self): # Data #",
"ordered columns. :param data: dictionary, as returned by cvx.Problem.get_problem_data('ECOS_BB') :return: None \"\"\" n",
"(row-wise max of P) self.P_j = np.amax(self.P, axis=1) # Capacities # max capacity",
"constraints force the exact same solution as in the paper (the objective is",
"0, 0, 0, 1]]) # total execution time of task j (row-wise max",
"can force Kondili's solution with # constraints.append(self.construct_konidili_solution_enforce()) constraints = sum(constraints, []) # Objective",
"i.e., no tasks can start after T-P_j for i in range(I): for j",
"j (row) self.rho_out = np.array([[0, 0, 0, 1, 0, 0, 0, 0, 0],",
"self.n_x = self.bool_ix.__len__() self.n_y = self.cont_ix.__len__() range_bool_ix = range(self.n_x) range_cont_ix = range(self.n_x, self.n_x+self.n_y)",
"quantities, float) - STN.Y_st_inflow and STN.Y_st_outflow (material flows, float), and can be accessed",
"outflows self.y_st_outflow[s,t] += self.rho_in[j,s]*self.y_ijt[i,j,t] constraint_state_eq.append( self.C_min[s] <= self.y_s[s] + sum( [self.y_st_inflow[(s,tt)] for tt",
"= self.horizon # Units capability (what tasks can be processed on which unit)",
"in e.g. kg self.V_max = np.array([[100, 100, 100, 100, 100], [80, 80, 80,",
"self.tasks.__len__() T = self.T constraint_box = [] for i in range(I): for j",
"1) return constraint_box def construct_units_capacity_constraint(self): \"\"\" Ensure maximum and minimum sizes of the",
"can only perform tasks that are compatible with self.J_i, and tasks should be",
"2, 0, 0, 2, 0], [0, 0, 0, 0, 0, 0, 1, 0,",
"<= 1) return constraint_box def construct_units_capacity_constraint(self): \"\"\" Ensure maximum and minimum sizes of",
"[self.y_st_outflow[(s,tt)] for tt in range(t+1)] )) return constraint_state_eq def construct_konidili_solution_enforce(self): \"\"\" The nominal",
"self.y_st_outflow[s,t] += self.rho_in[j,s]*self.y_ijt[i,j,t] constraint_state_eq.append( self.C_min[s] <= self.y_s[s] + sum( [self.y_st_inflow[(s,tt)] for tt in",
"the problem matrices (A_eq, B_eq, b_eq, etc) with ordered columns. :param data: dictionary,",
"in range(self.J): for t in range(self.T): self.x_ijt[i,j,t] = cvx.Bool() # we separate creation",
"in range(self.T)])) for s in range(self.S)] ) def construct_nominal_model(self): \"\"\" Constructs the nominal",
"# storage capacity for state s self.C_max = np.array([np.infty, np.infty, np.infty, 100, 200,",
"---- # Definition of the STN (order in the list matters!) self.units =",
"in range(self.S): self.Y_st_inflow[s,t] = self.y_st_inflow[s,t].value self.Y_st_outflow[s,t] = self.y_st_outflow[s,t].value self.Y_st[s,t] = self.y_s[s].value + (sum([self.y_st_inflow[s,tt].value",
"0, 0, 0, 0, 0, 0, 0]) # objective to maximize (revenue from",
"cvx.Variable() # auxiliary expressions used in the state equations self.y_st_inflow = {} self.y_st_outflow",
"Construct box constraints on x_ijt and y_ijt; useful for testing with continuous variables",
"0, 0, 0], [0, 0, 0.2, 0, 0.8, 0, 0, 0, 0], [0,",
"state equations are eliminated to allow for the robust counterpart. We only store",
"80, 80], [50, 50, 50, 50, 50], [200, 200, 200, 200, 200]]) self.V_min",
"# can force Kondili's solution with # constraints.append(self.construct_konidili_solution_enforce()) constraints = sum(constraints, []) #",
"# Optimization problem structure (cvx.Problem type) self.model = 0 # Optimization Variables #",
"0, 0, 0, 0, 0, 0], [0, 0.5, 0.5, 0, 0, 0, 0,",
"data['A'][:,range_bool_ix] self.B_eq = data['A'][:,range_cont_ix] self.b_eq = data['b'] self.A_ineq = data['G'][:,range_bool_ix] self.B_ineq = data['G'][:,range_cont_ix]",
"# we separate creation of x_ijt and y_ijt in two loops, so that",
"0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])",
"for tt in range(t+1)] )) constraint_state_eq.append( self.C_max[s] >= self.y_s[s] + sum( [self.y_st_inflow[(s,tt)] for",
"range(self.T): self.x_ijt[i,j,t] = cvx.Bool() # we separate creation of x_ijt and y_ijt in",
"0, 0, 0, 0, 0, 0, 0, 0]) # objective to maximize (revenue",
"bool) - STN.Y_ijt (batch sizes, float) - STN.Y_st (material quantities, float) - STN.Y_st_inflow",
"= [0, 1, 2] # indices of the input states self.horizon = 11",
"processed on which unit) # row = unit, column = task self.J_i =",
"set(data['bool_vars_idx'])) self.n_x = self.bool_ix.__len__() self.n_y = self.cont_ix.__len__() range_bool_ix = range(self.n_x) range_cont_ix = range(self.n_x,",
"self.model.get_problem_data('ECOS_BB') self.retrieve_standard_model(data) def retrieve_standard_model(self, data): \"\"\" Here we store the problem matrices (A_eq,",
":param data: dictionary, as returned by cvx.Problem.get_problem_data('ECOS_BB') :return: None \"\"\" n = data['c'].shape[0]",
"0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0],",
"self.units.__len__() J = self.tasks.__len__() T = self.T constraint_box = [] for i in",
"the instance attributes - STN.X_ijt (assignments, bool) - STN.Y_ijt (batch sizes, float) -",
"B_eq, b_eq, etc) with ordered columns. :param data: dictionary, as returned by cvx.Problem.get_problem_data('ECOS_BB')",
">= 0): self.y_st_inflow[s,t] += self.rho_out[j,s]*self.y_ijt[i,j,t-self.P[j,s]] # set outflows self.y_st_outflow[s,t] += self.rho_in[j,s]*self.y_ijt[i,j,t] constraint_state_eq.append( self.C_min[s]",
"objective = cvx.Minimize(self.construct_objective()) # Model # ----- self.model = cvx.Problem(objective, constraints) # Also",
"allocation BIG_M = 40 constraint_allocation = [] # 1) each unit i is",
"\"\"\" construct the allocation constraints: 1) each unit i is processing at most",
"self.states = ['Feed A', 'Feed B', 'Feed C', 'Hot A', 'Intermediate AB', 'Intermediate",
"# early enough such that they are completed within T, i.e., no tasks",
"data of the problem is in the __init__() method, and can be changed.",
"paper has several optimizers. The following constraints force the exact same solution as",
"== 0 ) return constraint_allocation def construct_box_constraint(self): \"\"\" Construct box constraints on x_ijt",
"model # min c_x'*x + c_y'*y # s.t. A_eq*x + B_eq*y = b_eq",
"- STN.Y_st_inflow and STN.Y_st_outflow (material flows, float), and can be accessed from there",
"range(I): for j in range(J): for t in range(T): constraint_box.append(self.x_ijt[i,j,t] >= 0) constraint_box.append(self.x_ijt[i,j,t]",
":return: None \"\"\" # Constraints # ----------- constraints = [] constraints.append(self.construct_allocation_constraint()) constraints.append(self.construct_units_capacity_constraint()) constraints.append(self.construct_state_equations_and_storage_constraint())",
"in range(J): for t in range(T): constraint_box.append(self.x_ijt[i,j,t] >= 0) constraint_box.append(self.x_ijt[i,j,t] <= 1) constraint_box.append(self.y_ijt[i,j,t]",
"sum ( sum( [[self.x_ijt[(i,jj,tt)] for jj in range(J)] for tt in range(t,t+self.P_j[j])], []",
"constraints.append(self.construct_state_equations_and_storage_constraint()) # can force Kondili's solution with # constraints.append(self.construct_konidili_solution_enforce()) constraints = sum(constraints, [])",
"0.4, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0,",
"inspection/plotting. The np.arrays are saved within the instance attributes - STN.X_ijt (assignments, bool)",
"input feeds. :return: cvx.Objective \"\"\" return - sum( [self.c[s]*( sum([self.y_st_inflow[s,t] for t in",
"on which unit) # row = unit, column = task self.J_i = np.array([[1,",
"self.cont_ix.__len__() range_bool_ix = range(self.n_x) range_cont_ix = range(self.n_x, self.n_x+self.n_y) self.c_x = data['c'][range_bool_ix] self.c_y =",
"sum([self.y_st_outflow[s,tt].value for tt in range(t+1)])) def plot_schedule(self, color='red', style='ggplot'): \"\"\" Plot the nominal",
"0], [0, 0, 0, 0, 0]]) # storage capacity for state s self.C_max",
"\"\"\" Constructs the nominal STN model, and saves it in the class attribute",
"C', 'Hot A', 'Intermediate AB', 'Intermediate BC', 'Impure E', 'Product 1', 'Product 2']",
"self.B_eq = data['A'][:,range_cont_ix] self.b_eq = data['b'] self.A_ineq = data['G'][:,range_bool_ix] self.B_ineq = data['G'][:,range_cont_ix] self.b_ineq",
"np.infty, 100, 200, 150, 100, np.infty, np.infty]) self.C_min = np.array([0, 0, 0, 0,",
"2] # indices of the input states self.horizon = 11 # horizon in",
"task self.J_i = np.array([[1, 0, 0, 0, 0], [0, 1, 1, 1, 0],",
"\"\"\" Objective encodes c'*(y_s(t=end)-y_s(t=0)), i.e., value of the final products minus cost of",
"method, and can be changed. Additional constraints can be included as functions that",
"in range(self.T): constraint_capacity.append( self.x_ijt[i,j,t]*self.V_min[i,j] <= self.y_ijt[i,j,t] ) constraint_capacity.append( self.y_ijt[i,j,t] <= self.x_ijt[i,j,t]*self.V_max[i,j] ) return",
"np.zeros((self.S,self.T)) # to store the standard model # min c_x'*x + c_y'*y #",
"[0, 0, 0, 0, 0, 0, 1, 0, 0]]) # fractions of output",
"T, i.e., no tasks can start after T-P_j for i in range(I): for",
"self.y_ijt[i,j,t] <= self.x_ijt[i,j,t]*self.V_max[i,j] ) return constraint_capacity def construct_state_equations_and_storage_constraint(self): \"\"\" Implementation of state equations,",
"range(I): for t in range(T): constraint_allocation.append( sum( [self.x_ijt[(i,j,t)] for j in range(J)] )",
"10, 10]) # Optimization problem structure (cvx.Problem type) self.model = 0 # Optimization",
"s in range(self.S)] ) def construct_nominal_model(self): \"\"\" Constructs the nominal STN model, and",
"0, 0, 0, 0]]) # storage capacity for state s self.C_max = np.array([np.infty,",
"\"\"\" constraint_kondili = [] constraint_kondili.append( [self.y_ijt[0,0,1] == 52] ) constraint_kondili.append( [self.y_ijt[1,1,0] == 80]",
"Additional constraints can be included as functions that return cvx.Constraints, and added in",
"= np.zeros((self.S,self.T)) self.Y_st_outflow = np.zeros((self.S,self.T)) # to store the standard model # min",
"method is executed. :return: None \"\"\" for t in range(self.T): for j in",
"s.t. A_eq*x + B_eq*y = b_eq # A_ineq*x + B_ineq*y <= b_ineq #",
"continuous variables instead of bools. :return: list of cvx.Constraint \"\"\" I = self.units.__len__()",
"1) constraint_box.append(self.y_ijt[i,j,t] >= 0) constraint_box.append(self.y_ijt[i,j,t] <= 1) return constraint_box def construct_units_capacity_constraint(self): \"\"\" Ensure",
"Kondili's solution with # constraints.append(self.construct_konidili_solution_enforce()) constraints = sum(constraints, []) # Objective # ---------",
"steps # Aliases self.I = self.units.__len__() self.J = self.tasks.__len__() self.S = self.states.__len__() self.T",
"1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0,",
"output state starts with a quantity of 0 kg for s in range(self.S):",
"as a cvx.Problem type. Constraints can be added/removed here. :return: None \"\"\" #",
"0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]) # storage",
"self.units.__len__() self.J = self.tasks.__len__() self.S = self.states.__len__() self.T = self.horizon # Units capability",
"= np.array([[1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0.5, 0.5,",
"1 ) for j in range(J): for t in range(T-self.P_j[j]+1): constraint_allocation.append( sum (",
"for jj in range(J)] for tt in range(t,t+self.P_j[j])], [] ) ) <= self.P_j[j]*BIG_M*(1",
"if s not in self.input_states: constraint_state_eq.append( self.y_s[s] == 0 ) # 2) state",
"# 1) every intermediate / output state starts with a quantity of 0",
"equations and storage capacities for t in range(self.T): for s in range(self.S): self.y_st_inflow[s,t]",
"---------- # to store results self.X_ijt = np.zeros((self.I,self.J,self.T)) self.Y_ijt = np.zeros((self.I,self.J,self.T)) self.Y_st =",
"0 self.m_ineq = 0 def construct_allocation_constraint(self): \"\"\" construct the allocation constraints: 1) each",
"= 0 self.B_ineq = 0 self.b_eq = 0 self.b_ineq = 0 self.bool_ix =",
"2, 0, 0, 0], [0, 0, 0, 0, 2, 0, 0, 2, 0],",
"1, 1, 1, 0], [0, 0, 0, 0, 1]]) # Recipes and timing",
"of P) self.P_j = np.amax(self.P, axis=1) # Capacities # max capacity of unit",
"0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 2,",
"to produce output state s (column) from task j (row) self.P = np.array([[0,",
"self.P_j = np.amax(self.P, axis=1) # Capacities # max capacity of unit i (row)",
"1, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 1]]) #",
"# --------- objective = cvx.Minimize(self.construct_objective()) # Model # ----- self.model = cvx.Problem(objective, constraints)",
"of steps # Aliases self.I = self.units.__len__() self.J = self.tasks.__len__() self.S = self.states.__len__()",
"storage capacity for state s self.C_max = np.array([np.infty, np.infty, np.infty, 100, 200, 150,",
"objective to maximize (revenue from the states) self.c = np.array([0, 0, 0, -1,",
"= np.array([0, 0, 0, 0, 0, 0, 0, 0, 0]) # objective to",
"AB', 'Intermediate BC', 'Impure E', 'Product 1', 'Product 2'] self.input_states = [0, 1,",
"in the paper (the objective is unaffected) :return: list of cvx.Constraint \"\"\" constraint_kondili",
"= data['c'][range_cont_ix] self.A_eq = data['A'][:,range_bool_ix] self.B_eq = data['A'][:,range_cont_ix] self.b_eq = data['b'] self.A_ineq =",
"[] constraints.append(self.construct_allocation_constraint()) constraints.append(self.construct_units_capacity_constraint()) constraints.append(self.construct_state_equations_and_storage_constraint()) # can force Kondili's solution with # constraints.append(self.construct_konidili_solution_enforce()) constraints",
"the solution dictionaries (self.x_ijt, self.y_ijt) into np.arrays for easier inspection/plotting. The np.arrays are",
"can be accessed from there once the method is executed. :return: None \"\"\"",
"a cvx.Problem type. Constraints can be added/removed here. :return: None \"\"\" # Constraints",
"0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0,",
"unit constraints. :return: list of cvx.Constraint \"\"\" constraint_capacity = [] for i in",
"0.6, 0, 0, 0.4, 0], [0, 0, 0, 0, 0, 0, 1, 0,",
"saves it in the class attribute self.model as a cvx.Problem type. Constraints can",
"range(J): for t in range(T): constraint_allocation.append( self.x_ijt[i,j,t]*(1-self.J_i[i,j]) == 0 ) if t >=",
"2) units can only perform tasks that are compatible with self.J_i, and tasks",
"cvx.Objective \"\"\" return - sum( [self.c[s]*( sum([self.y_st_inflow[s,t] for t in range(self.T)]) - sum([self.y_st_outflow[s,t]",
"0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0.6,",
"0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0.6, 0,",
"required to execute task j (row) self.rho_in = np.array([[1, 0, 0, 0, 0,",
"---------------------- self.x_ijt = {} # allocation variable (bool) self.y_ijt = {} # batch",
"self.T # TODO BIG-M for allocation BIG_M = 40 constraint_allocation = [] #",
"x_ijt and y_ijt; useful for testing with continuous variables instead of bools. :return:",
"0, 0], [0, 0, 0, 0, 2, 0, 0, 2, 0], [0, 0,",
"standard model do not get mixed up for i in range(self.I): for j",
"execution time of task j (row-wise max of P) self.P_j = np.amax(self.P, axis=1)",
"1, 2] # indices of the input states self.horizon = 11 # horizon",
"0, 0, 1]]) # Recipes and timing # fractions of input state s",
"0, 0]]) # storage capacity for state s self.C_max = np.array([np.infty, np.infty, np.infty,",
"\"\"\" # Constraints # ----------- constraints = [] constraints.append(self.construct_allocation_constraint()) constraints.append(self.construct_units_capacity_constraint()) constraints.append(self.construct_state_equations_and_storage_constraint()) # can",
"0, 0, 0, 0], [0, 0, 0, 0, 0, 2, 0, 0, 0],",
"unit i is processing at most one task j at each t 2)",
"0]]) # storage capacity for state s self.C_max = np.array([np.infty, np.infty, np.infty, 100,",
"in range(I): for t in range(T): constraint_allocation.append( sum( [self.x_ijt[(i,j,t)] for j in range(J)]",
"[self.x_ijt[(i,j,t)] for j in range(J)] ) <= 1 ) for j in range(J):",
"return constraint_kondili def construct_objective(self): \"\"\" Objective encodes c'*(y_s(t=end)-y_s(t=0)), i.e., value of the final",
"and timing # fractions of input state s (column) required to execute task",
"self.B_eq = 0 self.B_ineq = 0 self.b_eq = 0 self.b_ineq = 0 self.bool_ix",
"= [] for i in range(self.I): for j in range(self.J): for t in",
"for j in range(J): for t in range(T-self.P_j[j]+1): constraint_allocation.append( sum ( sum( [[self.x_ijt[(i,jj,tt)]",
"self.C_min[s] <= self.y_s[s] + sum( [self.y_st_inflow[(s,tt)] for tt in range(t+1)] ) - sum(",
"be accessed from there once the method is executed. :return: None \"\"\" for",
"self.units = ['Heater', 'Reactor 1', 'Reactor 2', 'Column'] self.tasks = ['Heat', 'Rea. 1',",
"0, 0, 0, 2, 0, 0, 0, 1]]) # total execution time of",
"== 0 ) if t >= T-self.P_j[j]: constraint_allocation.append( self.x_ijt[i,j,t] == 0 ) return",
"value (float) \"\"\" print 'Constructing nominal model...' self.construct_nominal_model() print 'Solving...' self.model.solve(verbose=True, solver='GUROBI') self.unpack_results()",
"return constraint_box def construct_units_capacity_constraint(self): \"\"\" Ensure maximum and minimum sizes of the batches",
"which unit) # row = unit, column = task self.J_i = np.array([[1, 0,",
"changed. Additional constraints can be included as functions that return cvx.Constraints, and added",
"[0, 0, 0.2, 0, 0.8, 0, 0, 0, 0], [0, 0, 0, 0,",
"for state s self.C_max = np.array([np.infty, np.infty, np.infty, 100, 200, 150, 100, np.infty,",
"constraint_allocation.append( self.x_ijt[i,j,t] == 0 ) return constraint_allocation def construct_box_constraint(self): \"\"\" Construct box constraints",
"0, 0, 0, 0], [0, 0.5, 0.5, 0, 0, 0, 0, 0, 0],",
"def construct_konidili_solution_enforce(self): \"\"\" The nominal model with the data of Kondili's paper has",
"list of cvx.Constraint \"\"\" constraint_state_eq = [] # 1) every intermediate / output",
"* class STN(object): def __init__(self): # Data # ---- # Definition of the",
"2'] self.input_states = [0, 1, 2] # indices of the input states self.horizon",
"objective is unaffected) :return: list of cvx.Constraint \"\"\" constraint_kondili = [] constraint_kondili.append( [self.y_ijt[0,0,1]",
"range(t+1)] ) - sum( [self.y_st_outflow[(s,tt)] for tt in range(t+1)] )) constraint_state_eq.append( self.C_max[s] >=",
"0, 0, 0, 0, 0, 0], [0, 0, 0, 0.4, 0, 0.6, 0,",
"sizes of the batches to be processed are within unit constraints. :return: list",
"= np.array([0, 0, 0, -1, -1, -1, -1, 10, 10]) # Optimization problem",
"self.J_i = np.array([[1, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0,",
"size [kg] self.y_s = {} # state quantity [kg] for i in range(self.I):",
") # 2) units can only perform tasks that are compatible with self.J_i,",
"range(self.I): self.X_ijt[i,j,t] = self.x_ijt[i,j,t].value self.Y_ijt[i,j,t] = self.y_ijt[i,j,t].value for t in range(self.T): for s",
"0, 0, 0, 0.9]]) # time (in # of steps) required to produce",
"Data # ---- # Definition of the STN (order in the list matters!)",
"completed within T, i.e., no tasks can start after T-P_j for i in",
"\"\"\" Constructs and solved the nominal STN model. The solution is stored in",
"schedule. :return: None \"\"\" plot_stn_schedule(self, self.Y_ijt, color=color, style=style) # imported with plotting if",
"# auxiliary expressions used in the state equations self.y_st_inflow = {} self.y_st_outflow =",
"in two loops, so that the optimization variables # in the standard model",
"= 0 # Optimization Variables # ---------------------- self.x_ijt = {} # allocation variable",
"'Intermediate AB', 'Intermediate BC', 'Impure E', 'Product 1', 'Product 2'] self.input_states = [0,",
"s in range(self.S): if s not in self.input_states: constraint_state_eq.append( self.y_s[s] == 0 )",
"are eliminated to allow for the robust counterpart. We only store # the",
"i in range(self.I): for j in range(self.J): for t in range(self.T): self.x_ijt[i,j,t] =",
"can be included as functions that return cvx.Constraints, and added in the STN.construst_nominal_model()",
"\"\"\" Implementation of state equations, and states capacities (storages) :return: list of cvx.Constraint",
"__author__ = 'robin' \"\"\" Implementation of a scheduling system based on the STN",
"for i in range(I): for j in range(J): for t in range(T): constraint_box.append(self.x_ijt[i,j,t]",
"0, 0, 0.1, 0, 0, 0, 0.9]]) # time (in # of steps)",
"not in self.input_states: constraint_state_eq.append( self.y_s[s] == 0 ) # 2) state equations and",
"start after T-P_j for i in range(I): for j in range(J): for t",
"3', 'Sep.'] self.states = ['Feed A', 'Feed B', 'Feed C', 'Hot A', 'Intermediate",
"after T-P_j for i in range(I): for j in range(J): for t in",
"implement functions (now the class methods) with exceedingly long signatures. \"\"\" import numpy",
"at most one task j at each t for i in range(I): for",
"0, 1, 0, 0]]) # fractions of output state s (column) produced by",
"of unit i (row) to process task j (column), in e.g. kg self.V_max",
"\"\"\" import numpy as np import cvxpy as cvx from plotting import *",
"[0, 0, 0, 0, 0.6, 0, 0, 0.4, 0], [0, 0, 0, 0,",
"s self.C_max = np.array([np.infty, np.infty, np.infty, 100, 200, 150, 100, np.infty, np.infty]) self.C_min",
"of x_ijt and y_ijt in two loops, so that the optimization variables #",
"0, 0.1, 0, 0, 0, 0.9]]) # time (in # of steps) required",
"= {} # state quantity [kg] for i in range(self.I): for j in",
"task j (column), in e.g. kg self.V_max = np.array([[100, 100, 100, 100, 100],",
"flows, float), and can be accessed from there once the method is executed.",
"0, 0, 0], [0, 0, 0, 0.4, 0, 0.6, 0, 0, 0], [0,",
"min c_x'*x + c_y'*y # s.t. A_eq*x + B_eq*y = b_eq # A_ineq*x",
"11 # horizon in number of of steps # Aliases self.I = self.units.__len__()",
"0, 0, -1, -1, -1, -1, 10, 10]) # Optimization problem structure (cvx.Problem",
"s in range(self.S): self.y_st_inflow[s,t] = cvx.Constant(0) self.y_st_outflow[s,t] = cvx.Constant(0) for i in range(self.I):",
"= np.array([np.infty, np.infty, np.infty, 100, 200, 150, 100, np.infty, np.infty]) self.C_min = np.array([0,",
"[] # 1) every intermediate / output state starts with a quantity of",
":return: list of cvx.Constraint \"\"\" constraint_kondili = [] constraint_kondili.append( [self.y_ijt[0,0,1] == 52] )",
"in range(t+1)] )) return constraint_state_eq def construct_konidili_solution_enforce(self): \"\"\" The nominal model with the",
"output state s (column) from task j (row) self.P = np.array([[0, 0, 0,",
"range(T-self.P_j[j]+1): constraint_allocation.append( sum ( sum( [[self.x_ijt[(i,jj,tt)] for jj in range(J)] for tt in",
"enough such that they are completed within T, i.e., no tasks can start",
"construct_allocation_constraint(self): \"\"\" construct the allocation constraints: 1) each unit i is processing at",
") for j in range(J): for t in range(T-self.P_j[j]+1): constraint_allocation.append( sum ( sum(",
"range(self.T)]) - sum([self.y_st_outflow[s,t] for t in range(self.T)])) for s in range(self.S)] ) def",
"# Data # ---- # Definition of the STN (order in the list",
"and saves it in the class attribute self.model as a cvx.Problem type. Constraints",
"range(self.S): self.y_s[s] = cvx.Variable() # auxiliary expressions used in the state equations self.y_st_inflow",
"= 0 self.bool_ix = 0 self.cont_ix = 0 self.m_eq = 0 self.m_ineq =",
"tt in range(t+1)])) def plot_schedule(self, color='red', style='ggplot'): \"\"\" Plot the nominal schedule. :return:",
"cvx.Minimize(self.construct_objective()) # Model # ----- self.model = cvx.Problem(objective, constraints) # Also store the",
"self.model = 0 # Optimization Variables # ---------------------- self.x_ijt = {} # allocation",
"j (column), in e.g. kg self.V_max = np.array([[100, 100, 100, 100, 100], [80,",
"self.m_ineq = 0 def construct_allocation_constraint(self): \"\"\" construct the allocation constraints: 1) each unit",
"for j in range(self.J): for t in range(self.T): self.y_ijt[i,j,t] = cvx.Variable() # state",
"self.n_x+self.n_y) self.c_x = data['c'][range_bool_ix] self.c_y = data['c'][range_cont_ix] self.A_eq = data['A'][:,range_bool_ix] self.B_eq = data['A'][:,range_cont_ix]",
"started # early enough such that they are completed within T, i.e., no",
"range_bool_ix = range(self.n_x) range_cont_ix = range(self.n_x, self.n_x+self.n_y) self.c_x = data['c'][range_bool_ix] self.c_y = data['c'][range_cont_ix]",
"can only perform tasks that are compatible with self.J_i :return: list of cvx.Constraint",
"unaffected) :return: list of cvx.Constraint \"\"\" constraint_kondili = [] constraint_kondili.append( [self.y_ijt[0,0,1] == 52]",
"e.g. kg self.V_max = np.array([[100, 100, 100, 100, 100], [80, 80, 80, 80,",
"# ---- # Definition of the STN (order in the list matters!) self.units",
"<= 1) constraint_box.append(self.y_ijt[i,j,t] >= 0) constraint_box.append(self.y_ijt[i,j,t] <= 1) return constraint_box def construct_units_capacity_constraint(self): \"\"\"",
"quantities, float) - STN.Y_st_inflow and Y_st_outflow (material flows, float) :return: optimal value (float)",
"constraint_state_eq.append( self.C_max[s] >= self.y_s[s] + sum( [self.y_st_inflow[(s,tt)] for tt in range(t+1)] ) -",
"in self.input_states: constraint_state_eq.append( self.y_s[s] == 0 ) # 2) state equations and storage",
"retrieve_standard_model(self, data): \"\"\" Here we store the problem matrices (A_eq, B_eq, b_eq, etc)",
"which we name y_s for s in range(self.S): self.y_s[s] = cvx.Variable() # auxiliary",
"construct_nominal_model(self): \"\"\" Constructs the nominal STN model, and saves it in the class",
"of cvx.Constraint \"\"\" constraint_capacity = [] for i in range(self.I): for j in",
"in range(self.S): self.y_s[s] = cvx.Variable() # auxiliary expressions used in the state equations",
"to execute task j (row) self.rho_in = np.array([[1, 0, 0, 0, 0, 0,",
"to avoid having to implement functions (now the class methods) with exceedingly long",
"for t in range(self.T): for s in range(self.S): self.y_st_inflow[s,t] = cvx.Constant(0) self.y_st_outflow[s,t] =",
"[0, 0, 0, 0, 0.1, 0, 0, 0, 0.9]]) # time (in #",
"the optimization variables # in the standard model do not get mixed up",
"capacity for state s self.C_max = np.array([np.infty, np.infty, np.infty, 100, 200, 150, 100,",
"(float) \"\"\" print 'Constructing nominal model...' self.construct_nominal_model() print 'Solving...' self.model.solve(verbose=True, solver='GUROBI') self.unpack_results() return",
"\"\"\" print 'Constructing nominal model...' self.construct_nominal_model() print 'Solving...' self.model.solve(verbose=True, solver='GUROBI') self.unpack_results() return self.model.value",
"def construct_box_constraint(self): \"\"\" Construct box constraints on x_ijt and y_ijt; useful for testing",
"in range(t+1)] ) - sum( [self.y_st_outflow[(s,tt)] for tt in range(t+1)] )) return constraint_state_eq",
"for i in range(self.I): for j in range(self.J): for t in range(self.T): constraint_capacity.append(",
"sum( [self.y_st_inflow[(s,tt)] for tt in range(t+1)] ) - sum( [self.y_st_outflow[(s,tt)] for tt in",
"solver='GUROBI') self.unpack_results() return self.model.value def unpack_results(self): \"\"\" Once model is solved, transform the",
"return cvx.Constraints, and added in the STN.construst_nominal_model() method. We pack everything in a",
"within unit constraints. :return: list of cvx.Constraint \"\"\" constraint_capacity = [] for i",
"# ----------- constraints = [] constraints.append(self.construct_allocation_constraint()) constraints.append(self.construct_units_capacity_constraint()) constraints.append(self.construct_state_equations_and_storage_constraint()) # can force Kondili's solution",
"for t in range(self.T): for j in range(self.J): for i in range(self.I): self.X_ijt[i,j,t]",
"variables # in the standard model do not get mixed up for i",
"early enough such that they are completed within T, i.e., no tasks can",
"self.retrieve_standard_model(data) def retrieve_standard_model(self, data): \"\"\" Here we store the problem matrices (A_eq, B_eq,",
"- STN.X_ijt (assignments, bool) - STN.Y_ijt (batch sizes, float) - STN.Y_st (material quantities,",
"b_eq # A_ineq*x + B_ineq*y <= b_ineq # x \\in {0,1} self.c_x =",
"can start after T-P_j for i in range(I): for j in range(J): for",
"sum( [self.y_st_outflow[(s,tt)] for tt in range(t+1)] )) constraint_state_eq.append( self.C_max[s] >= self.y_s[s] + sum(",
"self.m_eq = self.A_eq.shape[0] self.m_ineq = self.A_ineq.shape[0] def solve(self): \"\"\" Constructs and solved the",
"dictionary, as returned by cvx.Problem.get_problem_data('ECOS_BB') :return: None \"\"\" n = data['c'].shape[0] self.bool_ix =",
"t in range(self.T): self.x_ijt[i,j,t] = cvx.Bool() # we separate creation of x_ijt and",
"of the input feeds. :return: cvx.Objective \"\"\" return - sum( [self.c[s]*( sum([self.y_st_inflow[s,t] for",
"np.array([0, 0, 0, -1, -1, -1, -1, 10, 10]) # Optimization problem structure",
"of cvx.Constraint \"\"\" constraint_state_eq = [] # 1) every intermediate / output state",
"is solved, transform the solution dictionaries (self.x_ijt, self.y_ijt) into np.arrays for easier inspection/plotting.",
"processed are within unit constraints. :return: list of cvx.Constraint \"\"\" constraint_capacity = []",
"range(self.S): self.Y_st_inflow[s,t] = self.y_st_inflow[s,t].value self.Y_st_outflow[s,t] = self.y_st_outflow[s,t].value self.Y_st[s,t] = self.y_s[s].value + (sum([self.y_st_inflow[s,tt].value for",
"data['c'][range_cont_ix] self.A_eq = data['A'][:,range_bool_ix] self.B_eq = data['A'][:,range_cont_ix] self.b_eq = data['b'] self.A_ineq = data['G'][:,range_bool_ix]",
"i in range(self.I): for j in range(self.J): for t in range(self.T): self.y_ijt[i,j,t] =",
"= cvx.Constant(0) for i in range(self.I): for j in range(self.J): if self.J_i[i,j]: #",
"# indices of the input states self.horizon = 11 # horizon in number",
"# ----- self.model = cvx.Problem(objective, constraints) # Also store the matrices of te",
"counterpart. We only store # the initial state y_s(t=0), which we name y_s",
"0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0,",
"-1, -1, 10, 10]) # Optimization problem structure (cvx.Problem type) self.model = 0",
"self.Y_ijt = np.zeros((self.I,self.J,self.T)) self.Y_st = np.zeros((self.S,self.T)) self.Y_st_inflow = np.zeros((self.S,self.T)) self.Y_st_outflow = np.zeros((self.S,self.T)) #",
"{0,1} self.c_x = 0 self.c_y = 0 self.A_eq = 0 self.A_ineq = 0",
"0, 0, 1, 0, 0], [0, 0, 0, 0, 0.1, 0, 0, 0,",
"j at each t for i in range(I): for t in range(T): constraint_allocation.append(",
"tt in range(t+1)] ) - sum( [self.y_st_outflow[(s,tt)] for tt in range(t+1)] )) constraint_state_eq.append(",
"cvx.Constant(0) for i in range(self.I): for j in range(self.J): if self.J_i[i,j]: # set",
"Objective encodes c'*(y_s(t=end)-y_s(t=0)), i.e., value of the final products minus cost of the",
"0], [0, 0, 0, 0, 0, 2, 0, 0, 0], [0, 0, 0,",
"BIG_M = 40 constraint_allocation = [] # 1) each unit i is processing",
"0, 0, 0], [0, 0.5, 0.5, 0, 0, 0, 0, 0, 0], [0,",
"fractions of output state s (column) produced by task j (row) self.rho_out =",
"(order in the list matters!) self.units = ['Heater', 'Reactor 1', 'Reactor 2', 'Column']",
"data): \"\"\" Here we store the problem matrices (A_eq, B_eq, b_eq, etc) with",
"(sum([self.y_st_inflow[s,tt].value for tt in range(t+1)]) - sum([self.y_st_outflow[s,tt].value for tt in range(t+1)])) def plot_schedule(self,",
"j (row-wise max of P) self.P_j = np.amax(self.P, axis=1) # Capacities # max",
"self.bool_ix = 0 self.cont_ix = 0 self.m_eq = 0 self.m_ineq = 0 def",
"only perform tasks that are compatible with self.J_i :return: list of cvx.Constraint \"\"\"",
"import * class STN(object): def __init__(self): # Data # ---- # Definition of",
"self.A_eq = 0 self.A_ineq = 0 self.B_eq = 0 self.B_ineq = 0 self.b_eq",
"self.b_eq = data['b'] self.A_ineq = data['G'][:,range_bool_ix] self.B_ineq = data['G'][:,range_cont_ix] self.b_ineq = data['h'] self.b_ineq",
"up for i in range(self.I): for j in range(self.J): for t in range(self.T):",
"self.y_ijt[i,j,t].value for t in range(self.T): for s in range(self.S): self.Y_st_inflow[s,t] = self.y_st_inflow[s,t].value self.Y_st_outflow[s,t]",
"[] for i in range(self.I): for j in range(self.J): for t in range(self.T):",
"A', 'Intermediate AB', 'Intermediate BC', 'Impure E', 'Product 1', 'Product 2'] self.input_states =",
"['Feed A', 'Feed B', 'Feed C', 'Hot A', 'Intermediate AB', 'Intermediate BC', 'Impure",
"self.input_states: constraint_state_eq.append( self.y_s[s] == 0 ) # 2) state equations and storage capacities",
"model do not get mixed up for i in range(self.I): for j in",
"'Intermediate BC', 'Impure E', 'Product 1', 'Product 2'] self.input_states = [0, 1, 2]",
"0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0.1,",
"200, 200]]) self.V_min = np.array([[0, 0, 0, 0, 0], [0, 0, 0, 0,",
"list of cvx.Constraint \"\"\" constraint_kondili = [] constraint_kondili.append( [self.y_ijt[0,0,1] == 52] ) constraint_kondili.append(",
"j (row) self.rho_in = np.array([[1, 0, 0, 0, 0, 0, 0, 0, 0],",
"range(self.S): if s not in self.input_states: constraint_state_eq.append( self.y_s[s] == 0 ) # 2)",
"auxiliary expressions used in the state equations self.y_st_inflow = {} self.y_st_outflow = {}",
"= task self.J_i = np.array([[1, 0, 0, 0, 0], [0, 1, 1, 1,",
"= np.array([[1, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 1,",
"there once the method is executed. :return: None \"\"\" for t in range(self.T):",
"50, 50], [200, 200, 200, 200, 200]]) self.V_min = np.array([[0, 0, 0, 0,",
"[[self.x_ijt[(i,jj,tt)] for jj in range(J)] for tt in range(t,t+self.P_j[j])], [] ) ) <=",
"self.b_ineq = data['h'] self.m_eq = self.A_eq.shape[0] self.m_ineq = self.A_ineq.shape[0] def solve(self): \"\"\" Constructs",
"(t-self.P[j,s] >= 0): self.y_st_inflow[s,t] += self.rho_out[j,s]*self.y_ijt[i,j,t-self.P[j,s]] # set outflows self.y_st_outflow[s,t] += self.rho_in[j,s]*self.y_ijt[i,j,t] constraint_state_eq.append(",
"0], [0, 0, 0, 0, 1]]) # Recipes and timing # fractions of",
"list of cvx.Constraint \"\"\" I = self.units.__len__() J = self.tasks.__len__() S = self.states.__len__()",
"[0, 0, 0, 0, 1]]) # Recipes and timing # fractions of input",
"{} # batch size [kg] self.y_s = {} # state quantity [kg] for",
"input state s (column) required to execute task j (row) self.rho_in = np.array([[1,",
"float) :return: optimal value (float) \"\"\" print 'Constructing nominal model...' self.construct_nominal_model() print 'Solving...'",
"in range(self.S): self.y_st_inflow[s,t] = cvx.Constant(0) self.y_st_outflow[s,t] = cvx.Constant(0) for i in range(self.I): for",
"i in range(self.I): for j in range(self.J): if self.J_i[i,j]: # set inflows if",
"the STN model. The data of the problem is in the __init__() method,",
"data['c'].shape[0] self.bool_ix = data['bool_vars_idx'] self.cont_ix = list(set(range(n)) - set(data['bool_vars_idx'])) self.n_x = self.bool_ix.__len__() self.n_y",
"in range(t,t+self.P_j[j])], [] ) ) <= self.P_j[j]*BIG_M*(1 - self.x_ijt[(i,j,t)]) + 1 ) #",
"self.A_ineq.shape[0] def solve(self): \"\"\" Constructs and solved the nominal STN model. The solution",
"0, 0], [0, 0, 0, 0, 0.1, 0, 0, 0, 0.9]]) # time",
"def construct_nominal_model(self): \"\"\" Constructs the nominal STN model, and saves it in the",
"Definition of the STN (order in the list matters!) self.units = ['Heater', 'Reactor",
"return constraint_allocation def construct_box_constraint(self): \"\"\" Construct box constraints on x_ijt and y_ijt; useful",
"self.bool_ix.__len__() self.n_y = self.cont_ix.__len__() range_bool_ix = range(self.n_x) range_cont_ix = range(self.n_x, self.n_x+self.n_y) self.c_x =",
"model...' self.construct_nominal_model() print 'Solving...' self.model.solve(verbose=True, solver='GUROBI') self.unpack_results() return self.model.value def unpack_results(self): \"\"\" Once",
"[0, 0, 0, 0, 0]]) # storage capacity for state s self.C_max =",
"cvx.Problem.get_problem_data('ECOS_BB') :return: None \"\"\" n = data['c'].shape[0] self.bool_ix = data['bool_vars_idx'] self.cont_ix = list(set(range(n))",
"in range(self.T): for s in range(self.S): self.y_st_inflow[s,t] = cvx.Constant(0) self.y_st_outflow[s,t] = cvx.Constant(0) for",
"STN.Y_st (material quantities, float) - STN.Y_st_inflow and Y_st_outflow (material flows, float) :return: optimal",
"output state s (column) produced by task j (row) self.rho_out = np.array([[0, 0,",
"units can only perform tasks that are compatible with self.J_i, and tasks should",
"of steps) required to produce output state s (column) from task j (row)",
"0, 0.8, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1,",
"self.T = self.horizon # Units capability (what tasks can be processed on which",
"E', 'Product 1', 'Product 2'] self.input_states = [0, 1, 2] # indices of",
"transform the solution dictionaries (self.x_ijt, self.y_ijt) into np.arrays for easier inspection/plotting. The np.arrays",
"self.construct_nominal_model() print 'Solving...' self.model.solve(verbose=True, solver='GUROBI') self.unpack_results() return self.model.value def unpack_results(self): \"\"\" Once model",
"= self.y_st_outflow[s,t].value self.Y_st[s,t] = self.y_s[s].value + (sum([self.y_st_inflow[s,tt].value for tt in range(t+1)]) - sum([self.y_st_outflow[s,tt].value",
"tasks that are compatible with self.J_i :return: list of cvx.Constraint \"\"\" I =",
"force Kondili's solution with # constraints.append(self.construct_konidili_solution_enforce()) constraints = sum(constraints, []) # Objective #",
") if t >= T-self.P_j[j]: constraint_allocation.append( self.x_ijt[i,j,t] == 0 ) return constraint_allocation def",
"self.A_ineq = 0 self.B_eq = 0 self.B_ineq = 0 self.b_eq = 0 self.b_ineq",
"cvx.Constraint \"\"\" constraint_capacity = [] for i in range(self.I): for j in range(self.J):",
"constraints.append(self.construct_konidili_solution_enforce()) constraints = sum(constraints, []) # Objective # --------- objective = cvx.Minimize(self.construct_objective()) #",
"self.A_ineq = data['G'][:,range_bool_ix] self.B_ineq = data['G'][:,range_cont_ix] self.b_ineq = data['h'] self.b_ineq = data['h'] self.m_eq",
"constraint_kondili def construct_objective(self): \"\"\" Objective encodes c'*(y_s(t=end)-y_s(t=0)), i.e., value of the final products",
"allocation constraints: 1) each unit i is processing at most one task j",
"plot_stn_schedule(self, self.Y_ijt, color=color, style=style) # imported with plotting if __name__ == '__main__': #",
"-1, -1, -1, 10, 10]) # Optimization problem structure (cvx.Problem type) self.model =",
"'Rea. 1', 'Rea. 2', 'Rea. 3', 'Sep.'] self.states = ['Feed A', 'Feed B',",
"= b_eq # A_ineq*x + B_ineq*y <= b_ineq # x \\in {0,1} self.c_x",
"allow for the robust counterpart. We only store # the initial state y_s(t=0),",
"the nominal STN model. The solution is stored in the np.arrays - STN.X_ijt",
"= 0 self.b_ineq = 0 self.bool_ix = 0 self.cont_ix = 0 self.m_eq =",
"0, 0, 0], [0, 0, 0, 0, 0, 2, 0, 0, 0], [0,",
"0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 1]]) # Recipes",
"= self.A_eq.shape[0] self.m_ineq = self.A_ineq.shape[0] def solve(self): \"\"\" Constructs and solved the nominal",
"0, -1, -1, -1, -1, 10, 10]) # Optimization problem structure (cvx.Problem type)",
"long signatures. \"\"\" import numpy as np import cvxpy as cvx from plotting",
"self.I = self.units.__len__() self.J = self.tasks.__len__() self.S = self.states.__len__() self.T = self.horizon #",
"input states self.horizon = 11 # horizon in number of of steps #",
"cost of the input feeds. :return: cvx.Objective \"\"\" return - sum( [self.c[s]*( sum([self.y_st_inflow[s,t]",
"0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0,",
"solved the nominal STN model. The solution is stored in the np.arrays -",
"j at each t 2) units can only perform tasks that are compatible",
"for s in range(self.S): self.Y_st_inflow[s,t] = self.y_st_inflow[s,t].value self.Y_st_outflow[s,t] = self.y_st_outflow[s,t].value self.Y_st[s,t] = self.y_s[s].value",
"be included as functions that return cvx.Constraints, and added in the STN.construst_nominal_model() method.",
"construct_box_constraint(self): \"\"\" Construct box constraints on x_ijt and y_ijt; useful for testing with",
"0.1, 0, 0, 0, 0.9]]) # time (in # of steps) required to",
"i in range(self.I): for j in range(self.J): for t in range(self.T): constraint_capacity.append( self.x_ijt[i,j,t]*self.V_min[i,j]",
"self.rho_in = np.array([[1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0.5,",
"0 ) # 2) state equations and storage capacities for t in range(self.T):",
"0, 0, 0, 0.1, 0, 0, 0, 0.9]]) # time (in # of",
"The following constraints force the exact same solution as in the paper (the",
"store the matrices of te standard model: data = self.model.get_problem_data('ECOS_BB') self.retrieve_standard_model(data) def retrieve_standard_model(self,",
"0, 0, 2, 0, 0, 0, 1]]) # total execution time of task",
"\"\"\" Here we store the problem matrices (A_eq, B_eq, b_eq, etc) with ordered",
"that are compatible with self.J_i, and tasks should be started # early enough",
"# max capacity of unit i (row) to process task j (column), in",
"np.arrays are saved within the instance attributes - STN.X_ijt (assignments, bool) - STN.Y_ijt",
"self.input_states = [0, 1, 2] # indices of the input states self.horizon =",
"c_y'*y # s.t. A_eq*x + B_eq*y = b_eq # A_ineq*x + B_ineq*y <=",
"in range(self.J): for i in range(self.I): self.X_ijt[i,j,t] = self.x_ijt[i,j,t].value self.Y_ijt[i,j,t] = self.y_ijt[i,j,t].value for",
"self.y_ijt = {} # batch size [kg] self.y_s = {} # state quantity",
"not get mixed up for i in range(self.I): for j in range(self.J): for",
") return constraint_allocation def construct_box_constraint(self): \"\"\" Construct box constraints on x_ijt and y_ijt;",
"[200, 200, 200, 200, 200]]) self.V_min = np.array([[0, 0, 0, 0, 0], [0,",
"data['A'][:,range_cont_ix] self.b_eq = data['b'] self.A_ineq = data['G'][:,range_bool_ix] self.B_ineq = data['G'][:,range_cont_ix] self.b_ineq = data['h']",
"1, 0, 0, 0], [0, 0, 0, 0, 0.6, 0, 0, 0.4, 0],",
"for tt in range(t+1)]) - sum([self.y_st_outflow[s,tt].value for tt in range(t+1)])) def plot_schedule(self, color='red',",
"STN model, and saves it in the class attribute self.model as a cvx.Problem",
"range(T): constraint_allocation.append( self.x_ijt[i,j,t]*(1-self.J_i[i,j]) == 0 ) if t >= T-self.P_j[j]: constraint_allocation.append( self.x_ijt[i,j,t] ==",
"<= self.x_ijt[i,j,t]*self.V_max[i,j] ) return constraint_capacity def construct_state_equations_and_storage_constraint(self): \"\"\" Implementation of state equations, and",
"for j in range(J)] ) <= 1 ) for j in range(J): for",
"constraint_capacity def construct_state_equations_and_storage_constraint(self): \"\"\" Implementation of state equations, and states capacities (storages) :return:",
"each t 2) units can only perform tasks that are compatible with self.J_i",
"in range(self.T): for j in range(self.J): for i in range(self.I): self.X_ijt[i,j,t] = self.x_ijt[i,j,t].value",
"2', 'Column'] self.tasks = ['Heat', 'Rea. 1', 'Rea. 2', 'Rea. 3', 'Sep.'] self.states",
"max of P) self.P_j = np.amax(self.P, axis=1) # Capacities # max capacity of",
"self.Y_st = np.zeros((self.S,self.T)) self.Y_st_inflow = np.zeros((self.S,self.T)) self.Y_st_outflow = np.zeros((self.S,self.T)) # to store the",
"i in range(self.I): self.X_ijt[i,j,t] = self.x_ijt[i,j,t].value self.Y_ijt[i,j,t] = self.y_ijt[i,j,t].value for t in range(self.T):",
"such that they are completed within T, i.e., no tasks can start after",
"T = self.T constraint_box = [] for i in range(I): for j in",
"Implementation of state equations, and states capacities (storages) :return: list of cvx.Constraint \"\"\"",
"STN.Y_st_inflow and STN.Y_st_outflow (material flows, float), and can be accessed from there once",
"= self.y_st_inflow[s,t].value self.Y_st_outflow[s,t] = self.y_st_outflow[s,t].value self.Y_st[s,t] = self.y_s[s].value + (sum([self.y_st_inflow[s,tt].value for tt in",
"200, 150, 100, np.infty, np.infty]) self.C_min = np.array([0, 0, 0, 0, 0, 0,",
"\"\"\" constraint_capacity = [] for i in range(self.I): for j in range(self.J): for",
"2, 0, 0, 0, 1]]) # total execution time of task j (row-wise",
"for s in range(self.S): if s not in self.input_states: constraint_state_eq.append( self.y_s[s] == 0",
"cvx.Constraint \"\"\" I = self.units.__len__() J = self.tasks.__len__() T = self.T constraint_box =",
"= np.zeros((self.S,self.T)) # to store the standard model # min c_x'*x + c_y'*y",
"set inflows if (t-self.P[j,s] >= 0): self.y_st_inflow[s,t] += self.rho_out[j,s]*self.y_ijt[i,j,t-self.P[j,s]] # set outflows self.y_st_outflow[s,t]",
"= [] constraints.append(self.construct_allocation_constraint()) constraints.append(self.construct_units_capacity_constraint()) constraints.append(self.construct_state_equations_and_storage_constraint()) # can force Kondili's solution with # constraints.append(self.construct_konidili_solution_enforce())",
"0.9]]) # time (in # of steps) required to produce output state s",
"0], [0, 0, 0, 0, 0, 0, 1, 0, 0]]) # fractions of",
"self.cont_ix = 0 self.m_eq = 0 self.m_ineq = 0 def construct_allocation_constraint(self): \"\"\" construct",
"t in range(T): constraint_allocation.append( sum( [self.x_ijt[(i,j,t)] for j in range(J)] ) <= 1",
"constraint_box.append(self.x_ijt[i,j,t] <= 1) constraint_box.append(self.y_ijt[i,j,t] >= 0) constraint_box.append(self.y_ijt[i,j,t] <= 1) return constraint_box def construct_units_capacity_constraint(self):",
"type. Constraints can be added/removed here. :return: None \"\"\" # Constraints # -----------",
"constraint_allocation.append( self.x_ijt[i,j,t]*(1-self.J_i[i,j]) == 0 ) if t >= T-self.P_j[j]: constraint_allocation.append( self.x_ijt[i,j,t] == 0",
"0, 0, 0, 0]) # objective to maximize (revenue from the states) self.c",
"has several optimizers. The following constraints force the exact same solution as in",
"self.C_max[s] >= self.y_s[s] + sum( [self.y_st_inflow[(s,tt)] for tt in range(t+1)] ) - sum(",
"for easier inspection/plotting. The np.arrays are saved within the instance attributes - STN.X_ijt",
"{} self.y_st_outflow = {} # Attributes # ---------- # to store results self.X_ijt",
"self.y_s = {} # state quantity [kg] for i in range(self.I): for j",
"= cvx.Problem(objective, constraints) # Also store the matrices of te standard model: data",
"produced by task j (row) self.rho_out = np.array([[0, 0, 0, 1, 0, 0,",
"self.J_i :return: list of cvx.Constraint \"\"\" I = self.units.__len__() J = self.tasks.__len__() S",
"variables instead of bools. :return: list of cvx.Constraint \"\"\" I = self.units.__len__() J",
"most one task j at each t for i in range(I): for t",
"and y_ijt in two loops, so that the optimization variables # in the",
"timing # fractions of input state s (column) required to execute task j",
"task j at each t for i in range(I): for t in range(T):",
"constraint_capacity = [] for i in range(self.I): for j in range(self.J): for t",
"0, 0, 2, 0, 0, 2, 0], [0, 0, 0, 0, 0, 0,",
"self.B_ineq = data['G'][:,range_cont_ix] self.b_ineq = data['h'] self.b_ineq = data['h'] self.m_eq = self.A_eq.shape[0] self.m_ineq",
"B_eq*y = b_eq # A_ineq*x + B_ineq*y <= b_ineq # x \\in {0,1}",
"everything in a class to avoid having to implement functions (now the class",
") # 2) state equations and storage capacities for t in range(self.T): for",
":return: None \"\"\" n = data['c'].shape[0] self.bool_ix = data['bool_vars_idx'] self.cont_ix = list(set(range(n)) -",
"is in the __init__() method, and can be changed. Additional constraints can be",
"Y_st_outflow (material flows, float) :return: optimal value (float) \"\"\" print 'Constructing nominal model...'",
"200, 200, 200]]) self.V_min = np.array([[0, 0, 0, 0, 0], [0, 0, 0,",
"100, 100], [80, 80, 80, 80, 80], [50, 50, 50, 50, 50], [200,",
"constraint_allocation.append( sum ( sum( [[self.x_ijt[(i,jj,tt)] for jj in range(J)] for tt in range(t,t+self.P_j[j])],",
"# A_ineq*x + B_ineq*y <= b_ineq # x \\in {0,1} self.c_x = 0",
"in range(self.T): for s in range(self.S): self.Y_st_inflow[s,t] = self.y_st_inflow[s,t].value self.Y_st_outflow[s,t] = self.y_st_outflow[s,t].value self.Y_st[s,t]",
"\"\"\" Construct box constraints on x_ijt and y_ijt; useful for testing with continuous",
"= self.y_ijt[i,j,t].value for t in range(self.T): for s in range(self.S): self.Y_st_inflow[s,t] = self.y_st_inflow[s,t].value",
"on the STN model. The data of the problem is in the __init__()",
"[self.y_st_inflow[(s,tt)] for tt in range(t+1)] ) - sum( [self.y_st_outflow[(s,tt)] for tt in range(t+1)]",
"+ sum( [self.y_st_inflow[(s,tt)] for tt in range(t+1)] ) - sum( [self.y_st_outflow[(s,tt)] for tt",
"# constraints.append(self.construct_konidili_solution_enforce()) constraints = sum(constraints, []) # Objective # --------- objective = cvx.Minimize(self.construct_objective())",
"and Y_st_outflow (material flows, float) :return: optimal value (float) \"\"\" print 'Constructing nominal",
"0, 0, 0], [0, 0, 0, 0, 2, 0, 0, 2, 0], [0,",
"states) self.c = np.array([0, 0, 0, -1, -1, -1, -1, 10, 10]) #",
"only store # the initial state y_s(t=0), which we name y_s for s",
"10]) # Optimization problem structure (cvx.Problem type) self.model = 0 # Optimization Variables",
"[0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0,",
"should be started # early enough such that they are completed within T,",
"constraint_allocation.append( sum( [self.x_ijt[(i,j,t)] for j in range(J)] ) <= 1 ) for j",
"\"\"\" The nominal model with the data of Kondili's paper has several optimizers.",
"class attribute self.model as a cvx.Problem type. Constraints can be added/removed here. :return:",
"[0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 0, 0,",
"1]]) # Recipes and timing # fractions of input state s (column) required",
"np.array([[0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0,",
":return: list of cvx.Constraint \"\"\" constraint_capacity = [] for i in range(self.I): for",
"<= self.y_s[s] + sum( [self.y_st_inflow[(s,tt)] for tt in range(t+1)] ) - sum( [self.y_st_outflow[(s,tt)]",
"self.y_st_inflow[s,t].value self.Y_st_outflow[s,t] = self.y_st_outflow[s,t].value self.Y_st[s,t] = self.y_s[s].value + (sum([self.y_st_inflow[s,tt].value for tt in range(t+1)])",
"\"\"\" Ensure maximum and minimum sizes of the batches to be processed are",
"return - sum( [self.c[s]*( sum([self.y_st_inflow[s,t] for t in range(self.T)]) - sum([self.y_st_outflow[s,t] for t",
"0, 0, 0]) # objective to maximize (revenue from the states) self.c =",
"0, 0, 1, 0, 0]]) # fractions of output state s (column) produced",
"np.array([[1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0.5, 0.5, 0,",
"self.tasks.__len__() self.S = self.states.__len__() self.T = self.horizon # Units capability (what tasks can",
"self.y_st_outflow = {} # Attributes # ---------- # to store results self.X_ijt =",
"the standard model do not get mixed up for i in range(self.I): for",
"t in range(self.T): for s in range(self.S): self.y_st_inflow[s,t] = cvx.Constant(0) self.y_st_outflow[s,t] = cvx.Constant(0)",
"= ['Heater', 'Reactor 1', 'Reactor 2', 'Column'] self.tasks = ['Heat', 'Rea. 1', 'Rea.",
"to store the standard model # min c_x'*x + c_y'*y # s.t. A_eq*x",
"self.y_ijt) into np.arrays for easier inspection/plotting. The np.arrays are saved within the instance",
"np.zeros((self.S,self.T)) self.Y_st_inflow = np.zeros((self.S,self.T)) self.Y_st_outflow = np.zeros((self.S,self.T)) # to store the standard model",
"- STN.Y_st (material quantities, float) - STN.Y_st_inflow and Y_st_outflow (material flows, float) :return:",
"0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 2, 0, 0,",
"time of task j (row-wise max of P) self.P_j = np.amax(self.P, axis=1) #",
"0) constraint_box.append(self.x_ijt[i,j,t] <= 1) constraint_box.append(self.y_ijt[i,j,t] >= 0) constraint_box.append(self.y_ijt[i,j,t] <= 1) return constraint_box def",
"useful for testing with continuous variables instead of bools. :return: list of cvx.Constraint",
"0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0]]) # fractions",
"of input state s (column) required to execute task j (row) self.rho_in =",
"== 52] ) constraint_kondili.append( [self.y_ijt[1,1,0] == 80] ) return constraint_kondili def construct_objective(self): \"\"\"",
"100, np.infty, np.infty]) self.C_min = np.array([0, 0, 0, 0, 0, 0, 0, 0,",
"<= b_ineq # x \\in {0,1} self.c_x = 0 self.c_y = 0 self.A_eq",
"sum( [self.y_st_outflow[(s,tt)] for tt in range(t+1)] )) return constraint_state_eq def construct_konidili_solution_enforce(self): \"\"\" The",
"y_ijt in two loops, so that the optimization variables # in the standard",
"= self.bool_ix.__len__() self.n_y = self.cont_ix.__len__() range_bool_ix = range(self.n_x) range_cont_ix = range(self.n_x, self.n_x+self.n_y) self.c_x",
"s in range(self.S): self.Y_st_inflow[s,t] = self.y_st_inflow[s,t].value self.Y_st_outflow[s,t] = self.y_st_outflow[s,t].value self.Y_st[s,t] = self.y_s[s].value +",
"(row) self.P = np.array([[0, 0, 0, 1, 0, 0, 0, 0, 0], [0,",
"1, 0, 0], [0, 0, 0, 0, 0.1, 0, 0, 0, 0.9]]) #",
"A_ineq*x + B_ineq*y <= b_ineq # x \\in {0,1} self.c_x = 0 self.c_y",
"to process task j (column), in e.g. kg self.V_max = np.array([[100, 100, 100,",
"at each t 2) units can only perform tasks that are compatible with",
"range(self.S)] ) def construct_nominal_model(self): \"\"\" Constructs the nominal STN model, and saves it",
"x_ijt and y_ijt in two loops, so that the optimization variables # in",
"i in range(I): for j in range(J): for t in range(T): constraint_allocation.append( self.x_ijt[i,j,t]*(1-self.J_i[i,j])",
"self.y_st_inflow = {} self.y_st_outflow = {} # Attributes # ---------- # to store",
"construct_konidili_solution_enforce(self): \"\"\" The nominal model with the data of Kondili's paper has several",
"range(J): for t in range(T): constraint_box.append(self.x_ijt[i,j,t] >= 0) constraint_box.append(self.x_ijt[i,j,t] <= 1) constraint_box.append(self.y_ijt[i,j,t] >=",
"t for i in range(I): for t in range(T): constraint_allocation.append( sum( [self.x_ijt[(i,j,t)] for",
"0, 0, 0, 0, 0, 0, 0], [0, 0.5, 0.5, 0, 0, 0,",
"j in range(J)] ) <= 1 ) for j in range(J): for t",
"cvx.Constraint \"\"\" I = self.units.__len__() J = self.tasks.__len__() S = self.states.__len__() T =",
"+= self.rho_in[j,s]*self.y_ijt[i,j,t] constraint_state_eq.append( self.C_min[s] <= self.y_s[s] + sum( [self.y_st_inflow[(s,tt)] for tt in range(t+1)]",
"self.c = np.array([0, 0, 0, -1, -1, -1, -1, 10, 10]) # Optimization",
"(bool) self.y_ijt = {} # batch size [kg] self.y_s = {} # state",
"we name y_s for s in range(self.S): self.y_s[s] = cvx.Variable() # auxiliary expressions",
"0.2, 0, 0.8, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0,",
"P) self.P_j = np.amax(self.P, axis=1) # Capacities # max capacity of unit i",
"constraint_kondili.append( [self.y_ijt[1,1,0] == 80] ) return constraint_kondili def construct_objective(self): \"\"\" Objective encodes c'*(y_s(t=end)-y_s(t=0)),",
"for the robust counterpart. We only store # the initial state y_s(t=0), which",
"0]]) # fractions of output state s (column) produced by task j (row)",
"time (in # of steps) required to produce output state s (column) from",
"Kondili's paper has several optimizers. The following constraints force the exact same solution",
"# Objective # --------- objective = cvx.Minimize(self.construct_objective()) # Model # ----- self.model =",
"Also store the matrices of te standard model: data = self.model.get_problem_data('ECOS_BB') self.retrieve_standard_model(data) def",
"the batches to be processed are within unit constraints. :return: list of cvx.Constraint",
"0, 0, 0, 0, 0, 0]) # objective to maximize (revenue from the",
"# x \\in {0,1} self.c_x = 0 self.c_y = 0 self.A_eq = 0",
"for t in range(T): constraint_allocation.append( self.x_ijt[i,j,t]*(1-self.J_i[i,j]) == 0 ) if t >= T-self.P_j[j]:",
"instance attributes - STN.X_ijt (assignments, bool) - STN.Y_ijt (batch sizes, float) - STN.Y_st",
"0, 1]]) # Recipes and timing # fractions of input state s (column)",
"(row) self.rho_in = np.array([[1, 0, 0, 0, 0, 0, 0, 0, 0], [0,",
"= np.array([[0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0,",
"j in range(self.J): for t in range(self.T): constraint_capacity.append( self.x_ijt[i,j,t]*self.V_min[i,j] <= self.y_ijt[i,j,t] ) constraint_capacity.append(",
"constraint_box def construct_units_capacity_constraint(self): \"\"\" Ensure maximum and minimum sizes of the batches to",
"0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0],",
"equations are eliminated to allow for the robust counterpart. We only store #",
"capacities for t in range(self.T): for s in range(self.S): self.y_st_inflow[s,t] = cvx.Constant(0) self.y_st_outflow[s,t]",
"0.6, 0, 0, 0], [0, 0, 0.2, 0, 0.8, 0, 0, 0, 0],",
"0 self.b_eq = 0 self.b_ineq = 0 self.bool_ix = 0 self.cont_ix = 0",
"= cvx.Constant(0) self.y_st_outflow[s,t] = cvx.Constant(0) for i in range(self.I): for j in range(self.J):",
"the STN.construst_nominal_model() method. We pack everything in a class to avoid having to",
"tt in range(t+1)] ) - sum( [self.y_st_outflow[(s,tt)] for tt in range(t+1)] )) return",
"0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]) #",
"np.infty, np.infty]) self.C_min = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0])",
"the input feeds. :return: cvx.Objective \"\"\" return - sum( [self.c[s]*( sum([self.y_st_inflow[s,t] for t",
"results self.X_ijt = np.zeros((self.I,self.J,self.T)) self.Y_ijt = np.zeros((self.I,self.J,self.T)) self.Y_st = np.zeros((self.S,self.T)) self.Y_st_inflow = np.zeros((self.S,self.T))",
"here. :return: None \"\"\" # Constraints # ----------- constraints = [] constraints.append(self.construct_allocation_constraint()) constraints.append(self.construct_units_capacity_constraint())",
"'Solving...' self.model.solve(verbose=True, solver='GUROBI') self.unpack_results() return self.model.value def unpack_results(self): \"\"\" Once model is solved,",
"self.unpack_results() return self.model.value def unpack_results(self): \"\"\" Once model is solved, transform the solution",
"200]]) self.V_min = np.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0],",
"the np.arrays - STN.X_ijt (assignments, bool) - STN.Y_ijt (batch sizes, float) - STN.Y_st",
"solution dictionaries (self.x_ijt, self.y_ijt) into np.arrays for easier inspection/plotting. The np.arrays are saved",
"np.zeros((self.I,self.J,self.T)) self.Y_st = np.zeros((self.S,self.T)) self.Y_st_inflow = np.zeros((self.S,self.T)) self.Y_st_outflow = np.zeros((self.S,self.T)) # to store",
"+ 1 ) # 2) units can only perform tasks that are compatible",
"and solved the nominal STN model. The solution is stored in the np.arrays",
"\"\"\" Once model is solved, transform the solution dictionaries (self.x_ijt, self.y_ijt) into np.arrays",
"of te standard model: data = self.model.get_problem_data('ECOS_BB') self.retrieve_standard_model(data) def retrieve_standard_model(self, data): \"\"\" Here",
"self.T constraint_box = [] for i in range(I): for j in range(J): for",
":return: list of cvx.Constraint \"\"\" I = self.units.__len__() J = self.tasks.__len__() S =",
"in range(t+1)]) - sum([self.y_st_outflow[s,tt].value for tt in range(t+1)])) def plot_schedule(self, color='red', style='ggplot'): \"\"\"",
"np import cvxpy as cvx from plotting import * class STN(object): def __init__(self):",
"1) each unit i is processing at most one task j at each",
"= 40 constraint_allocation = [] # 1) each unit i is processing at",
"0], [0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0,",
"are completed within T, i.e., no tasks can start after T-P_j for i",
"in range(self.I): self.X_ijt[i,j,t] = self.x_ijt[i,j,t].value self.Y_ijt[i,j,t] = self.y_ijt[i,j,t].value for t in range(self.T): for",
"[80, 80, 80, 80, 80], [50, 50, 50, 50, 50], [200, 200, 200,",
"horizon in number of of steps # Aliases self.I = self.units.__len__() self.J =",
"# set inflows if (t-self.P[j,s] >= 0): self.y_st_inflow[s,t] += self.rho_out[j,s]*self.y_ijt[i,j,t-self.P[j,s]] # set outflows",
"[self.c[s]*( sum([self.y_st_inflow[s,t] for t in range(self.T)]) - sum([self.y_st_outflow[s,t] for t in range(self.T)])) for",
"Plot the nominal schedule. :return: None \"\"\" plot_stn_schedule(self, self.Y_ijt, color=color, style=style) # imported",
"np.amax(self.P, axis=1) # Capacities # max capacity of unit i (row) to process",
"for i in range(self.I): self.X_ijt[i,j,t] = self.x_ijt[i,j,t].value self.Y_ijt[i,j,t] = self.y_ijt[i,j,t].value for t in",
"from the states) self.c = np.array([0, 0, 0, -1, -1, -1, -1, 10,",
"Aliases self.I = self.units.__len__() self.J = self.tasks.__len__() self.S = self.states.__len__() self.T = self.horizon",
"0, 0, 0, 0, 0], [0, 0.5, 0.5, 0, 0, 0, 0, 0,",
"constraint_kondili = [] constraint_kondili.append( [self.y_ijt[0,0,1] == 52] ) constraint_kondili.append( [self.y_ijt[1,1,0] == 80] )",
"for tt in range(t+1)] ) - sum( [self.y_st_outflow[(s,tt)] for tt in range(t+1)] ))",
"required to produce output state s (column) from task j (row) self.P =",
"np.infty, np.infty, 100, 200, 150, 100, np.infty, np.infty]) self.C_min = np.array([0, 0, 0,",
"the standard model # min c_x'*x + c_y'*y # s.t. A_eq*x + B_eq*y",
"with a quantity of 0 kg for s in range(self.S): if s not",
"as np import cvxpy as cvx from plotting import * class STN(object): def",
"0, 0, 0, 2, 0, 0, 0], [0, 0, 0, 0, 2, 0,",
"the states) self.c = np.array([0, 0, 0, -1, -1, -1, -1, 10, 10])",
"robust counterpart. We only store # the initial state y_s(t=0), which we name",
"0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 2,",
"range(self.n_x, self.n_x+self.n_y) self.c_x = data['c'][range_bool_ix] self.c_y = data['c'][range_cont_ix] self.A_eq = data['A'][:,range_bool_ix] self.B_eq =",
"<= 1 ) for j in range(J): for t in range(T-self.P_j[j]+1): constraint_allocation.append( sum",
"and storage capacities for t in range(self.T): for s in range(self.S): self.y_st_inflow[s,t] =",
"range(t+1)] )) constraint_state_eq.append( self.C_max[s] >= self.y_s[s] + sum( [self.y_st_inflow[(s,tt)] for tt in range(t+1)]",
"The solution is stored in the np.arrays - STN.X_ijt (assignments, bool) - STN.Y_ijt",
"range(self.T)])) for s in range(self.S)] ) def construct_nominal_model(self): \"\"\" Constructs the nominal STN",
"equations, and states capacities (storages) :return: list of cvx.Constraint \"\"\" constraint_state_eq = []",
"state equations self.y_st_inflow = {} self.y_st_outflow = {} # Attributes # ---------- #",
"task j (row) self.P = np.array([[0, 0, 0, 1, 0, 0, 0, 0,",
"self.y_st_inflow[s,t] = cvx.Constant(0) self.y_st_outflow[s,t] = cvx.Constant(0) for i in range(self.I): for j in",
"# to store the standard model # min c_x'*x + c_y'*y # s.t.",
"constraint_box = [] for i in range(I): for j in range(J): for t",
"intermediate / output state starts with a quantity of 0 kg for s",
"self.rho_out[j,s]*self.y_ijt[i,j,t-self.P[j,s]] # set outflows self.y_st_outflow[s,t] += self.rho_in[j,s]*self.y_ijt[i,j,t] constraint_state_eq.append( self.C_min[s] <= self.y_s[s] + sum(",
"self.states.__len__() self.T = self.horizon # Units capability (what tasks can be processed on",
"optimization variables # in the standard model do not get mixed up for",
"- sum( [self.c[s]*( sum([self.y_st_inflow[s,t] for t in range(self.T)]) - sum([self.y_st_outflow[s,t] for t in",
"- STN.X_ijt (assignments, bool) - STN.Y_ijt (batch sizes, float) - STN.Y_st (stored material",
"# Model # ----- self.model = cvx.Problem(objective, constraints) # Also store the matrices",
"solve(self): \"\"\" Constructs and solved the nominal STN model. The solution is stored",
"T = self.T # TODO BIG-M for allocation BIG_M = 40 constraint_allocation =",
")) return constraint_state_eq def construct_konidili_solution_enforce(self): \"\"\" The nominal model with the data of",
"batches to be processed are within unit constraints. :return: list of cvx.Constraint \"\"\"",
"and y_ijt; useful for testing with continuous variables instead of bools. :return: list",
"state s (column) produced by task j (row) self.rho_out = np.array([[0, 0, 0,",
"self.V_min = np.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0,",
"+ B_ineq*y <= b_ineq # x \\in {0,1} self.c_x = 0 self.c_y =",
"(storages) :return: list of cvx.Constraint \"\"\" constraint_state_eq = [] # 1) every intermediate",
"a quantity of 0 kg for s in range(self.S): if s not in",
") - sum( [self.y_st_outflow[(s,tt)] for tt in range(t+1)] )) return constraint_state_eq def construct_konidili_solution_enforce(self):",
"{} # state quantity [kg] for i in range(self.I): for j in range(self.J):",
"def __init__(self): # Data # ---- # Definition of the STN (order in",
"= np.zeros((self.I,self.J,self.T)) self.Y_ijt = np.zeros((self.I,self.J,self.T)) self.Y_st = np.zeros((self.S,self.T)) self.Y_st_inflow = np.zeros((self.S,self.T)) self.Y_st_outflow =",
"# 1) each unit i is processing at most one task j at",
"of Kondili's paper has several optimizers. The following constraints force the exact same",
"they are completed within T, i.e., no tasks can start after T-P_j for",
"self.y_st_outflow[s,t] = cvx.Constant(0) for i in range(self.I): for j in range(self.J): if self.J_i[i,j]:",
"t >= T-self.P_j[j]: constraint_allocation.append( self.x_ijt[i,j,t] == 0 ) return constraint_allocation def construct_box_constraint(self): \"\"\"",
"0, 0, 0], [0, 0, 0, 0, 0.6, 0, 0, 0.4, 0], [0,",
"with ordered columns. :param data: dictionary, as returned by cvx.Problem.get_problem_data('ECOS_BB') :return: None \"\"\"",
"set outflows self.y_st_outflow[s,t] += self.rho_in[j,s]*self.y_ijt[i,j,t] constraint_state_eq.append( self.C_min[s] <= self.y_s[s] + sum( [self.y_st_inflow[(s,tt)] for",
":return: None \"\"\" plot_stn_schedule(self, self.Y_ijt, color=color, style=style) # imported with plotting if __name__",
"Model # ----- self.model = cvx.Problem(objective, constraints) # Also store the matrices of",
"# row = unit, column = task self.J_i = np.array([[1, 0, 0, 0,",
"constraints = [] constraints.append(self.construct_allocation_constraint()) constraints.append(self.construct_units_capacity_constraint()) constraints.append(self.construct_state_equations_and_storage_constraint()) # can force Kondili's solution with #",
">= 0) constraint_box.append(self.x_ijt[i,j,t] <= 1) constraint_box.append(self.y_ijt[i,j,t] >= 0) constraint_box.append(self.y_ijt[i,j,t] <= 1) return constraint_box",
"# in the standard model do not get mixed up for i in",
"data['c'][range_bool_ix] self.c_y = data['c'][range_cont_ix] self.A_eq = data['A'][:,range_bool_ix] self.B_eq = data['A'][:,range_cont_ix] self.b_eq = data['b']",
"1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 2, 0,",
"the method is executed. :return: None \"\"\" for t in range(self.T): for j",
"data['G'][:,range_cont_ix] self.b_ineq = data['h'] self.b_ineq = data['h'] self.m_eq = self.A_eq.shape[0] self.m_ineq = self.A_ineq.shape[0]",
"at most one task j at each t 2) units can only perform",
"= data['G'][:,range_bool_ix] self.B_ineq = data['G'][:,range_cont_ix] self.b_ineq = data['h'] self.b_ineq = data['h'] self.m_eq =",
"\"\"\" Plot the nominal schedule. :return: None \"\"\" plot_stn_schedule(self, self.Y_ijt, color=color, style=style) #",
"= np.amax(self.P, axis=1) # Capacities # max capacity of unit i (row) to",
"0 self.c_y = 0 self.A_eq = 0 self.A_ineq = 0 self.B_eq = 0",
"constraint_state_eq.append( self.y_s[s] == 0 ) # 2) state equations and storage capacities for",
"80], [50, 50, 50, 50, 50], [200, 200, 200, 200, 200]]) self.V_min =",
"tasks can start after T-P_j for i in range(I): for j in range(J):",
"def retrieve_standard_model(self, data): \"\"\" Here we store the problem matrices (A_eq, B_eq, b_eq,",
"one task j at each t 2) units can only perform tasks that",
"Once model is solved, transform the solution dictionaries (self.x_ijt, self.y_ijt) into np.arrays for",
"self.A_eq = data['A'][:,range_bool_ix] self.B_eq = data['A'][:,range_cont_ix] self.b_eq = data['b'] self.A_ineq = data['G'][:,range_bool_ix] self.B_ineq",
"( sum( [[self.x_ijt[(i,jj,tt)] for jj in range(J)] for tt in range(t,t+self.P_j[j])], [] )",
"self.B_ineq = 0 self.b_eq = 0 self.b_ineq = 0 self.bool_ix = 0 self.cont_ix",
"\"\"\" Implementation of a scheduling system based on the STN model. The data",
"returned by cvx.Problem.get_problem_data('ECOS_BB') :return: None \"\"\" n = data['c'].shape[0] self.bool_ix = data['bool_vars_idx'] self.cont_ix",
"self.A_eq.shape[0] self.m_ineq = self.A_ineq.shape[0] def solve(self): \"\"\" Constructs and solved the nominal STN",
"columns. :param data: dictionary, as returned by cvx.Problem.get_problem_data('ECOS_BB') :return: None \"\"\" n =",
"data['bool_vars_idx'] self.cont_ix = list(set(range(n)) - set(data['bool_vars_idx'])) self.n_x = self.bool_ix.__len__() self.n_y = self.cont_ix.__len__() range_bool_ix",
"on x_ijt and y_ijt; useful for testing with continuous variables instead of bools.",
"A', 'Feed B', 'Feed C', 'Hot A', 'Intermediate AB', 'Intermediate BC', 'Impure E',",
"(material flows, float), and can be accessed from there once the method is",
"0, 2, 0, 0, 0], [0, 0, 0, 0, 2, 0, 0, 2,",
"range(self.J): for t in range(self.T): constraint_capacity.append( self.x_ijt[i,j,t]*self.V_min[i,j] <= self.y_ijt[i,j,t] ) constraint_capacity.append( self.y_ijt[i,j,t] <=",
"paper (the objective is unaffected) :return: list of cvx.Constraint \"\"\" constraint_kondili = []",
"for t in range(self.T): for s in range(self.S): self.Y_st_inflow[s,t] = self.y_st_inflow[s,t].value self.Y_st_outflow[s,t] =",
"0], [0, 0, 0, 0, 0.6, 0, 0, 0.4, 0], [0, 0, 0,",
"return constraint_state_eq def construct_konidili_solution_enforce(self): \"\"\" The nominal model with the data of Kondili's",
"if t >= T-self.P_j[j]: constraint_allocation.append( self.x_ijt[i,j,t] == 0 ) return constraint_allocation def construct_box_constraint(self):",
"constraint_state_eq def construct_konidili_solution_enforce(self): \"\"\" The nominal model with the data of Kondili's paper",
"to allow for the robust counterpart. We only store # the initial state",
"constraint_capacity.append( self.x_ijt[i,j,t]*self.V_min[i,j] <= self.y_ijt[i,j,t] ) constraint_capacity.append( self.y_ijt[i,j,t] <= self.x_ijt[i,j,t]*self.V_max[i,j] ) return constraint_capacity def",
"for t in range(T): constraint_allocation.append( sum( [self.x_ijt[(i,j,t)] for j in range(J)] ) <=",
"(self.x_ijt, self.y_ijt) into np.arrays for easier inspection/plotting. The np.arrays are saved within the",
"0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1,",
"constraint_state_eq.append( self.C_min[s] <= self.y_s[s] + sum( [self.y_st_inflow[(s,tt)] for tt in range(t+1)] ) -",
"data['b'] self.A_ineq = data['G'][:,range_bool_ix] self.B_ineq = data['G'][:,range_cont_ix] self.b_ineq = data['h'] self.b_ineq = data['h']",
"'Hot A', 'Intermediate AB', 'Intermediate BC', 'Impure E', 'Product 1', 'Product 2'] self.input_states",
"encodes c'*(y_s(t=end)-y_s(t=0)), i.e., value of the final products minus cost of the input",
"= [] # 1) each unit i is processing at most one task",
"float) - STN.Y_st_inflow and STN.Y_st_outflow (material flows, float), and can be accessed from",
"execute task j (row) self.rho_in = np.array([[1, 0, 0, 0, 0, 0, 0,",
"of cvx.Constraint \"\"\" I = self.units.__len__() J = self.tasks.__len__() S = self.states.__len__() T",
"print 'Constructing nominal model...' self.construct_nominal_model() print 'Solving...' self.model.solve(verbose=True, solver='GUROBI') self.unpack_results() return self.model.value def",
"list of cvx.Constraint \"\"\" constraint_capacity = [] for i in range(self.I): for j",
"0]) # objective to maximize (revenue from the states) self.c = np.array([0, 0,",
"cvx.Constraint \"\"\" constraint_state_eq = [] # 1) every intermediate / output state starts",
"value of the final products minus cost of the input feeds. :return: cvx.Objective",
"of task j (row-wise max of P) self.P_j = np.amax(self.P, axis=1) # Capacities",
"import cvxpy as cvx from plotting import * class STN(object): def __init__(self): #",
"- STN.Y_st (stored material quantities, float) - STN.Y_st_inflow and STN.Y_st_outflow (material flows, float),",
"1, 1, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 1]])",
"states self.horizon = 11 # horizon in number of of steps # Aliases",
"(assignments, bool) - STN.Y_ijt (batch sizes, float) - STN.Y_st (material quantities, float) -",
"for j in range(self.J): if self.J_i[i,j]: # set inflows if (t-self.P[j,s] >= 0):",
"are within unit constraints. :return: list of cvx.Constraint \"\"\" constraint_capacity = [] for",
"['Heater', 'Reactor 1', 'Reactor 2', 'Column'] self.tasks = ['Heat', 'Rea. 1', 'Rea. 2',",
"for t in range(T-self.P_j[j]+1): constraint_allocation.append( sum ( sum( [[self.x_ijt[(i,jj,tt)] for jj in range(J)]",
"in range(J)] for tt in range(t,t+self.P_j[j])], [] ) ) <= self.P_j[j]*BIG_M*(1 - self.x_ijt[(i,j,t)])",
"= 0 self.A_eq = 0 self.A_ineq = 0 self.B_eq = 0 self.B_ineq =",
"by cvx.Problem.get_problem_data('ECOS_BB') :return: None \"\"\" n = data['c'].shape[0] self.bool_ix = data['bool_vars_idx'] self.cont_ix =",
"to maximize (revenue from the states) self.c = np.array([0, 0, 0, -1, -1,",
"range(self.J): if self.J_i[i,j]: # set inflows if (t-self.P[j,s] >= 0): self.y_st_inflow[s,t] += self.rho_out[j,s]*self.y_ijt[i,j,t-self.P[j,s]]",
"imported with plotting if __name__ == '__main__': # example usage of the class",
"= cvx.Variable() # auxiliary expressions used in the state equations self.y_st_inflow = {}",
"0], [0, 0, 0, 0, 2, 0, 0, 0, 1]]) # total execution",
"every intermediate / output state starts with a quantity of 0 kg for",
"# Attributes # ---------- # to store results self.X_ijt = np.zeros((self.I,self.J,self.T)) self.Y_ijt =",
"self.n_y = self.cont_ix.__len__() range_bool_ix = range(self.n_x) range_cont_ix = range(self.n_x, self.n_x+self.n_y) self.c_x = data['c'][range_bool_ix]",
"is stored in the np.arrays - STN.X_ijt (assignments, bool) - STN.Y_ijt (batch sizes,",
"in range(T): constraint_allocation.append( sum( [self.x_ijt[(i,j,t)] for j in range(J)] ) <= 1 )",
"# allocation variable (bool) self.y_ijt = {} # batch size [kg] self.y_s =",
"nominal STN model, and saves it in the class attribute self.model as a",
"0], [0, 0.5, 0.5, 0, 0, 0, 0, 0, 0], [0, 0, 0,",
"with continuous variables instead of bools. :return: list of cvx.Constraint \"\"\" I =",
"We only store # the initial state y_s(t=0), which we name y_s for",
"of cvx.Constraint \"\"\" I = self.units.__len__() J = self.tasks.__len__() T = self.T constraint_box",
"0, 0.6, 0, 0, 0.4, 0], [0, 0, 0, 0, 0, 0, 1,",
"in range(self.T)]) - sum([self.y_st_outflow[s,t] for t in range(self.T)])) for s in range(self.S)] )",
"data['h'] self.b_ineq = data['h'] self.m_eq = self.A_eq.shape[0] self.m_ineq = self.A_ineq.shape[0] def solve(self): \"\"\"",
"be started # early enough such that they are completed within T, i.e.,",
"2) state equations and storage capacities for t in range(self.T): for s in",
"for tt in range(t+1)])) def plot_schedule(self, color='red', style='ggplot'): \"\"\" Plot the nominal schedule.",
"1, 0, 0], [0, 0, 0, 0, 2, 0, 0, 0, 1]]) #",
"tasks that are compatible with self.J_i, and tasks should be started # early",
"0, 0, 0, 0, 0], [0, 0, 0, 0.4, 0, 0.6, 0, 0,",
"style=style) # imported with plotting if __name__ == '__main__': # example usage of",
"'Impure E', 'Product 1', 'Product 2'] self.input_states = [0, 1, 2] # indices",
"of a scheduling system based on the STN model. The data of the",
"0 self.A_ineq = 0 self.B_eq = 0 self.B_ineq = 0 self.b_eq = 0",
"quantity [kg] for i in range(self.I): for j in range(self.J): for t in",
"of the STN (order in the list matters!) self.units = ['Heater', 'Reactor 1',",
"separate creation of x_ijt and y_ijt in two loops, so that the optimization",
"for tt in range(t,t+self.P_j[j])], [] ) ) <= self.P_j[j]*BIG_M*(1 - self.x_ijt[(i,j,t)]) + 1",
"the STN (order in the list matters!) self.units = ['Heater', 'Reactor 1', 'Reactor",
"0, 0, 0.9]]) # time (in # of steps) required to produce output",
"self.x_ijt[i,j,t] == 0 ) return constraint_allocation def construct_box_constraint(self): \"\"\" Construct box constraints on",
"j (row) self.P = np.array([[0, 0, 0, 1, 0, 0, 0, 0, 0],",
"STN.X_ijt (assignments, bool) - STN.Y_ijt (batch sizes, float) - STN.Y_st (material quantities, float)",
"0): self.y_st_inflow[s,t] += self.rho_out[j,s]*self.y_ijt[i,j,t-self.P[j,s]] # set outflows self.y_st_outflow[s,t] += self.rho_in[j,s]*self.y_ijt[i,j,t] constraint_state_eq.append( self.C_min[s] <=",
"__init__() method, and can be changed. Additional constraints can be included as functions",
"'Constructing nominal model...' self.construct_nominal_model() print 'Solving...' self.model.solve(verbose=True, solver='GUROBI') self.unpack_results() return self.model.value def unpack_results(self):",
"0 def construct_allocation_constraint(self): \"\"\" construct the allocation constraints: 1) each unit i is",
"# the initial state y_s(t=0), which we name y_s for s in range(self.S):",
"1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0,",
"\"\"\" I = self.units.__len__() J = self.tasks.__len__() S = self.states.__len__() T = self.T",
"in range(self.I): for j in range(self.J): for t in range(self.T): constraint_capacity.append( self.x_ijt[i,j,t]*self.V_min[i,j] <=",
"kg for s in range(self.S): if s not in self.input_states: constraint_state_eq.append( self.y_s[s] ==",
"matters!) self.units = ['Heater', 'Reactor 1', 'Reactor 2', 'Column'] self.tasks = ['Heat', 'Rea.",
"cvx.Bool() # we separate creation of x_ijt and y_ijt in two loops, so",
"following constraints force the exact same solution as in the paper (the objective",
"for i in range(self.I): for j in range(self.J): for t in range(self.T): self.x_ijt[i,j,t]",
"tt in range(t,t+self.P_j[j])], [] ) ) <= self.P_j[j]*BIG_M*(1 - self.x_ijt[(i,j,t)]) + 1 )",
"1 ) # 2) units can only perform tasks that are compatible with",
"and tasks should be started # early enough such that they are completed",
"used in the state equations self.y_st_inflow = {} self.y_st_outflow = {} # Attributes",
"of the final products minus cost of the input feeds. :return: cvx.Objective \"\"\"",
") constraint_kondili.append( [self.y_ijt[1,1,0] == 80] ) return constraint_kondili def construct_objective(self): \"\"\" Objective encodes",
"mixed up for i in range(self.I): for j in range(self.J): for t in",
"cvx.Constraints, and added in the STN.construst_nominal_model() method. We pack everything in a class",
"= np.zeros((self.I,self.J,self.T)) self.Y_st = np.zeros((self.S,self.T)) self.Y_st_inflow = np.zeros((self.S,self.T)) self.Y_st_outflow = np.zeros((self.S,self.T)) # to",
"= 0 def construct_allocation_constraint(self): \"\"\" construct the allocation constraints: 1) each unit i",
"'Rea. 2', 'Rea. 3', 'Sep.'] self.states = ['Feed A', 'Feed B', 'Feed C',",
"of output state s (column) produced by task j (row) self.rho_out = np.array([[0,",
"0, 0, 0, 2, 0, 0, 2, 0], [0, 0, 0, 0, 0,",
"- sum([self.y_st_outflow[s,t] for t in range(self.T)])) for s in range(self.S)] ) def construct_nominal_model(self):",
"at each t for i in range(I): for t in range(T): constraint_allocation.append( sum(",
"range(self.n_x) range_cont_ix = range(self.n_x, self.n_x+self.n_y) self.c_x = data['c'][range_bool_ix] self.c_y = data['c'][range_cont_ix] self.A_eq =",
"== '__main__': # example usage of the class model = STN() model.solve() model.plot_schedule()",
"\"\"\" n = data['c'].shape[0] self.bool_ix = data['bool_vars_idx'] self.cont_ix = list(set(range(n)) - set(data['bool_vars_idx'])) self.n_x",
"# set outflows self.y_st_outflow[s,t] += self.rho_in[j,s]*self.y_ijt[i,j,t] constraint_state_eq.append( self.C_min[s] <= self.y_s[s] + sum( [self.y_st_inflow[(s,tt)]",
"saved within the instance attributes - STN.X_ijt (assignments, bool) - STN.Y_ijt (batch sizes,",
"y_s(t=0), which we name y_s for s in range(self.S): self.y_s[s] = cvx.Variable() #",
"as in the paper (the objective is unaffected) :return: list of cvx.Constraint \"\"\"",
"in range(self.S)] ) def construct_nominal_model(self): \"\"\" Constructs the nominal STN model, and saves",
"j in range(self.J): for i in range(self.I): self.X_ijt[i,j,t] = self.x_ijt[i,j,t].value self.Y_ijt[i,j,t] = self.y_ijt[i,j,t].value",
"bools. :return: list of cvx.Constraint \"\"\" I = self.units.__len__() J = self.tasks.__len__() T",
"exact same solution as in the paper (the objective is unaffected) :return: list",
"j in range(self.J): for t in range(self.T): self.y_ijt[i,j,t] = cvx.Variable() # state equations",
"[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0,",
"max capacity of unit i (row) to process task j (column), in e.g.",
"np.zeros((self.I,self.J,self.T)) self.Y_ijt = np.zeros((self.I,self.J,self.T)) self.Y_st = np.zeros((self.S,self.T)) self.Y_st_inflow = np.zeros((self.S,self.T)) self.Y_st_outflow = np.zeros((self.S,self.T))",
"J = self.tasks.__len__() T = self.T constraint_box = [] for i in range(I):",
"cvx.Constant(0) self.y_st_outflow[s,t] = cvx.Constant(0) for i in range(self.I): for j in range(self.J): if",
"self.bool_ix = data['bool_vars_idx'] self.cont_ix = list(set(range(n)) - set(data['bool_vars_idx'])) self.n_x = self.bool_ix.__len__() self.n_y =",
"for t in range(self.T)])) for s in range(self.S)] ) def construct_nominal_model(self): \"\"\" Constructs",
"0, 0]]) # fractions of output state s (column) produced by task j",
"of bools. :return: list of cvx.Constraint \"\"\" I = self.units.__len__() J = self.tasks.__len__()",
"self.x_ijt[i,j,t]*self.V_max[i,j] ) return constraint_capacity def construct_state_equations_and_storage_constraint(self): \"\"\" Implementation of state equations, and states",
"1', 'Rea. 2', 'Rea. 3', 'Sep.'] self.states = ['Feed A', 'Feed B', 'Feed",
"class methods) with exceedingly long signatures. \"\"\" import numpy as np import cvxpy",
"in range(t+1)] ) - sum( [self.y_st_outflow[(s,tt)] for tt in range(t+1)] )) constraint_state_eq.append( self.C_max[s]",
"0, 0.2, 0, 0.8, 0, 0, 0, 0], [0, 0, 0, 0, 0,",
"self.Y_ijt, color=color, style=style) # imported with plotting if __name__ == '__main__': # example",
") constraint_capacity.append( self.y_ijt[i,j,t] <= self.x_ijt[i,j,t]*self.V_max[i,j] ) return constraint_capacity def construct_state_equations_and_storage_constraint(self): \"\"\" Implementation of",
"- sum( [self.y_st_outflow[(s,tt)] for tt in range(t+1)] )) return constraint_state_eq def construct_konidili_solution_enforce(self): \"\"\"",
"the problem is in the __init__() method, and can be changed. Additional constraints",
"0, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0,",
"we separate creation of x_ijt and y_ijt in two loops, so that the",
"problem is in the __init__() method, and can be changed. Additional constraints can",
"self.rho_in[j,s]*self.y_ijt[i,j,t] constraint_state_eq.append( self.C_min[s] <= self.y_s[s] + sum( [self.y_st_inflow[(s,tt)] for tt in range(t+1)] )",
"in the state equations self.y_st_inflow = {} self.y_st_outflow = {} # Attributes #",
"0], [0, 0, 0, 0.4, 0, 0.6, 0, 0, 0], [0, 0, 0.2,",
"batch size [kg] self.y_s = {} # state quantity [kg] for i in",
"= cvx.Bool() # we separate creation of x_ijt and y_ijt in two loops,",
"sum(constraints, []) # Objective # --------- objective = cvx.Minimize(self.construct_objective()) # Model # -----",
") <= 1 ) for j in range(J): for t in range(T-self.P_j[j]+1): constraint_allocation.append(",
"same solution as in the paper (the objective is unaffected) :return: list of",
"capability (what tasks can be processed on which unit) # row = unit,",
") return constraint_kondili def construct_objective(self): \"\"\" Objective encodes c'*(y_s(t=end)-y_s(t=0)), i.e., value of the",
"in range(J): for t in range(T-self.P_j[j]+1): constraint_allocation.append( sum ( sum( [[self.x_ijt[(i,jj,tt)] for jj",
"in the np.arrays - STN.X_ijt (assignments, bool) - STN.Y_ijt (batch sizes, float) -",
"j in range(self.J): for t in range(self.T): self.x_ijt[i,j,t] = cvx.Bool() # we separate",
"None \"\"\" plot_stn_schedule(self, self.Y_ijt, color=color, style=style) # imported with plotting if __name__ ==",
"= 0 self.c_y = 0 self.A_eq = 0 self.A_ineq = 0 self.B_eq =",
"0, 2, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0], [0,",
"included as functions that return cvx.Constraints, and added in the STN.construst_nominal_model() method. We",
"0 self.cont_ix = 0 self.m_eq = 0 self.m_ineq = 0 def construct_allocation_constraint(self): \"\"\"",
"def construct_objective(self): \"\"\" Objective encodes c'*(y_s(t=end)-y_s(t=0)), i.e., value of the final products minus",
"0, 0, 2, 0, 0, 0], [0, 0, 0, 0, 2, 0, 0,",
"the state equations self.y_st_inflow = {} self.y_st_outflow = {} # Attributes # ----------",
"= data['c'].shape[0] self.bool_ix = data['bool_vars_idx'] self.cont_ix = list(set(range(n)) - set(data['bool_vars_idx'])) self.n_x = self.bool_ix.__len__()",
"0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0,",
"- sum( [self.y_st_outflow[(s,tt)] for tt in range(t+1)] )) constraint_state_eq.append( self.C_max[s] >= self.y_s[s] +",
"in range(T): constraint_box.append(self.x_ijt[i,j,t] >= 0) constraint_box.append(self.x_ijt[i,j,t] <= 1) constraint_box.append(self.y_ijt[i,j,t] >= 0) constraint_box.append(self.y_ijt[i,j,t] <=",
"b_eq, etc) with ordered columns. :param data: dictionary, as returned by cvx.Problem.get_problem_data('ECOS_BB') :return:",
"range(self.J): for t in range(self.T): self.x_ijt[i,j,t] = cvx.Bool() # we separate creation of",
"50], [200, 200, 200, 200, 200]]) self.V_min = np.array([[0, 0, 0, 0, 0],",
"# state quantity [kg] for i in range(self.I): for j in range(self.J): for",
"the paper (the objective is unaffected) :return: list of cvx.Constraint \"\"\" constraint_kondili =",
"0], [0, 0, 0, 0, 0.1, 0, 0, 0, 0.9]]) # time (in",
"in the __init__() method, and can be changed. Additional constraints can be included",
"from plotting import * class STN(object): def __init__(self): # Data # ---- #",
"in range(t+1)])) def plot_schedule(self, color='red', style='ggplot'): \"\"\" Plot the nominal schedule. :return: None",
"sizes, float) - STN.Y_st (stored material quantities, float) - STN.Y_st_inflow and STN.Y_st_outflow (material",
"in the STN.construst_nominal_model() method. We pack everything in a class to avoid having",
"unit, column = task self.J_i = np.array([[1, 0, 0, 0, 0], [0, 1,",
"if self.J_i[i,j]: # set inflows if (t-self.P[j,s] >= 0): self.y_st_inflow[s,t] += self.rho_out[j,s]*self.y_ijt[i,j,t-self.P[j,s]] #",
"problem matrices (A_eq, B_eq, b_eq, etc) with ordered columns. :param data: dictionary, as",
"# fractions of input state s (column) required to execute task j (row)",
"perform tasks that are compatible with self.J_i, and tasks should be started #",
"flows, float) :return: optimal value (float) \"\"\" print 'Constructing nominal model...' self.construct_nominal_model() print",
"0, 0, 0]]) # storage capacity for state s self.C_max = np.array([np.infty, np.infty,",
"# fractions of output state s (column) produced by task j (row) self.rho_out",
"1', 'Product 2'] self.input_states = [0, 1, 2] # indices of the input",
"# 2) state equations and storage capacities for t in range(self.T): for s",
"maximum and minimum sizes of the batches to be processed are within unit",
"constraint_state_eq = [] # 1) every intermediate / output state starts with a",
"optimizers. The following constraints force the exact same solution as in the paper",
"self.y_ijt[i,j,t] = cvx.Variable() # state equations are eliminated to allow for the robust",
"BC', 'Impure E', 'Product 1', 'Product 2'] self.input_states = [0, 1, 2] #",
"= data['bool_vars_idx'] self.cont_ix = list(set(range(n)) - set(data['bool_vars_idx'])) self.n_x = self.bool_ix.__len__() self.n_y = self.cont_ix.__len__()",
"= 0 self.cont_ix = 0 self.m_eq = 0 self.m_ineq = 0 def construct_allocation_constraint(self):",
"B', 'Feed C', 'Hot A', 'Intermediate AB', 'Intermediate BC', 'Impure E', 'Product 1',",
"= data['b'] self.A_ineq = data['G'][:,range_bool_ix] self.B_ineq = data['G'][:,range_cont_ix] self.b_ineq = data['h'] self.b_ineq =",
"0, 0, 0], [0, 0, 0, 0, 0]]) # storage capacity for state",
"as returned by cvx.Problem.get_problem_data('ECOS_BB') :return: None \"\"\" n = data['c'].shape[0] self.bool_ix = data['bool_vars_idx']",
"0, 0], [0, 0, 0, 0, 0, 2, 0, 0, 0], [0, 0,",
"in range(J)] ) <= 1 ) for j in range(J): for t in",
"quantity of 0 kg for s in range(self.S): if s not in self.input_states:",
"STN.construst_nominal_model() method. We pack everything in a class to avoid having to implement",
"list(set(range(n)) - set(data['bool_vars_idx'])) self.n_x = self.bool_ix.__len__() self.n_y = self.cont_ix.__len__() range_bool_ix = range(self.n_x) range_cont_ix",
"0.8, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0,",
"and minimum sizes of the batches to be processed are within unit constraints.",
"float) - STN.Y_st (material quantities, float) - STN.Y_st_inflow and Y_st_outflow (material flows, float)",
"= 'robin' \"\"\" Implementation of a scheduling system based on the STN model.",
"unit) # row = unit, column = task self.J_i = np.array([[1, 0, 0,",
"cvxpy as cvx from plotting import * class STN(object): def __init__(self): # Data",
"0, 0, 1, 0, 0], [0, 0, 0, 0, 2, 0, 0, 0,",
"(in # of steps) required to produce output state s (column) from task",
"with the data of Kondili's paper has several optimizers. The following constraints force",
"self.J = self.tasks.__len__() self.S = self.states.__len__() self.T = self.horizon # Units capability (what",
"self.Y_st_inflow = np.zeros((self.S,self.T)) self.Y_st_outflow = np.zeros((self.S,self.T)) # to store the standard model #",
"initial state y_s(t=0), which we name y_s for s in range(self.S): self.y_s[s] =",
"is executed. :return: None \"\"\" for t in range(self.T): for j in range(self.J):",
"a scheduling system based on the STN model. The data of the problem",
"'Reactor 2', 'Column'] self.tasks = ['Heat', 'Rea. 1', 'Rea. 2', 'Rea. 3', 'Sep.']",
"range(self.J): for t in range(self.T): self.y_ijt[i,j,t] = cvx.Variable() # state equations are eliminated",
"self.m_eq = 0 self.m_ineq = 0 def construct_allocation_constraint(self): \"\"\" construct the allocation constraints:",
"0, 0, 0.6, 0, 0, 0.4, 0], [0, 0, 0, 0, 0, 0,",
"construct_units_capacity_constraint(self): \"\"\" Ensure maximum and minimum sizes of the batches to be processed",
"b_ineq # x \\in {0,1} self.c_x = 0 self.c_y = 0 self.A_eq =",
"class STN(object): def __init__(self): # Data # ---- # Definition of the STN",
"Attributes # ---------- # to store results self.X_ijt = np.zeros((self.I,self.J,self.T)) self.Y_ijt = np.zeros((self.I,self.J,self.T))",
"range(self.T): for j in range(self.J): for i in range(self.I): self.X_ijt[i,j,t] = self.x_ijt[i,j,t].value self.Y_ijt[i,j,t]",
"cvx.Variable() # state equations are eliminated to allow for the robust counterpart. We",
"is processing at most one task j at each t 2) units can",
"np.array([np.infty, np.infty, np.infty, 100, 200, 150, 100, np.infty, np.infty]) self.C_min = np.array([0, 0,",
"100, 200, 150, 100, np.infty, np.infty]) self.C_min = np.array([0, 0, 0, 0, 0,",
"self.b_ineq = data['h'] self.b_ineq = data['h'] self.m_eq = self.A_eq.shape[0] self.m_ineq = self.A_ineq.shape[0] def",
"def plot_schedule(self, color='red', style='ggplot'): \"\"\" Plot the nominal schedule. :return: None \"\"\" plot_stn_schedule(self,",
"float) - STN.Y_st (stored material quantities, float) - STN.Y_st_inflow and STN.Y_st_outflow (material flows,",
"fractions of input state s (column) required to execute task j (row) self.rho_in",
"having to implement functions (now the class methods) with exceedingly long signatures. \"\"\"",
"for j in range(J): for t in range(T): constraint_allocation.append( self.x_ijt[i,j,t]*(1-self.J_i[i,j]) == 0 )",
"store # the initial state y_s(t=0), which we name y_s for s in",
"self.c_y = data['c'][range_cont_ix] self.A_eq = data['A'][:,range_bool_ix] self.B_eq = data['A'][:,range_cont_ix] self.b_eq = data['b'] self.A_ineq",
"float), and can be accessed from there once the method is executed. :return:",
"task j (row) self.rho_in = np.array([[1, 0, 0, 0, 0, 0, 0, 0,",
"constraints.append(self.construct_units_capacity_constraint()) constraints.append(self.construct_state_equations_and_storage_constraint()) # can force Kondili's solution with # constraints.append(self.construct_konidili_solution_enforce()) constraints = sum(constraints,",
"# ---------------------- self.x_ijt = {} # allocation variable (bool) self.y_ijt = {} #",
"from there once the method is executed. :return: None \"\"\" for t in",
"accessed from there once the method is executed. :return: None \"\"\" for t",
"= self.model.get_problem_data('ECOS_BB') self.retrieve_standard_model(data) def retrieve_standard_model(self, data): \"\"\" Here we store the problem matrices",
"unit i (row) to process task j (column), in e.g. kg self.V_max =",
"te standard model: data = self.model.get_problem_data('ECOS_BB') self.retrieve_standard_model(data) def retrieve_standard_model(self, data): \"\"\" Here we",
"[kg] self.y_s = {} # state quantity [kg] for i in range(self.I): for",
"s (column) from task j (row) self.P = np.array([[0, 0, 0, 1, 0,",
"100, 100, 100, 100], [80, 80, 80, 80, 80], [50, 50, 50, 50,",
"= data['c'][range_bool_ix] self.c_y = data['c'][range_cont_ix] self.A_eq = data['A'][:,range_bool_ix] self.B_eq = data['A'][:,range_cont_ix] self.b_eq =",
"[0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0,",
"[0, 0, 0, 0, 2, 0, 0, 0, 1]]) # total execution time",
"storage capacities for t in range(self.T): for s in range(self.S): self.y_st_inflow[s,t] = cvx.Constant(0)",
"in range(I): for j in range(J): for t in range(T): constraint_box.append(self.x_ijt[i,j,t] >= 0)",
"eliminated to allow for the robust counterpart. We only store # the initial",
"self.b_ineq = 0 self.bool_ix = 0 self.cont_ix = 0 self.m_eq = 0 self.m_ineq",
"states capacities (storages) :return: list of cvx.Constraint \"\"\" constraint_state_eq = [] # 1)",
"= 0 self.b_eq = 0 self.b_ineq = 0 self.bool_ix = 0 self.cont_ix =",
"self.rho_out = np.array([[0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0,",
"the allocation constraints: 1) each unit i is processing at most one task",
"in range(self.J): for t in range(self.T): self.y_ijt[i,j,t] = cvx.Variable() # state equations are",
"J = self.tasks.__len__() S = self.states.__len__() T = self.T # TODO BIG-M for",
"[0, 1, 2] # indices of the input states self.horizon = 11 #",
") ) <= self.P_j[j]*BIG_M*(1 - self.x_ijt[(i,j,t)]) + 1 ) # 2) units can",
"task j (row-wise max of P) self.P_j = np.amax(self.P, axis=1) # Capacities #",
"52] ) constraint_kondili.append( [self.y_ijt[1,1,0] == 80] ) return constraint_kondili def construct_objective(self): \"\"\" Objective",
"# Capacities # max capacity of unit i (row) to process task j",
"50, 50, 50], [200, 200, 200, 200, 200]]) self.V_min = np.array([[0, 0, 0,",
"indices of the input states self.horizon = 11 # horizon in number of",
"so that the optimization variables # in the standard model do not get",
"for s in range(self.S): self.y_s[s] = cvx.Variable() # auxiliary expressions used in the",
"= data['A'][:,range_bool_ix] self.B_eq = data['A'][:,range_cont_ix] self.b_eq = data['b'] self.A_ineq = data['G'][:,range_bool_ix] self.B_ineq =",
"0 kg for s in range(self.S): if s not in self.input_states: constraint_state_eq.append( self.y_s[s]",
"the nominal STN model, and saves it in the class attribute self.model as",
"do not get mixed up for i in range(self.I): for j in range(self.J):",
"[kg] for i in range(self.I): for j in range(self.J): for t in range(self.T):",
"40 constraint_allocation = [] # 1) each unit i is processing at most",
"are saved within the instance attributes - STN.X_ijt (assignments, bool) - STN.Y_ijt (batch",
"[self.y_st_outflow[(s,tt)] for tt in range(t+1)] )) constraint_state_eq.append( self.C_max[s] >= self.y_s[s] + sum( [self.y_st_inflow[(s,tt)]",
"= 0 self.m_eq = 0 self.m_ineq = 0 def construct_allocation_constraint(self): \"\"\" construct the",
"model: data = self.model.get_problem_data('ECOS_BB') self.retrieve_standard_model(data) def retrieve_standard_model(self, data): \"\"\" Here we store the",
"__init__(self): # Data # ---- # Definition of the STN (order in the",
"self.b_eq = 0 self.b_ineq = 0 self.bool_ix = 0 self.cont_ix = 0 self.m_eq",
"force the exact same solution as in the paper (the objective is unaffected)",
"c_x'*x + c_y'*y # s.t. A_eq*x + B_eq*y = b_eq # A_ineq*x +",
"0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0.1, 0, 0,",
"the __init__() method, and can be changed. Additional constraints can be included as",
"def construct_units_capacity_constraint(self): \"\"\" Ensure maximum and minimum sizes of the batches to be",
"self.C_max = np.array([np.infty, np.infty, np.infty, 100, 200, 150, 100, np.infty, np.infty]) self.C_min =",
"t in range(T): constraint_allocation.append( self.x_ijt[i,j,t]*(1-self.J_i[i,j]) == 0 ) if t >= T-self.P_j[j]: constraint_allocation.append(",
"= cvx.Minimize(self.construct_objective()) # Model # ----- self.model = cvx.Problem(objective, constraints) # Also store",
"0) constraint_box.append(self.y_ijt[i,j,t] <= 1) return constraint_box def construct_units_capacity_constraint(self): \"\"\" Ensure maximum and minimum",
"constraint_box.append(self.y_ijt[i,j,t] >= 0) constraint_box.append(self.y_ijt[i,j,t] <= 1) return constraint_box def construct_units_capacity_constraint(self): \"\"\" Ensure maximum",
"{} # Attributes # ---------- # to store results self.X_ijt = np.zeros((self.I,self.J,self.T)) self.Y_ijt",
"the input states self.horizon = 11 # horizon in number of of steps",
"return constraint_capacity def construct_state_equations_and_storage_constraint(self): \"\"\" Implementation of state equations, and states capacities (storages)",
"self.states.__len__() T = self.T # TODO BIG-M for allocation BIG_M = 40 constraint_allocation",
"self.m_ineq = self.A_ineq.shape[0] def solve(self): \"\"\" Constructs and solved the nominal STN model.",
"STN.Y_ijt (batch sizes, float) - STN.Y_st (stored material quantities, float) - STN.Y_st_inflow and",
"range(J)] ) <= 1 ) for j in range(J): for t in range(T-self.P_j[j]+1):",
"data = self.model.get_problem_data('ECOS_BB') self.retrieve_standard_model(data) def retrieve_standard_model(self, data): \"\"\" Here we store the problem",
"the exact same solution as in the paper (the objective is unaffected) :return:",
"number of of steps # Aliases self.I = self.units.__len__() self.J = self.tasks.__len__() self.S",
"only perform tasks that are compatible with self.J_i, and tasks should be started",
"= [] # 1) every intermediate / output state starts with a quantity",
"(column) from task j (row) self.P = np.array([[0, 0, 0, 1, 0, 0,",
"= 11 # horizon in number of of steps # Aliases self.I =",
"None \"\"\" # Constraints # ----------- constraints = [] constraints.append(self.construct_allocation_constraint()) constraints.append(self.construct_units_capacity_constraint()) constraints.append(self.construct_state_equations_and_storage_constraint()) #",
":return: cvx.Objective \"\"\" return - sum( [self.c[s]*( sum([self.y_st_inflow[s,t] for t in range(self.T)]) -",
"I = self.units.__len__() J = self.tasks.__len__() T = self.T constraint_box = [] for",
"of the input states self.horizon = 11 # horizon in number of of",
"= 0 self.m_ineq = 0 def construct_allocation_constraint(self): \"\"\" construct the allocation constraints: 1)",
"100, 100, 100], [80, 80, 80, 80, 80], [50, 50, 50, 50, 50],",
"= ['Feed A', 'Feed B', 'Feed C', 'Hot A', 'Intermediate AB', 'Intermediate BC',",
"processing at most one task j at each t for i in range(I):",
"self.x_ijt[i,j,t] = cvx.Bool() # we separate creation of x_ijt and y_ijt in two",
"sum([self.y_st_inflow[s,t] for t in range(self.T)]) - sum([self.y_st_outflow[s,t] for t in range(self.T)])) for s",
"# to store results self.X_ijt = np.zeros((self.I,self.J,self.T)) self.Y_ijt = np.zeros((self.I,self.J,self.T)) self.Y_st = np.zeros((self.S,self.T))",
"# Units capability (what tasks can be processed on which unit) # row",
"in a class to avoid having to implement functions (now the class methods)",
"self.c_x = 0 self.c_y = 0 self.A_eq = 0 self.A_ineq = 0 self.B_eq",
"(batch sizes, float) - STN.Y_st (stored material quantities, float) - STN.Y_st_inflow and STN.Y_st_outflow",
"allocation variable (bool) self.y_ijt = {} # batch size [kg] self.y_s = {}",
"<gh_stars>1-10 __author__ = 'robin' \"\"\" Implementation of a scheduling system based on the",
"self.x_ijt[(i,j,t)]) + 1 ) # 2) units can only perform tasks that are",
"the final products minus cost of the input feeds. :return: cvx.Objective \"\"\" return",
"in the standard model do not get mixed up for i in range(self.I):",
"self.Y_ijt[i,j,t] = self.y_ijt[i,j,t].value for t in range(self.T): for s in range(self.S): self.Y_st_inflow[s,t] =",
"several optimizers. The following constraints force the exact same solution as in the",
"- STN.Y_st_inflow and Y_st_outflow (material flows, float) :return: optimal value (float) \"\"\" print",
"float) - STN.Y_st_inflow and Y_st_outflow (material flows, float) :return: optimal value (float) \"\"\"",
"in the list matters!) self.units = ['Heater', 'Reactor 1', 'Reactor 2', 'Column'] self.tasks",
"instead of bools. :return: list of cvx.Constraint \"\"\" I = self.units.__len__() J =",
"and states capacities (storages) :return: list of cvx.Constraint \"\"\" constraint_state_eq = [] #",
"capacities (storages) :return: list of cvx.Constraint \"\"\" constraint_state_eq = [] # 1) every",
"nominal model with the data of Kondili's paper has several optimizers. The following",
"0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1,",
"= self.y_s[s].value + (sum([self.y_st_inflow[s,tt].value for tt in range(t+1)]) - sum([self.y_st_outflow[s,tt].value for tt in",
"feeds. :return: cvx.Objective \"\"\" return - sum( [self.c[s]*( sum([self.y_st_inflow[s,t] for t in range(self.T)])",
"= sum(constraints, []) # Objective # --------- objective = cvx.Minimize(self.construct_objective()) # Model #",
"0, 0, 0, 0, 1, 0, 0]]) # fractions of output state s",
"0 # Optimization Variables # ---------------------- self.x_ijt = {} # allocation variable (bool)",
"--------- objective = cvx.Minimize(self.construct_objective()) # Model # ----- self.model = cvx.Problem(objective, constraints) #",
"0, 0], [0, 0, 0, 0, 2, 0, 0, 0, 1]]) # total",
"units can only perform tasks that are compatible with self.J_i :return: list of",
"(revenue from the states) self.c = np.array([0, 0, 0, -1, -1, -1, -1,",
"np.arrays - STN.X_ijt (assignments, bool) - STN.Y_ijt (batch sizes, float) - STN.Y_st (material",
"for t in range(T): constraint_box.append(self.x_ijt[i,j,t] >= 0) constraint_box.append(self.x_ijt[i,j,t] <= 1) constraint_box.append(self.y_ijt[i,j,t] >= 0)",
"within T, i.e., no tasks can start after T-P_j for i in range(I):",
"task j (row) self.rho_out = np.array([[0, 0, 0, 1, 0, 0, 0, 0,",
"state equations, and states capacities (storages) :return: list of cvx.Constraint \"\"\" constraint_state_eq =",
"with # constraints.append(self.construct_konidili_solution_enforce()) constraints = sum(constraints, []) # Objective # --------- objective =",
"range(t+1)])) def plot_schedule(self, color='red', style='ggplot'): \"\"\" Plot the nominal schedule. :return: None \"\"\"",
"once the method is executed. :return: None \"\"\" for t in range(self.T): for",
"for j in range(self.J): for i in range(self.I): self.X_ijt[i,j,t] = self.x_ijt[i,j,t].value self.Y_ijt[i,j,t] =",
"functions (now the class methods) with exceedingly long signatures. \"\"\" import numpy as",
"range(t+1)] )) return constraint_state_eq def construct_konidili_solution_enforce(self): \"\"\" The nominal model with the data",
"constraint_allocation = [] # 1) each unit i is processing at most one",
"150, 100, np.infty, np.infty]) self.C_min = np.array([0, 0, 0, 0, 0, 0, 0,",
"model, and saves it in the class attribute self.model as a cvx.Problem type.",
"- sum([self.y_st_outflow[s,tt].value for tt in range(t+1)])) def plot_schedule(self, color='red', style='ggplot'): \"\"\" Plot the",
"0, 0.4, 0, 0.6, 0, 0, 0], [0, 0, 0.2, 0, 0.8, 0,",
"expressions used in the state equations self.y_st_inflow = {} self.y_st_outflow = {} #",
"self.J_i, and tasks should be started # early enough such that they are",
"0 ) if t >= T-self.P_j[j]: constraint_allocation.append( self.x_ijt[i,j,t] == 0 ) return constraint_allocation",
"self.horizon # Units capability (what tasks can be processed on which unit) #",
"bool) - STN.Y_ijt (batch sizes, float) - STN.Y_st (stored material quantities, float) -",
"self.X_ijt[i,j,t] = self.x_ijt[i,j,t].value self.Y_ijt[i,j,t] = self.y_ijt[i,j,t].value for t in range(self.T): for s in",
"nominal STN model. The solution is stored in the np.arrays - STN.X_ijt (assignments,",
"(what tasks can be processed on which unit) # row = unit, column",
"= 0 self.A_ineq = 0 self.B_eq = 0 self.B_ineq = 0 self.b_eq =",
"sum( [self.c[s]*( sum([self.y_st_inflow[s,t] for t in range(self.T)]) - sum([self.y_st_outflow[s,t] for t in range(self.T)]))",
"0, 0, 0, 0], [0, 0, 0, 0, 0]]) # storage capacity for",
"0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0.6, 0, 0,",
"= self.states.__len__() T = self.T # TODO BIG-M for allocation BIG_M = 40"
] |
[
"- VALOR DO EMPRESTIMO: 80000.00; - SALARIO EMPREGADO: 1.600; - ANOS DE FINANCIAMENTO:",
"EMPRESTIMO: 80000.00; - SALARIO EMPREGADO: 1.600; - ANOS DE FINANCIAMENTO: 7 ANOS; -",
"EMPRESTIMO PARA COMPRA DE UMA CASA. - VALOR DO EMPRESTIMO: 80000.00; - SALARIO",
"DE UMA CASA. - VALOR DO EMPRESTIMO: 80000.00; - SALARIO EMPREGADO: 1.600; -",
"PARA COMPRA DE UMA CASA. - VALOR DO EMPRESTIMO: 80000.00; - SALARIO EMPREGADO:",
"CASA. - VALOR DO EMPRESTIMO: 80000.00; - SALARIO EMPREGADO: 1.600; - ANOS DE",
"<reponame>AleLucasG/Estudos-Python-I \"\"\"APROVANDO EMPRESTIMO PARA COMPRA DE UMA CASA. - VALOR DO EMPRESTIMO: 80000.00;",
"DO EMPRESTIMO: 80000.00; - SALARIO EMPREGADO: 1.600; - ANOS DE FINANCIAMENTO: 7 ANOS;",
"UMA CASA. - VALOR DO EMPRESTIMO: 80000.00; - SALARIO EMPREGADO: 1.600; - ANOS",
"\"\"\"APROVANDO EMPRESTIMO PARA COMPRA DE UMA CASA. - VALOR DO EMPRESTIMO: 80000.00; -",
"VALOR DO EMPRESTIMO: 80000.00; - SALARIO EMPREGADO: 1.600; - ANOS DE FINANCIAMENTO: 7",
"80000.00; - SALARIO EMPREGADO: 1.600; - ANOS DE FINANCIAMENTO: 7 ANOS; - \"\"\"",
"COMPRA DE UMA CASA. - VALOR DO EMPRESTIMO: 80000.00; - SALARIO EMPREGADO: 1.600;"
] |
[
"x: 2 * 0.648437 if x == 2 else 0.648437, lambda x: -(math.log(x)",
"as np import math from scipy.stats import truncnorm from time import time from",
"3 * math.log(np.cbrt(x ** 2) + 1) / 2,\\ lambda x: math.log(np.abs(x +",
"end = time() norm_res.append(\"%.4f\" % monte_int) norm_times.append(\"%.4f\" % (end - start)) anal_res.append(\"%.4f\" %",
"9 *math.cos(x)) / 12,\\ lambda x: -2 / (math.tan(x / 2) + 1),",
"* x) - 9 *math.cos(x)) / 12,\\ lambda x: -2 / (math.tan(x /",
"* funcs[1](x[1]) * funcs[2](x[2]) * funcs[3](x[3]) * funcs[4](x[4]) * funcs[5](x[5]) ] anal_funcs =",
"(end - start)) start = time() monte_int = monte_carlo(intervals[:j], monte_funcs[i], experiments_amount, normal_rand_generator) end",
"= monte_carlo(intervals[:j], monte_funcs[i], experiments_amount) end = time() monte_res.append(\"%.4f\" % monte_int) monte_times.append(\"%.4f\" % (end",
"lambda x: (math.cos(3 * x) - 9 *math.cos(x)) / 12,\\ lambda x: -2",
"zip(anal_funcs[:j], intervals[:j])])) headers = (\"Arity\", \"Monte-Carlo with uniform\", \"Monte-Carlo with normal\", \"Simpson\", \"Analytical\")",
"* funcs[5](x[5]) ] anal_funcs = [lambda x: 3 * math.log(np.cbrt(x ** 2) +",
"n - 1, 2)]) integral = h * (f(a) + first_part + second_part",
"2 else 0.648437, lambda x: -(math.log(x) + 1) / x ] intervals =",
"np.sum([f(a + i * h) for i in range(1, n, 2)]) second_part =",
"/ 3 return integral def normal_rand_generator(lower, upper, size): res = [truncnorm.rvs(a, b) for",
"x: math.log(x) / (x ** 2) ] monte_funcs = [funcs[0], \\ lambda x:",
"= [] norm_res = [] anal_res = [] for i in range(len(intervals)): j",
"volume * np.sum([f(random_generator(lower, upper, size)) for _ in range(experiments_amount)]) / experiments_amount return integral",
"3, \\ lambda x: 1 / (1 + math.sin(x)), \\ lambda x: math.log(x",
"h) for func, interval in zip(funcs[:j], intervals[:j])]) end = time() quad_res.append(\"%.4f\" % quad_ints)",
"x: funcs[0](x[0]) * funcs[1](x[1]) * funcs[2](x[2]) * funcs[3](x[3]) * funcs[4](x[4]), \\ lambda x:",
"for func, interval in zip(anal_funcs[:j], intervals[:j])])) headers = (\"Arity\", \"Monte-Carlo with uniform\", \"Monte-Carlo",
"start)) start = time() monte_int = monte_carlo(intervals[:j], monte_funcs[i], experiments_amount, normal_rand_generator) end = time()",
"headers = (\"Arity\", \"Monte-Carlo with uniform\", \"Monte-Carlo with normal\", \"Simpson\", \"Analytical\") content =",
"= time() monte_int = monte_carlo(intervals[:j], monte_funcs[i], experiments_amount) end = time() monte_res.append(\"%.4f\" % monte_int)",
"% monte_int) norm_times.append(\"%.4f\" % (end - start)) anal_res.append(\"%.4f\" % np.prod([calc_int(func, interval) for func,",
"h, experiments_amount in [(0.1, 100), (0.01, 1000)]: bench_methods(funcs, monte_funcs, anal_funcs, intervals, h, experiments_amount)",
"/ (x ** 2) ] monte_funcs = [funcs[0], \\ lambda x: funcs[0](x[0]) *",
"3.22))),\\ lambda x: (math.cos(3 * x) - 9 *math.cos(x)) / 12,\\ lambda x:",
"math.sin(x) ** 3, \\ lambda x: 1 / (1 + math.sin(x)), \\ lambda",
"funcs[0](x[0]) * funcs[1](x[1]) * funcs[2](x[2]), \\ lambda x: funcs[0](x[0]) * funcs[1](x[1]) * funcs[2](x[2])",
"x: 1 / (x + np.cbrt(x)), \\ lambda x: 1 / math.sqrt(x **",
"res def monte_carlo(intervals, f, experiments_amount, random_generator=np.random.uniform): size = len(intervals) lower, upper = zip(*intervals)",
"main(): funcs = [lambda x: 1 / (x + np.cbrt(x)), \\ lambda x:",
"lower, upper = zip(*intervals) volume = np.prod([b - a for a, b in",
"i * h) for i in range(1, n, 2)]) second_part = 2 *",
"1 / math.sqrt(x ** 2 + 3.22), \\ lambda x: math.sin(x) ** 3,",
"list(zip(monte_res, monte_times)), list(zip(norm_res, norm_times)), list(zip(quad_res, quad_times)), anal_res) table = tabulate(list(content), headers, tablefmt=\"fancy_grid\") print(f'Intervals",
"* np.sum([f(random_generator(lower, upper, size)) for _ in range(experiments_amount)]) / experiments_amount return integral def",
"\"Monte-Carlo with uniform\", \"Monte-Carlo with normal\", \"Simpson\", \"Analytical\") content = zip(list(range(1, len(intervals) +",
"(1.2, 2), (14, 88)] print(\"Format in methods is (value, time in seconds)\") for",
"funcs[5](x[5]) ] anal_funcs = [lambda x: 3 * math.log(np.cbrt(x ** 2) + 1)",
"np.prod([simpson(interval, func, h) for func, interval in zip(funcs[:j], intervals[:j])]) end = time() quad_res.append(\"%.4f\"",
"np import math from scipy.stats import truncnorm from time import time from tabulate",
"+ 3.22), \\ lambda x: math.sin(x) ** 3, \\ lambda x: 1 /",
"bench_methods(funcs, monte_funcs, anal_funcs, intervals, h, experiments_amount): quad_times = [] quad_res = [] monte_times",
"* funcs[2](x[2]) * funcs[3](x[3]), \\ lambda x: funcs[0](x[0]) * funcs[1](x[1]) * funcs[2](x[2]) *",
"quad_ints = np.prod([simpson(interval, func, h) for func, interval in zip(funcs[:j], intervals[:j])]) end =",
"math.log(np.cbrt(x ** 2) + 1) / 2,\\ lambda x: math.log(np.abs(x + math.sqrt(x **",
"a) / h + 1) first_part = 4 * np.sum([f(a + i *",
"(1 + math.sin(x)), \\ lambda x: math.log(x + 2) / x, \\ lambda",
"lambda x: 2 * 0.648437 if x == 2 else 0.648437, lambda x:",
"1) / 2,\\ lambda x: math.log(np.abs(x + math.sqrt(x ** 2 + 3.22))),\\ lambda",
"experiments {experiments_amount}') print(f'Step size = {h}') print(table) def main(): funcs = [lambda x:",
"norm_res = [] anal_res = [] for i in range(len(intervals)): j = i",
"lambda x: -(math.log(x) + 1) / x ] intervals = [(-3, -1), (1,",
"\\ lambda x: math.sin(x) ** 3, \\ lambda x: 1 / (1 +",
"start)) start = time() monte_int = monte_carlo(intervals[:j], monte_funcs[i], experiments_amount) end = time() monte_res.append(\"%.4f\"",
"math.log(np.abs(x + math.sqrt(x ** 2 + 3.22))),\\ lambda x: (math.cos(3 * x) -",
"interval): a, b = interval return f(b) - f(a) def bench_methods(funcs, monte_funcs, anal_funcs,",
"range(experiments_amount)]) / experiments_amount return integral def calc_int(f, interval): a, b = interval return",
"2)]) second_part = 2 * np.sum([f(a + i * h) for i in",
"monte_int) norm_times.append(\"%.4f\" % (end - start)) anal_res.append(\"%.4f\" % np.prod([calc_int(func, interval) for func, interval",
"(value, time in seconds)\") for h, experiments_amount in [(0.1, 100), (0.01, 1000)]: bench_methods(funcs,",
"[] monte_res = [] norm_times = [] norm_res = [] anal_res = []",
"with uniform\", \"Monte-Carlo with normal\", \"Simpson\", \"Analytical\") content = zip(list(range(1, len(intervals) + 1)),",
"f, h): a, b = interval n = int((b - a) / h",
"monte_funcs = [funcs[0], \\ lambda x: funcs[0](x[0]) * funcs[1](x[1]), \\ lambda x: funcs[0](x[0])",
"+ 1) / x ] intervals = [(-3, -1), (1, 3), (3, 5),",
"lambda x: math.sin(x) ** 3, \\ lambda x: 1 / (1 + math.sin(x)),",
"import math from scipy.stats import truncnorm from time import time from tabulate import",
"% (end - start)) start = time() monte_int = monte_carlo(intervals[:j], monte_funcs[i], experiments_amount, normal_rand_generator)",
"in range(1, n, 2)]) second_part = 2 * np.sum([f(a + i * h)",
"size = len(intervals) lower, upper = zip(*intervals) volume = np.prod([b - a for",
"% quad_ints) quad_times.append(\"%.4f\" % (end - start)) start = time() monte_int = monte_carlo(intervals[:j],",
"= [truncnorm.rvs(a, b) for a, b in zip(lower, upper)] return res def monte_carlo(intervals,",
"experiments_amount in [(0.1, 100), (0.01, 1000)]: bench_methods(funcs, monte_funcs, anal_funcs, intervals, h, experiments_amount) main()",
"anal_funcs, intervals, h, experiments_amount): quad_times = [] quad_res = [] monte_times = []",
"= {h}') print(table) def main(): funcs = [lambda x: 1 / (x +",
"+ first_part + second_part + f(b)) / 3 return integral def normal_rand_generator(lower, upper,",
"+ second_part + f(b)) / 3 return integral def normal_rand_generator(lower, upper, size): res",
"+ math.sqrt(x ** 2 + 3.22))),\\ lambda x: (math.cos(3 * x) - 9",
"f(b) - f(a) def bench_methods(funcs, monte_funcs, anal_funcs, intervals, h, experiments_amount): quad_times = []",
"= [] quad_res = [] monte_times = [] monte_res = [] norm_times =",
"1 / (x + np.cbrt(x)), \\ lambda x: 1 / math.sqrt(x ** 2",
"] anal_funcs = [lambda x: 3 * math.log(np.cbrt(x ** 2) + 1) /",
"for i in range(1, n, 2)]) second_part = 2 * np.sum([f(a + i",
"+ 1) / 2,\\ lambda x: math.log(np.abs(x + math.sqrt(x ** 2 + 3.22))),\\",
"= {intervals}') print(f'Monte-Carlo experiments {experiments_amount}') print(f'Step size = {h}') print(table) def main(): funcs",
"* funcs[3](x[3]) * funcs[4](x[4]), \\ lambda x: funcs[0](x[0]) * funcs[1](x[1]) * funcs[2](x[2]) *",
"x, \\ lambda x: math.log(x) / (x ** 2) ] monte_funcs = [funcs[0],",
"/ h + 1) first_part = 4 * np.sum([f(a + i * h)",
"time() monte_int = monte_carlo(intervals[:j], monte_funcs[i], experiments_amount, normal_rand_generator) end = time() norm_res.append(\"%.4f\" % monte_int)",
"<reponame>mehakun/Labs import numpy as np import math from scipy.stats import truncnorm from time",
"* funcs[4](x[4]), \\ lambda x: funcs[0](x[0]) * funcs[1](x[1]) * funcs[2](x[2]) * funcs[3](x[3]) *",
"= np.prod([b - a for a, b in intervals]) integral = volume *",
"f(b)) / 3 return integral def normal_rand_generator(lower, upper, size): res = [truncnorm.rvs(a, b)",
"anal_res) table = tabulate(list(content), headers, tablefmt=\"fancy_grid\") print(f'Intervals = {intervals}') print(f'Monte-Carlo experiments {experiments_amount}') print(f'Step",
"= [] for i in range(len(intervals)): j = i + 1 start =",
"upper, size): res = [truncnorm.rvs(a, b) for a, b in zip(lower, upper)] return",
"* np.sum([f(a + i * h) for i in range(2, n - 1,",
"from scipy.stats import truncnorm from time import time from tabulate import tabulate def",
"monte_int = monte_carlo(intervals[:j], monte_funcs[i], experiments_amount) end = time() monte_res.append(\"%.4f\" % monte_int) monte_times.append(\"%.4f\" %",
"volume = np.prod([b - a for a, b in intervals]) integral = volume",
"= int((b - a) / h + 1) first_part = 4 * np.sum([f(a",
"x: funcs[0](x[0]) * funcs[1](x[1]), \\ lambda x: funcs[0](x[0]) * funcs[1](x[1]) * funcs[2](x[2]), \\",
"* funcs[2](x[2]), \\ lambda x: funcs[0](x[0]) * funcs[1](x[1]) * funcs[2](x[2]) * funcs[3](x[3]), \\",
"* funcs[4](x[4]) * funcs[5](x[5]) ] anal_funcs = [lambda x: 3 * math.log(np.cbrt(x **",
"x: -2 / (math.tan(x / 2) + 1), lambda x: 2 * 0.648437",
"h * (f(a) + first_part + second_part + f(b)) / 3 return integral",
"headers, tablefmt=\"fancy_grid\") print(f'Intervals = {intervals}') print(f'Monte-Carlo experiments {experiments_amount}') print(f'Step size = {h}') print(table)",
"1)), list(zip(monte_res, monte_times)), list(zip(norm_res, norm_times)), list(zip(quad_res, quad_times)), anal_res) table = tabulate(list(content), headers, tablefmt=\"fancy_grid\")",
"x: (math.cos(3 * x) - 9 *math.cos(x)) / 12,\\ lambda x: -2 /",
"func, interval in zip(anal_funcs[:j], intervals[:j])])) headers = (\"Arity\", \"Monte-Carlo with uniform\", \"Monte-Carlo with",
"quad_times)), anal_res) table = tabulate(list(content), headers, tablefmt=\"fancy_grid\") print(f'Intervals = {intervals}') print(f'Monte-Carlo experiments {experiments_amount}')",
"** 2 + 3.22), \\ lambda x: math.sin(x) ** 3, \\ lambda x:",
"in seconds)\") for h, experiments_amount in [(0.1, 100), (0.01, 1000)]: bench_methods(funcs, monte_funcs, anal_funcs,",
"n = int((b - a) / h + 1) first_part = 4 *",
"2) ] monte_funcs = [funcs[0], \\ lambda x: funcs[0](x[0]) * funcs[1](x[1]), \\ lambda",
"0.648437, lambda x: -(math.log(x) + 1) / x ] intervals = [(-3, -1),",
"return integral def calc_int(f, interval): a, b = interval return f(b) - f(a)",
"second_part + f(b)) / 3 return integral def normal_rand_generator(lower, upper, size): res =",
"funcs[3](x[3]), \\ lambda x: funcs[0](x[0]) * funcs[1](x[1]) * funcs[2](x[2]) * funcs[3](x[3]) * funcs[4](x[4]),",
"2) + 1) / 2,\\ lambda x: math.log(np.abs(x + math.sqrt(x ** 2 +",
"= i + 1 start = time() quad_ints = np.prod([simpson(interval, func, h) for",
"start = time() monte_int = monte_carlo(intervals[:j], monte_funcs[i], experiments_amount) end = time() monte_res.append(\"%.4f\" %",
"funcs = [lambda x: 1 / (x + np.cbrt(x)), \\ lambda x: 1",
"methods is (value, time in seconds)\") for h, experiments_amount in [(0.1, 100), (0.01,",
"* h) for i in range(2, n - 1, 2)]) integral = h",
"for a, b in intervals]) integral = volume * np.sum([f(random_generator(lower, upper, size)) for",
"normal_rand_generator) end = time() norm_res.append(\"%.4f\" % monte_int) norm_times.append(\"%.4f\" % (end - start)) anal_res.append(\"%.4f\"",
"seconds)\") for h, experiments_amount in [(0.1, 100), (0.01, 1000)]: bench_methods(funcs, monte_funcs, anal_funcs, intervals,",
"+ i * h) for i in range(1, n, 2)]) second_part = 2",
"import numpy as np import math from scipy.stats import truncnorm from time import",
"\\ lambda x: 1 / (1 + math.sin(x)), \\ lambda x: math.log(x +",
"+ math.sin(x)), \\ lambda x: math.log(x + 2) / x, \\ lambda x:",
"= zip(list(range(1, len(intervals) + 1)), list(zip(monte_res, monte_times)), list(zip(norm_res, norm_times)), list(zip(quad_res, quad_times)), anal_res) table",
"= tabulate(list(content), headers, tablefmt=\"fancy_grid\") print(f'Intervals = {intervals}') print(f'Monte-Carlo experiments {experiments_amount}') print(f'Step size =",
"\"Analytical\") content = zip(list(range(1, len(intervals) + 1)), list(zip(monte_res, monte_times)), list(zip(norm_res, norm_times)), list(zip(quad_res, quad_times)),",
"lambda x: math.log(np.abs(x + math.sqrt(x ** 2 + 3.22))),\\ lambda x: (math.cos(3 *",
"monte_res = [] norm_times = [] norm_res = [] anal_res = [] for",
"monte_int) monte_times.append(\"%.4f\" % (end - start)) start = time() monte_int = monte_carlo(intervals[:j], monte_funcs[i],",
"(1, 3), (3, 5), (5, 7), (1.2, 2), (14, 88)] print(\"Format in methods",
"funcs[1](x[1]) * funcs[2](x[2]) * funcs[3](x[3]) * funcs[4](x[4]) * funcs[5](x[5]) ] anal_funcs = [lambda",
"math.sqrt(x ** 2 + 3.22))),\\ lambda x: (math.cos(3 * x) - 9 *math.cos(x))",
"\\ lambda x: funcs[0](x[0]) * funcs[1](x[1]) * funcs[2](x[2]), \\ lambda x: funcs[0](x[0]) *",
"for h, experiments_amount in [(0.1, 100), (0.01, 1000)]: bench_methods(funcs, monte_funcs, anal_funcs, intervals, h,",
"from time import time from tabulate import tabulate def simpson(interval, f, h): a,",
"if x == 2 else 0.648437, lambda x: -(math.log(x) + 1) / x",
"in methods is (value, time in seconds)\") for h, experiments_amount in [(0.1, 100),",
"+ f(b)) / 3 return integral def normal_rand_generator(lower, upper, size): res = [truncnorm.rvs(a,",
"2 * 0.648437 if x == 2 else 0.648437, lambda x: -(math.log(x) +",
"in intervals]) integral = volume * np.sum([f(random_generator(lower, upper, size)) for _ in range(experiments_amount)])",
"+ 1) first_part = 4 * np.sum([f(a + i * h) for i",
"for i in range(2, n - 1, 2)]) integral = h * (f(a)",
"time import time from tabulate import tabulate def simpson(interval, f, h): a, b",
"] intervals = [(-3, -1), (1, 3), (3, 5), (5, 7), (1.2, 2),",
"monte_times.append(\"%.4f\" % (end - start)) start = time() monte_int = monte_carlo(intervals[:j], monte_funcs[i], experiments_amount,",
"experiments_amount): quad_times = [] quad_res = [] monte_times = [] monte_res = []",
"with normal\", \"Simpson\", \"Analytical\") content = zip(list(range(1, len(intervals) + 1)), list(zip(monte_res, monte_times)), list(zip(norm_res,",
"== 2 else 0.648437, lambda x: -(math.log(x) + 1) / x ] intervals",
"end = time() monte_res.append(\"%.4f\" % monte_int) monte_times.append(\"%.4f\" % (end - start)) start =",
"2) + 1), lambda x: 2 * 0.648437 if x == 2 else",
"monte_funcs, anal_funcs, intervals, h, experiments_amount): quad_times = [] quad_res = [] monte_times =",
"* funcs[1](x[1]) * funcs[2](x[2]) * funcs[3](x[3]) * funcs[4](x[4]), \\ lambda x: funcs[0](x[0]) *",
"4 * np.sum([f(a + i * h) for i in range(1, n, 2)])",
"7), (1.2, 2), (14, 88)] print(\"Format in methods is (value, time in seconds)\")",
"interval n = int((b - a) / h + 1) first_part = 4",
"in range(len(intervals)): j = i + 1 start = time() quad_ints = np.prod([simpson(interval,",
"= [funcs[0], \\ lambda x: funcs[0](x[0]) * funcs[1](x[1]), \\ lambda x: funcs[0](x[0]) *",
"[truncnorm.rvs(a, b) for a, b in zip(lower, upper)] return res def monte_carlo(intervals, f,",
"intervals]) integral = volume * np.sum([f(random_generator(lower, upper, size)) for _ in range(experiments_amount)]) /",
"\\ lambda x: math.log(x + 2) / x, \\ lambda x: math.log(x) /",
"simpson(interval, f, h): a, b = interval n = int((b - a) /",
"in zip(funcs[:j], intervals[:j])]) end = time() quad_res.append(\"%.4f\" % quad_ints) quad_times.append(\"%.4f\" % (end -",
"np.sum([f(random_generator(lower, upper, size)) for _ in range(experiments_amount)]) / experiments_amount return integral def calc_int(f,",
"upper)] return res def monte_carlo(intervals, f, experiments_amount, random_generator=np.random.uniform): size = len(intervals) lower, upper",
"= time() quad_res.append(\"%.4f\" % quad_ints) quad_times.append(\"%.4f\" % (end - start)) start = time()",
"funcs[3](x[3]) * funcs[4](x[4]), \\ lambda x: funcs[0](x[0]) * funcs[1](x[1]) * funcs[2](x[2]) * funcs[3](x[3])",
"/ 2,\\ lambda x: math.log(np.abs(x + math.sqrt(x ** 2 + 3.22))),\\ lambda x:",
"{intervals}') print(f'Monte-Carlo experiments {experiments_amount}') print(f'Step size = {h}') print(table) def main(): funcs =",
"range(len(intervals)): j = i + 1 start = time() quad_ints = np.prod([simpson(interval, func,",
"3 return integral def normal_rand_generator(lower, upper, size): res = [truncnorm.rvs(a, b) for a,",
"\\ lambda x: funcs[0](x[0]) * funcs[1](x[1]) * funcs[2](x[2]) * funcs[3](x[3]) * funcs[4](x[4]) *",
"= [lambda x: 1 / (x + np.cbrt(x)), \\ lambda x: 1 /",
"= [(-3, -1), (1, 3), (3, 5), (5, 7), (1.2, 2), (14, 88)]",
"(x + np.cbrt(x)), \\ lambda x: 1 / math.sqrt(x ** 2 + 3.22),",
"(3, 5), (5, 7), (1.2, 2), (14, 88)] print(\"Format in methods is (value,",
"** 2 + 3.22))),\\ lambda x: (math.cos(3 * x) - 9 *math.cos(x)) /",
"quad_times.append(\"%.4f\" % (end - start)) start = time() monte_int = monte_carlo(intervals[:j], monte_funcs[i], experiments_amount)",
"x == 2 else 0.648437, lambda x: -(math.log(x) + 1) / x ]",
"a, b = interval n = int((b - a) / h + 1)",
"np.sum([f(a + i * h) for i in range(2, n - 1, 2)])",
"funcs[1](x[1]) * funcs[2](x[2]) * funcs[3](x[3]) * funcs[4](x[4]), \\ lambda x: funcs[0](x[0]) * funcs[1](x[1])",
"1) / x ] intervals = [(-3, -1), (1, 3), (3, 5), (5,",
"% (end - start)) start = time() monte_int = monte_carlo(intervals[:j], monte_funcs[i], experiments_amount) end",
"i in range(2, n - 1, 2)]) integral = h * (f(a) +",
"1), lambda x: 2 * 0.648437 if x == 2 else 0.648437, lambda",
"-1), (1, 3), (3, 5), (5, 7), (1.2, 2), (14, 88)] print(\"Format in",
"res = [truncnorm.rvs(a, b) for a, b in zip(lower, upper)] return res def",
"np.prod([calc_int(func, interval) for func, interval in zip(anal_funcs[:j], intervals[:j])])) headers = (\"Arity\", \"Monte-Carlo with",
"n, 2)]) second_part = 2 * np.sum([f(a + i * h) for i",
"h + 1) first_part = 4 * np.sum([f(a + i * h) for",
"x: math.log(np.abs(x + math.sqrt(x ** 2 + 3.22))),\\ lambda x: (math.cos(3 * x)",
"(f(a) + first_part + second_part + f(b)) / 3 return integral def normal_rand_generator(lower,",
"numpy as np import math from scipy.stats import truncnorm from time import time",
"return integral def normal_rand_generator(lower, upper, size): res = [truncnorm.rvs(a, b) for a, b",
"intervals = [(-3, -1), (1, 3), (3, 5), (5, 7), (1.2, 2), (14,",
"/ x, \\ lambda x: math.log(x) / (x ** 2) ] monte_funcs =",
"def simpson(interval, f, h): a, b = interval n = int((b - a)",
"math.sqrt(x ** 2 + 3.22), \\ lambda x: math.sin(x) ** 3, \\ lambda",
"] monte_funcs = [funcs[0], \\ lambda x: funcs[0](x[0]) * funcs[1](x[1]), \\ lambda x:",
"{h}') print(table) def main(): funcs = [lambda x: 1 / (x + np.cbrt(x)),",
"lambda x: 1 / math.sqrt(x ** 2 + 3.22), \\ lambda x: math.sin(x)",
"\\ lambda x: funcs[0](x[0]) * funcs[1](x[1]) * funcs[2](x[2]) * funcs[3](x[3]) * funcs[4](x[4]), \\",
"= h * (f(a) + first_part + second_part + f(b)) / 3 return",
"(end - start)) anal_res.append(\"%.4f\" % np.prod([calc_int(func, interval) for func, interval in zip(anal_funcs[:j], intervals[:j])]))",
"lambda x: -2 / (math.tan(x / 2) + 1), lambda x: 2 *",
"+ i * h) for i in range(2, n - 1, 2)]) integral",
"lambda x: funcs[0](x[0]) * funcs[1](x[1]) * funcs[2](x[2]) * funcs[3](x[3]) * funcs[4](x[4]) * funcs[5](x[5])",
"a, b in zip(lower, upper)] return res def monte_carlo(intervals, f, experiments_amount, random_generator=np.random.uniform): size",
"def calc_int(f, interval): a, b = interval return f(b) - f(a) def bench_methods(funcs,",
"upper = zip(*intervals) volume = np.prod([b - a for a, b in intervals])",
"h) for i in range(2, n - 1, 2)]) integral = h *",
"norm_res.append(\"%.4f\" % monte_int) norm_times.append(\"%.4f\" % (end - start)) anal_res.append(\"%.4f\" % np.prod([calc_int(func, interval) for",
"zip(funcs[:j], intervals[:j])]) end = time() quad_res.append(\"%.4f\" % quad_ints) quad_times.append(\"%.4f\" % (end - start))",
"len(intervals) lower, upper = zip(*intervals) volume = np.prod([b - a for a, b",
"= [] norm_times = [] norm_res = [] anal_res = [] for i",
"np.prod([b - a for a, b in intervals]) integral = volume * np.sum([f(random_generator(lower,",
"lambda x: funcs[0](x[0]) * funcs[1](x[1]) * funcs[2](x[2]) * funcs[3](x[3]), \\ lambda x: funcs[0](x[0])",
"/ math.sqrt(x ** 2 + 3.22), \\ lambda x: math.sin(x) ** 3, \\",
"= zip(*intervals) volume = np.prod([b - a for a, b in intervals]) integral",
"experiments_amount) end = time() monte_res.append(\"%.4f\" % monte_int) monte_times.append(\"%.4f\" % (end - start)) start",
"x: funcs[0](x[0]) * funcs[1](x[1]) * funcs[2](x[2]) * funcs[3](x[3]) * funcs[4](x[4]) * funcs[5](x[5]) ]",
"tabulate def simpson(interval, f, h): a, b = interval n = int((b -",
"= np.prod([simpson(interval, func, h) for func, interval in zip(funcs[:j], intervals[:j])]) end = time()",
"def bench_methods(funcs, monte_funcs, anal_funcs, intervals, h, experiments_amount): quad_times = [] quad_res = []",
"integral def normal_rand_generator(lower, upper, size): res = [truncnorm.rvs(a, b) for a, b in",
"interval return f(b) - f(a) def bench_methods(funcs, monte_funcs, anal_funcs, intervals, h, experiments_amount): quad_times",
"interval in zip(funcs[:j], intervals[:j])]) end = time() quad_res.append(\"%.4f\" % quad_ints) quad_times.append(\"%.4f\" % (end",
"i in range(1, n, 2)]) second_part = 2 * np.sum([f(a + i *",
"x: -(math.log(x) + 1) / x ] intervals = [(-3, -1), (1, 3),",
"\\ lambda x: 1 / math.sqrt(x ** 2 + 3.22), \\ lambda x:",
"_ in range(experiments_amount)]) / experiments_amount return integral def calc_int(f, interval): a, b =",
"np.cbrt(x)), \\ lambda x: 1 / math.sqrt(x ** 2 + 3.22), \\ lambda",
"time() monte_int = monte_carlo(intervals[:j], monte_funcs[i], experiments_amount) end = time() monte_res.append(\"%.4f\" % monte_int) monte_times.append(\"%.4f\"",
"j = i + 1 start = time() quad_ints = np.prod([simpson(interval, func, h)",
"anal_funcs = [lambda x: 3 * math.log(np.cbrt(x ** 2) + 1) / 2,\\",
"f, experiments_amount, random_generator=np.random.uniform): size = len(intervals) lower, upper = zip(*intervals) volume = np.prod([b",
"= [] monte_res = [] norm_times = [] norm_res = [] anal_res =",
"(end - start)) start = time() monte_int = monte_carlo(intervals[:j], monte_funcs[i], experiments_amount) end =",
"quad_ints) quad_times.append(\"%.4f\" % (end - start)) start = time() monte_int = monte_carlo(intervals[:j], monte_funcs[i],",
"(\"Arity\", \"Monte-Carlo with uniform\", \"Monte-Carlo with normal\", \"Simpson\", \"Analytical\") content = zip(list(range(1, len(intervals)",
"f(a) def bench_methods(funcs, monte_funcs, anal_funcs, intervals, h, experiments_amount): quad_times = [] quad_res =",
"h, experiments_amount): quad_times = [] quad_res = [] monte_times = [] monte_res =",
"* funcs[2](x[2]) * funcs[3](x[3]) * funcs[4](x[4]), \\ lambda x: funcs[0](x[0]) * funcs[1](x[1]) *",
"- f(a) def bench_methods(funcs, monte_funcs, anal_funcs, intervals, h, experiments_amount): quad_times = [] quad_res",
"x: math.sin(x) ** 3, \\ lambda x: 1 / (1 + math.sin(x)), \\",
"* funcs[1](x[1]), \\ lambda x: funcs[0](x[0]) * funcs[1](x[1]) * funcs[2](x[2]), \\ lambda x:",
"start)) anal_res.append(\"%.4f\" % np.prod([calc_int(func, interval) for func, interval in zip(anal_funcs[:j], intervals[:j])])) headers =",
"/ x ] intervals = [(-3, -1), (1, 3), (3, 5), (5, 7),",
"/ 2) + 1), lambda x: 2 * 0.648437 if x == 2",
"0.648437 if x == 2 else 0.648437, lambda x: -(math.log(x) + 1) /",
"* h) for i in range(1, n, 2)]) second_part = 2 * np.sum([f(a",
"intervals[:j])]) end = time() quad_res.append(\"%.4f\" % quad_ints) quad_times.append(\"%.4f\" % (end - start)) start",
"interval) for func, interval in zip(anal_funcs[:j], intervals[:j])])) headers = (\"Arity\", \"Monte-Carlo with uniform\",",
"list(zip(norm_res, norm_times)), list(zip(quad_res, quad_times)), anal_res) table = tabulate(list(content), headers, tablefmt=\"fancy_grid\") print(f'Intervals = {intervals}')",
"import time from tabulate import tabulate def simpson(interval, f, h): a, b =",
"- start)) anal_res.append(\"%.4f\" % np.prod([calc_int(func, interval) for func, interval in zip(anal_funcs[:j], intervals[:j])])) headers",
"return f(b) - f(a) def bench_methods(funcs, monte_funcs, anal_funcs, intervals, h, experiments_amount): quad_times =",
"print(f'Step size = {h}') print(table) def main(): funcs = [lambda x: 1 /",
"1 / (1 + math.sin(x)), \\ lambda x: math.log(x + 2) / x,",
"funcs[2](x[2]) * funcs[3](x[3]) * funcs[4](x[4]), \\ lambda x: funcs[0](x[0]) * funcs[1](x[1]) * funcs[2](x[2])",
"func, h) for func, interval in zip(funcs[:j], intervals[:j])]) end = time() quad_res.append(\"%.4f\" %",
"print(table) def main(): funcs = [lambda x: 1 / (x + np.cbrt(x)), \\",
"normal\", \"Simpson\", \"Analytical\") content = zip(list(range(1, len(intervals) + 1)), list(zip(monte_res, monte_times)), list(zip(norm_res, norm_times)),",
"time in seconds)\") for h, experiments_amount in [(0.1, 100), (0.01, 1000)]: bench_methods(funcs, monte_funcs,",
"* funcs[3](x[3]), \\ lambda x: funcs[0](x[0]) * funcs[1](x[1]) * funcs[2](x[2]) * funcs[3](x[3]) *",
"monte_funcs[i], experiments_amount) end = time() monte_res.append(\"%.4f\" % monte_int) monte_times.append(\"%.4f\" % (end - start))",
"range(2, n - 1, 2)]) integral = h * (f(a) + first_part +",
"= interval return f(b) - f(a) def bench_methods(funcs, monte_funcs, anal_funcs, intervals, h, experiments_amount):",
"3.22), \\ lambda x: math.sin(x) ** 3, \\ lambda x: 1 / (1",
"* 0.648437 if x == 2 else 0.648437, lambda x: -(math.log(x) + 1)",
"zip(*intervals) volume = np.prod([b - a for a, b in intervals]) integral =",
"for a, b in zip(lower, upper)] return res def monte_carlo(intervals, f, experiments_amount, random_generator=np.random.uniform):",
"- start)) start = time() monte_int = monte_carlo(intervals[:j], monte_funcs[i], experiments_amount) end = time()",
"anal_res.append(\"%.4f\" % np.prod([calc_int(func, interval) for func, interval in zip(anal_funcs[:j], intervals[:j])])) headers = (\"Arity\",",
"= time() quad_ints = np.prod([simpson(interval, func, h) for func, interval in zip(funcs[:j], intervals[:j])])",
"intervals[:j])])) headers = (\"Arity\", \"Monte-Carlo with uniform\", \"Monte-Carlo with normal\", \"Simpson\", \"Analytical\") content",
"{experiments_amount}') print(f'Step size = {h}') print(table) def main(): funcs = [lambda x: 1",
"2,\\ lambda x: math.log(np.abs(x + math.sqrt(x ** 2 + 3.22))),\\ lambda x: (math.cos(3",
"in zip(lower, upper)] return res def monte_carlo(intervals, f, experiments_amount, random_generator=np.random.uniform): size = len(intervals)",
"- 9 *math.cos(x)) / 12,\\ lambda x: -2 / (math.tan(x / 2) +",
"quad_res = [] monte_times = [] monte_res = [] norm_times = [] norm_res",
"monte_times = [] monte_res = [] norm_times = [] norm_res = [] anal_res",
"x: funcs[0](x[0]) * funcs[1](x[1]) * funcs[2](x[2]), \\ lambda x: funcs[0](x[0]) * funcs[1](x[1]) *",
"from tabulate import tabulate def simpson(interval, f, h): a, b = interval n",
"x: 3 * math.log(np.cbrt(x ** 2) + 1) / 2,\\ lambda x: math.log(np.abs(x",
"a, b in intervals]) integral = volume * np.sum([f(random_generator(lower, upper, size)) for _",
"= 4 * np.sum([f(a + i * h) for i in range(1, n,",
"x: funcs[0](x[0]) * funcs[1](x[1]) * funcs[2](x[2]) * funcs[3](x[3]), \\ lambda x: funcs[0](x[0]) *",
"2)]) integral = h * (f(a) + first_part + second_part + f(b)) /",
"/ (math.tan(x / 2) + 1), lambda x: 2 * 0.648437 if x",
"= time() norm_res.append(\"%.4f\" % monte_int) norm_times.append(\"%.4f\" % (end - start)) anal_res.append(\"%.4f\" % np.prod([calc_int(func,",
"quad_times = [] quad_res = [] monte_times = [] monte_res = [] norm_times",
"i * h) for i in range(2, n - 1, 2)]) integral =",
"monte_int = monte_carlo(intervals[:j], monte_funcs[i], experiments_amount, normal_rand_generator) end = time() norm_res.append(\"%.4f\" % monte_int) norm_times.append(\"%.4f\"",
"size): res = [truncnorm.rvs(a, b) for a, b in zip(lower, upper)] return res",
"zip(list(range(1, len(intervals) + 1)), list(zip(monte_res, monte_times)), list(zip(norm_res, norm_times)), list(zip(quad_res, quad_times)), anal_res) table =",
"in zip(anal_funcs[:j], intervals[:j])])) headers = (\"Arity\", \"Monte-Carlo with uniform\", \"Monte-Carlo with normal\", \"Simpson\",",
"scipy.stats import truncnorm from time import time from tabulate import tabulate def simpson(interval,",
"+ 1)), list(zip(monte_res, monte_times)), list(zip(norm_res, norm_times)), list(zip(quad_res, quad_times)), anal_res) table = tabulate(list(content), headers,",
"in range(2, n - 1, 2)]) integral = h * (f(a) + first_part",
"+ 1), lambda x: 2 * 0.648437 if x == 2 else 0.648437,",
"/ experiments_amount return integral def calc_int(f, interval): a, b = interval return f(b)",
"import truncnorm from time import time from tabulate import tabulate def simpson(interval, f,",
"- 1, 2)]) integral = h * (f(a) + first_part + second_part +",
"= len(intervals) lower, upper = zip(*intervals) volume = np.prod([b - a for a,",
"\\ lambda x: funcs[0](x[0]) * funcs[1](x[1]) * funcs[2](x[2]) * funcs[3](x[3]), \\ lambda x:",
"first_part = 4 * np.sum([f(a + i * h) for i in range(1,",
"% monte_int) monte_times.append(\"%.4f\" % (end - start)) start = time() monte_int = monte_carlo(intervals[:j],",
"/ (x + np.cbrt(x)), \\ lambda x: 1 / math.sqrt(x ** 2 +",
"\"Simpson\", \"Analytical\") content = zip(list(range(1, len(intervals) + 1)), list(zip(monte_res, monte_times)), list(zip(norm_res, norm_times)), list(zip(quad_res,",
"funcs[0](x[0]) * funcs[1](x[1]), \\ lambda x: funcs[0](x[0]) * funcs[1](x[1]) * funcs[2](x[2]), \\ lambda",
"/ 12,\\ lambda x: -2 / (math.tan(x / 2) + 1), lambda x:",
"[lambda x: 3 * math.log(np.cbrt(x ** 2) + 1) / 2,\\ lambda x:",
"-2 / (math.tan(x / 2) + 1), lambda x: 2 * 0.648437 if",
"for i in range(len(intervals)): j = i + 1 start = time() quad_ints",
"interval in zip(anal_funcs[:j], intervals[:j])])) headers = (\"Arity\", \"Monte-Carlo with uniform\", \"Monte-Carlo with normal\",",
"[(-3, -1), (1, 3), (3, 5), (5, 7), (1.2, 2), (14, 88)] print(\"Format",
"[] quad_res = [] monte_times = [] monte_res = [] norm_times = []",
"*math.cos(x)) / 12,\\ lambda x: -2 / (math.tan(x / 2) + 1), lambda",
"+ 1 start = time() quad_ints = np.prod([simpson(interval, func, h) for func, interval",
"\\ lambda x: math.log(x) / (x ** 2) ] monte_funcs = [funcs[0], \\",
"random_generator=np.random.uniform): size = len(intervals) lower, upper = zip(*intervals) volume = np.prod([b - a",
"calc_int(f, interval): a, b = interval return f(b) - f(a) def bench_methods(funcs, monte_funcs,",
"lambda x: funcs[0](x[0]) * funcs[1](x[1]), \\ lambda x: funcs[0](x[0]) * funcs[1](x[1]) * funcs[2](x[2]),",
"size = {h}') print(table) def main(): funcs = [lambda x: 1 / (x",
"funcs[3](x[3]) * funcs[4](x[4]) * funcs[5](x[5]) ] anal_funcs = [lambda x: 3 * math.log(np.cbrt(x",
"def main(): funcs = [lambda x: 1 / (x + np.cbrt(x)), \\ lambda",
"i in range(len(intervals)): j = i + 1 start = time() quad_ints =",
"b = interval n = int((b - a) / h + 1) first_part",
"88)] print(\"Format in methods is (value, time in seconds)\") for h, experiments_amount in",
"funcs[2](x[2]) * funcs[3](x[3]), \\ lambda x: funcs[0](x[0]) * funcs[1](x[1]) * funcs[2](x[2]) * funcs[3](x[3])",
"[lambda x: 1 / (x + np.cbrt(x)), \\ lambda x: 1 / math.sqrt(x",
"start = time() monte_int = monte_carlo(intervals[:j], monte_funcs[i], experiments_amount, normal_rand_generator) end = time() norm_res.append(\"%.4f\"",
"for _ in range(experiments_amount)]) / experiments_amount return integral def calc_int(f, interval): a, b",
"= time() monte_int = monte_carlo(intervals[:j], monte_funcs[i], experiments_amount, normal_rand_generator) end = time() norm_res.append(\"%.4f\" %",
"norm_times.append(\"%.4f\" % (end - start)) anal_res.append(\"%.4f\" % np.prod([calc_int(func, interval) for func, interval in",
"funcs[0](x[0]) * funcs[1](x[1]) * funcs[2](x[2]) * funcs[3](x[3]), \\ lambda x: funcs[0](x[0]) * funcs[1](x[1])",
"= 2 * np.sum([f(a + i * h) for i in range(2, n",
"* funcs[1](x[1]) * funcs[2](x[2]) * funcs[3](x[3]), \\ lambda x: funcs[0](x[0]) * funcs[1](x[1]) *",
"= interval n = int((b - a) / h + 1) first_part =",
"+ 2) / x, \\ lambda x: math.log(x) / (x ** 2) ]",
"% np.prod([calc_int(func, interval) for func, interval in zip(anal_funcs[:j], intervals[:j])])) headers = (\"Arity\", \"Monte-Carlo",
"first_part + second_part + f(b)) / 3 return integral def normal_rand_generator(lower, upper, size):",
"lambda x: 1 / (1 + math.sin(x)), \\ lambda x: math.log(x + 2)",
"1 start = time() quad_ints = np.prod([simpson(interval, func, h) for func, interval in",
"print(f'Intervals = {intervals}') print(f'Monte-Carlo experiments {experiments_amount}') print(f'Step size = {h}') print(table) def main():",
"zip(lower, upper)] return res def monte_carlo(intervals, f, experiments_amount, random_generator=np.random.uniform): size = len(intervals) lower,",
"math.log(x) / (x ** 2) ] monte_funcs = [funcs[0], \\ lambda x: funcs[0](x[0])",
"normal_rand_generator(lower, upper, size): res = [truncnorm.rvs(a, b) for a, b in zip(lower, upper)]",
"x: math.log(x + 2) / x, \\ lambda x: math.log(x) / (x **",
"b in zip(lower, upper)] return res def monte_carlo(intervals, f, experiments_amount, random_generator=np.random.uniform): size =",
"monte_times)), list(zip(norm_res, norm_times)), list(zip(quad_res, quad_times)), anal_res) table = tabulate(list(content), headers, tablefmt=\"fancy_grid\") print(f'Intervals =",
"[] norm_times = [] norm_res = [] anal_res = [] for i in",
"2 * np.sum([f(a + i * h) for i in range(2, n -",
"else 0.648437, lambda x: -(math.log(x) + 1) / x ] intervals = [(-3,",
"in range(experiments_amount)]) / experiments_amount return integral def calc_int(f, interval): a, b = interval",
"** 2) + 1) / 2,\\ lambda x: math.log(np.abs(x + math.sqrt(x ** 2",
"5), (5, 7), (1.2, 2), (14, 88)] print(\"Format in methods is (value, time",
"print(\"Format in methods is (value, time in seconds)\") for h, experiments_amount in [(0.1,",
"\\ lambda x: funcs[0](x[0]) * funcs[1](x[1]), \\ lambda x: funcs[0](x[0]) * funcs[1](x[1]) *",
"integral = h * (f(a) + first_part + second_part + f(b)) / 3",
"% (end - start)) anal_res.append(\"%.4f\" % np.prod([calc_int(func, interval) for func, interval in zip(anal_funcs[:j],",
"b = interval return f(b) - f(a) def bench_methods(funcs, monte_funcs, anal_funcs, intervals, h,",
"- a for a, b in intervals]) integral = volume * np.sum([f(random_generator(lower, upper,",
"monte_carlo(intervals, f, experiments_amount, random_generator=np.random.uniform): size = len(intervals) lower, upper = zip(*intervals) volume =",
"end = time() quad_res.append(\"%.4f\" % quad_ints) quad_times.append(\"%.4f\" % (end - start)) start =",
"2), (14, 88)] print(\"Format in methods is (value, time in seconds)\") for h,",
"= [] anal_res = [] for i in range(len(intervals)): j = i +",
"h): a, b = interval n = int((b - a) / h +",
"math.sin(x)), \\ lambda x: math.log(x + 2) / x, \\ lambda x: math.log(x)",
"funcs[1](x[1]), \\ lambda x: funcs[0](x[0]) * funcs[1](x[1]) * funcs[2](x[2]), \\ lambda x: funcs[0](x[0])",
"truncnorm from time import time from tabulate import tabulate def simpson(interval, f, h):",
"len(intervals) + 1)), list(zip(monte_res, monte_times)), list(zip(norm_res, norm_times)), list(zip(quad_res, quad_times)), anal_res) table = tabulate(list(content),",
"= monte_carlo(intervals[:j], monte_funcs[i], experiments_amount, normal_rand_generator) end = time() norm_res.append(\"%.4f\" % monte_int) norm_times.append(\"%.4f\" %",
"= [lambda x: 3 * math.log(np.cbrt(x ** 2) + 1) / 2,\\ lambda",
"h) for i in range(1, n, 2)]) second_part = 2 * np.sum([f(a +",
"upper, size)) for _ in range(experiments_amount)]) / experiments_amount return integral def calc_int(f, interval):",
"print(f'Monte-Carlo experiments {experiments_amount}') print(f'Step size = {h}') print(table) def main(): funcs = [lambda",
"/ (1 + math.sin(x)), \\ lambda x: math.log(x + 2) / x, \\",
"1, 2)]) integral = h * (f(a) + first_part + second_part + f(b))",
"funcs[2](x[2]) * funcs[3](x[3]) * funcs[4](x[4]) * funcs[5](x[5]) ] anal_funcs = [lambda x: 3",
"[] norm_res = [] anal_res = [] for i in range(len(intervals)): j =",
"lambda x: funcs[0](x[0]) * funcs[1](x[1]) * funcs[2](x[2]), \\ lambda x: funcs[0](x[0]) * funcs[1](x[1])",
"** 2) ] monte_funcs = [funcs[0], \\ lambda x: funcs[0](x[0]) * funcs[1](x[1]), \\",
"integral = volume * np.sum([f(random_generator(lower, upper, size)) for _ in range(experiments_amount)]) / experiments_amount",
"= volume * np.sum([f(random_generator(lower, upper, size)) for _ in range(experiments_amount)]) / experiments_amount return",
"a, b = interval return f(b) - f(a) def bench_methods(funcs, monte_funcs, anal_funcs, intervals,",
"range(1, n, 2)]) second_part = 2 * np.sum([f(a + i * h) for",
"* np.sum([f(a + i * h) for i in range(1, n, 2)]) second_part",
"def normal_rand_generator(lower, upper, size): res = [truncnorm.rvs(a, b) for a, b in zip(lower,",
"size)) for _ in range(experiments_amount)]) / experiments_amount return integral def calc_int(f, interval): a,",
"list(zip(quad_res, quad_times)), anal_res) table = tabulate(list(content), headers, tablefmt=\"fancy_grid\") print(f'Intervals = {intervals}') print(f'Monte-Carlo experiments",
"+ np.cbrt(x)), \\ lambda x: 1 / math.sqrt(x ** 2 + 3.22), \\",
"experiments_amount, normal_rand_generator) end = time() norm_res.append(\"%.4f\" % monte_int) norm_times.append(\"%.4f\" % (end - start))",
"3), (3, 5), (5, 7), (1.2, 2), (14, 88)] print(\"Format in methods is",
"int((b - a) / h + 1) first_part = 4 * np.sum([f(a +",
"anal_res = [] for i in range(len(intervals)): j = i + 1 start",
"experiments_amount return integral def calc_int(f, interval): a, b = interval return f(b) -",
"funcs[4](x[4]) * funcs[5](x[5]) ] anal_funcs = [lambda x: 3 * math.log(np.cbrt(x ** 2)",
"[] monte_times = [] monte_res = [] norm_times = [] norm_res = []",
"[] anal_res = [] for i in range(len(intervals)): j = i + 1",
"monte_carlo(intervals[:j], monte_funcs[i], experiments_amount, normal_rand_generator) end = time() norm_res.append(\"%.4f\" % monte_int) norm_times.append(\"%.4f\" % (end",
"tabulate import tabulate def simpson(interval, f, h): a, b = interval n =",
"* math.log(np.cbrt(x ** 2) + 1) / 2,\\ lambda x: math.log(np.abs(x + math.sqrt(x",
"= (\"Arity\", \"Monte-Carlo with uniform\", \"Monte-Carlo with normal\", \"Simpson\", \"Analytical\") content = zip(list(range(1,",
"quad_res.append(\"%.4f\" % quad_ints) quad_times.append(\"%.4f\" % (end - start)) start = time() monte_int =",
"* (f(a) + first_part + second_part + f(b)) / 3 return integral def",
"experiments_amount, random_generator=np.random.uniform): size = len(intervals) lower, upper = zip(*intervals) volume = np.prod([b -",
"x ] intervals = [(-3, -1), (1, 3), (3, 5), (5, 7), (1.2,",
"+ 3.22))),\\ lambda x: (math.cos(3 * x) - 9 *math.cos(x)) / 12,\\ lambda",
"math.log(x + 2) / x, \\ lambda x: math.log(x) / (x ** 2)",
"uniform\", \"Monte-Carlo with normal\", \"Simpson\", \"Analytical\") content = zip(list(range(1, len(intervals) + 1)), list(zip(monte_res,",
"math from scipy.stats import truncnorm from time import time from tabulate import tabulate",
"lambda x: math.log(x) / (x ** 2) ] monte_funcs = [funcs[0], \\ lambda",
"return res def monte_carlo(intervals, f, experiments_amount, random_generator=np.random.uniform): size = len(intervals) lower, upper =",
"funcs[0](x[0]) * funcs[1](x[1]) * funcs[2](x[2]) * funcs[3](x[3]) * funcs[4](x[4]), \\ lambda x: funcs[0](x[0])",
"for func, interval in zip(funcs[:j], intervals[:j])]) end = time() quad_res.append(\"%.4f\" % quad_ints) quad_times.append(\"%.4f\"",
"func, interval in zip(funcs[:j], intervals[:j])]) end = time() quad_res.append(\"%.4f\" % quad_ints) quad_times.append(\"%.4f\" %",
"norm_times = [] norm_res = [] anal_res = [] for i in range(len(intervals)):",
"b) for a, b in zip(lower, upper)] return res def monte_carlo(intervals, f, experiments_amount,",
"* funcs[2](x[2]) * funcs[3](x[3]) * funcs[4](x[4]) * funcs[5](x[5]) ] anal_funcs = [lambda x:",
"content = zip(list(range(1, len(intervals) + 1)), list(zip(monte_res, monte_times)), list(zip(norm_res, norm_times)), list(zip(quad_res, quad_times)), anal_res)",
"-(math.log(x) + 1) / x ] intervals = [(-3, -1), (1, 3), (3,",
"import tabulate def simpson(interval, f, h): a, b = interval n = int((b",
"def monte_carlo(intervals, f, experiments_amount, random_generator=np.random.uniform): size = len(intervals) lower, upper = zip(*intervals) volume",
"[funcs[0], \\ lambda x: funcs[0](x[0]) * funcs[1](x[1]), \\ lambda x: funcs[0](x[0]) * funcs[1](x[1])",
"[] for i in range(len(intervals)): j = i + 1 start = time()",
"1) first_part = 4 * np.sum([f(a + i * h) for i in",
"(x ** 2) ] monte_funcs = [funcs[0], \\ lambda x: funcs[0](x[0]) * funcs[1](x[1]),",
"tabulate(list(content), headers, tablefmt=\"fancy_grid\") print(f'Intervals = {intervals}') print(f'Monte-Carlo experiments {experiments_amount}') print(f'Step size = {h}')",
"funcs[2](x[2]), \\ lambda x: funcs[0](x[0]) * funcs[1](x[1]) * funcs[2](x[2]) * funcs[3](x[3]), \\ lambda",
"time() quad_ints = np.prod([simpson(interval, func, h) for func, interval in zip(funcs[:j], intervals[:j])]) end",
"funcs[0](x[0]) * funcs[1](x[1]) * funcs[2](x[2]) * funcs[3](x[3]) * funcs[4](x[4]) * funcs[5](x[5]) ] anal_funcs",
"norm_times)), list(zip(quad_res, quad_times)), anal_res) table = tabulate(list(content), headers, tablefmt=\"fancy_grid\") print(f'Intervals = {intervals}') print(f'Monte-Carlo",
"table = tabulate(list(content), headers, tablefmt=\"fancy_grid\") print(f'Intervals = {intervals}') print(f'Monte-Carlo experiments {experiments_amount}') print(f'Step size",
"** 3, \\ lambda x: 1 / (1 + math.sin(x)), \\ lambda x:",
"* funcs[1](x[1]) * funcs[2](x[2]), \\ lambda x: funcs[0](x[0]) * funcs[1](x[1]) * funcs[2](x[2]) *",
"(14, 88)] print(\"Format in methods is (value, time in seconds)\") for h, experiments_amount",
"x: 1 / math.sqrt(x ** 2 + 3.22), \\ lambda x: math.sin(x) **",
"funcs[1](x[1]) * funcs[2](x[2]) * funcs[3](x[3]), \\ lambda x: funcs[0](x[0]) * funcs[1](x[1]) * funcs[2](x[2])",
"intervals, h, experiments_amount): quad_times = [] quad_res = [] monte_times = [] monte_res",
"second_part = 2 * np.sum([f(a + i * h) for i in range(2,",
"b in intervals]) integral = volume * np.sum([f(random_generator(lower, upper, size)) for _ in",
"lambda x: math.log(x + 2) / x, \\ lambda x: math.log(x) / (x",
"time from tabulate import tabulate def simpson(interval, f, h): a, b = interval",
"12,\\ lambda x: -2 / (math.tan(x / 2) + 1), lambda x: 2",
"time() monte_res.append(\"%.4f\" % monte_int) monte_times.append(\"%.4f\" % (end - start)) start = time() monte_int",
"lambda x: funcs[0](x[0]) * funcs[1](x[1]) * funcs[2](x[2]) * funcs[3](x[3]) * funcs[4](x[4]), \\ lambda",
"a for a, b in intervals]) integral = volume * np.sum([f(random_generator(lower, upper, size))",
"2) / x, \\ lambda x: math.log(x) / (x ** 2) ] monte_funcs",
"time() quad_res.append(\"%.4f\" % quad_ints) quad_times.append(\"%.4f\" % (end - start)) start = time() monte_int",
"(5, 7), (1.2, 2), (14, 88)] print(\"Format in methods is (value, time in",
"monte_carlo(intervals[:j], monte_funcs[i], experiments_amount) end = time() monte_res.append(\"%.4f\" % monte_int) monte_times.append(\"%.4f\" % (end -",
"= [] monte_times = [] monte_res = [] norm_times = [] norm_res =",
"time() norm_res.append(\"%.4f\" % monte_int) norm_times.append(\"%.4f\" % (end - start)) anal_res.append(\"%.4f\" % np.prod([calc_int(func, interval)",
"monte_funcs[i], experiments_amount, normal_rand_generator) end = time() norm_res.append(\"%.4f\" % monte_int) norm_times.append(\"%.4f\" % (end -",
"x: 1 / (1 + math.sin(x)), \\ lambda x: math.log(x + 2) /",
"- start)) start = time() monte_int = monte_carlo(intervals[:j], monte_funcs[i], experiments_amount, normal_rand_generator) end =",
"2 + 3.22), \\ lambda x: math.sin(x) ** 3, \\ lambda x: 1",
"= time() monte_res.append(\"%.4f\" % monte_int) monte_times.append(\"%.4f\" % (end - start)) start = time()",
"x) - 9 *math.cos(x)) / 12,\\ lambda x: -2 / (math.tan(x / 2)",
"tablefmt=\"fancy_grid\") print(f'Intervals = {intervals}') print(f'Monte-Carlo experiments {experiments_amount}') print(f'Step size = {h}') print(table) def",
"- a) / h + 1) first_part = 4 * np.sum([f(a + i",
"monte_res.append(\"%.4f\" % monte_int) monte_times.append(\"%.4f\" % (end - start)) start = time() monte_int =",
"start = time() quad_ints = np.prod([simpson(interval, func, h) for func, interval in zip(funcs[:j],",
"is (value, time in seconds)\") for h, experiments_amount in [(0.1, 100), (0.01, 1000)]:",
"(math.tan(x / 2) + 1), lambda x: 2 * 0.648437 if x ==",
"i + 1 start = time() quad_ints = np.prod([simpson(interval, func, h) for func,",
"2 + 3.22))),\\ lambda x: (math.cos(3 * x) - 9 *math.cos(x)) / 12,\\",
"\"Monte-Carlo with normal\", \"Simpson\", \"Analytical\") content = zip(list(range(1, len(intervals) + 1)), list(zip(monte_res, monte_times)),",
"(math.cos(3 * x) - 9 *math.cos(x)) / 12,\\ lambda x: -2 / (math.tan(x",
"integral def calc_int(f, interval): a, b = interval return f(b) - f(a) def",
"* funcs[3](x[3]) * funcs[4](x[4]) * funcs[5](x[5]) ] anal_funcs = [lambda x: 3 *",
"funcs[1](x[1]) * funcs[2](x[2]), \\ lambda x: funcs[0](x[0]) * funcs[1](x[1]) * funcs[2](x[2]) * funcs[3](x[3]),",
"funcs[4](x[4]), \\ lambda x: funcs[0](x[0]) * funcs[1](x[1]) * funcs[2](x[2]) * funcs[3](x[3]) * funcs[4](x[4])"
] |
[
"its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version",
"governing # permissions and limitations under the License. from io import BytesIO from",
"_write_to(w, events): write_event_types = [] for event in events: write_event_types.append(w.send(event)) return write_event_types def",
"License for the specific language governing # permissions and limitations under the License.",
"import BytesIO from amazon.ion.writer import blocking_writer from amazon.ion.writer_binary import binary_writer from amazon.ion.writer_text import",
"events, algorithm) _run_test(_writer_provider(\"text\"), events, algorithm) def _run_test(writer_provider, events, algorithm): # capture behavior of",
"from .util import binary_reader_over from .util import consume from .util import hash_function_provider def",
"in compliance with the License. # A copy of the License is located",
"permissions and limitations under the License. from io import BytesIO from amazon.ion.writer import",
"This file is distributed # on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR",
"= BytesIO() hw = hash_writer(blocking_writer(writer_provider(), hw_bytes), hash_function_provider(algorithm)) hw_write_event_types = _write_to(hw, events) # assert",
"hw_write_event_types == expected_write_event_types # assert writer/hash_writer produced the same output assert hw_bytes.getvalue() ==",
"return write_event_types def _writer_provider(type): def _f(): if type == \"binary\": return binary_writer() elif",
"5} 6) }, 7]' algorithm = \"md5\" # generate events to be used",
"assert writer/hash_writer response behavior is identical assert hw_write_event_types == expected_write_event_types # assert writer/hash_writer",
"from io import BytesIO from amazon.ion.writer import blocking_writer from amazon.ion.writer_binary import binary_writer from",
"file accompanying this file. This file is distributed # on an \"AS IS\"",
"amazon.ion.writer_text import raw_writer from ionhash.hasher import hash_writer from .util import binary_reader_over from .util",
"be used to write the data events = consume(binary_reader_over(ion_str)) _run_test(_writer_provider(\"binary\"), events, algorithm) _run_test(_writer_provider(\"text\"),",
"hw = hash_writer(blocking_writer(writer_provider(), hw_bytes), hash_function_provider(algorithm)) hw_write_event_types = _write_to(hw, events) # assert writer/hash_writer response",
"= consume(binary_reader_over(ion_str)) _run_test(_writer_provider(\"binary\"), events, algorithm) _run_test(_writer_provider(\"text\"), events, algorithm) def _run_test(writer_provider, events, algorithm): #",
"6) }, 7]' algorithm = \"md5\" # generate events to be used to",
"algorithm) _run_test(_writer_provider(\"text\"), events, algorithm) def _run_test(writer_provider, events, algorithm): # capture behavior of an",
"this file except in compliance with the License. # A copy of the",
"# express or implied. See the License for the specific language governing #",
"and limitations under the License. from io import BytesIO from amazon.ion.writer import blocking_writer",
"specific language governing # permissions and limitations under the License. from io import",
"A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"}, 7]' algorithm = \"md5\" # generate events to be used to write",
"CONDITIONS OF ANY KIND, either # express or implied. See the License for",
"to be used to write the data events = consume(binary_reader_over(ion_str)) _run_test(_writer_provider(\"binary\"), events, algorithm)",
"OF ANY KIND, either # express or implied. See the License for the",
"from amazon.ion.writer import blocking_writer from amazon.ion.writer_binary import binary_writer from amazon.ion.writer_text import raw_writer from",
"identical assert hw_write_event_types == expected_write_event_types # assert writer/hash_writer produced the same output assert",
"ANY KIND, either # express or implied. See the License for the specific",
"algorithm) def _run_test(writer_provider, events, algorithm): # capture behavior of an ion-python writer expected_bytes",
"raw_writer from ionhash.hasher import hash_writer from .util import binary_reader_over from .util import consume",
"implied. See the License for the specific language governing # permissions and limitations",
"Version 2.0 (the \"License\"). # You may not use this file except in",
"generate events to be used to write the data events = consume(binary_reader_over(ion_str)) _run_test(_writer_provider(\"binary\"),",
"write_event_types.append(w.send(event)) return write_event_types def _writer_provider(type): def _f(): if type == \"binary\": return binary_writer()",
"compliance with the License. # A copy of the License is located at",
"expected_bytes = BytesIO() w = blocking_writer(writer_provider(), expected_bytes) expected_write_event_types = _write_to(w, events) hw_bytes =",
"write_event_types = [] for event in events: write_event_types.append(w.send(event)) return write_event_types def _writer_provider(type): def",
"import hash_function_provider def test_hash_writer(): ion_str = '[1, 2, {a: 3, b: (4 {c:",
"import raw_writer from ionhash.hasher import hash_writer from .util import binary_reader_over from .util import",
"hash_writer from .util import binary_reader_over from .util import consume from .util import hash_function_provider",
"algorithm = \"md5\" # generate events to be used to write the data",
"if type == \"binary\": return binary_writer() elif type == \"text\": return raw_writer() return",
"test_hash_writer(): ion_str = '[1, 2, {a: 3, b: (4 {c: 5} 6) },",
"from amazon.ion.writer_binary import binary_writer from amazon.ion.writer_text import raw_writer from ionhash.hasher import hash_writer from",
"(the \"License\"). # You may not use this file except in compliance with",
"= '[1, 2, {a: 3, b: (4 {c: 5} 6) }, 7]' algorithm",
"io import BytesIO from amazon.ion.writer import blocking_writer from amazon.ion.writer_binary import binary_writer from amazon.ion.writer_text",
"events) # assert writer/hash_writer response behavior is identical assert hw_write_event_types == expected_write_event_types #",
"on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"3, b: (4 {c: 5} 6) }, 7]' algorithm = \"md5\" # generate",
"accompanying this file. This file is distributed # on an \"AS IS\" BASIS,",
"events, algorithm): # capture behavior of an ion-python writer expected_bytes = BytesIO() w",
"data events = consume(binary_reader_over(ion_str)) _run_test(_writer_provider(\"binary\"), events, algorithm) _run_test(_writer_provider(\"text\"), events, algorithm) def _run_test(writer_provider, events,",
"= BytesIO() w = blocking_writer(writer_provider(), expected_bytes) expected_write_event_types = _write_to(w, events) hw_bytes = BytesIO()",
"events: write_event_types.append(w.send(event)) return write_event_types def _writer_provider(type): def _f(): if type == \"binary\": return",
"def _writer_provider(type): def _f(): if type == \"binary\": return binary_writer() elif type ==",
"expected_write_event_types # assert writer/hash_writer produced the same output assert hw_bytes.getvalue() == expected_bytes.getvalue() def",
"is distributed # on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF",
"hash_function_provider def test_hash_writer(): ion_str = '[1, 2, {a: 3, b: (4 {c: 5}",
"def _run_test(writer_provider, events, algorithm): # capture behavior of an ion-python writer expected_bytes =",
"_write_to(w, events) hw_bytes = BytesIO() hw = hash_writer(blocking_writer(writer_provider(), hw_bytes), hash_function_provider(algorithm)) hw_write_event_types = _write_to(hw,",
"hw_write_event_types = _write_to(hw, events) # assert writer/hash_writer response behavior is identical assert hw_write_event_types",
"assert hw_write_event_types == expected_write_event_types # assert writer/hash_writer produced the same output assert hw_bytes.getvalue()",
"== expected_write_event_types # assert writer/hash_writer produced the same output assert hw_bytes.getvalue() == expected_bytes.getvalue()",
"write the data events = consume(binary_reader_over(ion_str)) _run_test(_writer_provider(\"binary\"), events, algorithm) _run_test(_writer_provider(\"text\"), events, algorithm) def",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # or in the \"license\" file accompanying this file.",
"under the License. from io import BytesIO from amazon.ion.writer import blocking_writer from amazon.ion.writer_binary",
"License, Version 2.0 (the \"License\"). # You may not use this file except",
"expected_bytes) expected_write_event_types = _write_to(w, events) hw_bytes = BytesIO() hw = hash_writer(blocking_writer(writer_provider(), hw_bytes), hash_function_provider(algorithm))",
"You may not use this file except in compliance with the License. #",
"the same output assert hw_bytes.getvalue() == expected_bytes.getvalue() def _write_to(w, events): write_event_types = []",
"event in events: write_event_types.append(w.send(event)) return write_event_types def _writer_provider(type): def _f(): if type ==",
"of an ion-python writer expected_bytes = BytesIO() w = blocking_writer(writer_provider(), expected_bytes) expected_write_event_types =",
"the Apache License, Version 2.0 (the \"License\"). # You may not use this",
"= hash_writer(blocking_writer(writer_provider(), hw_bytes), hash_function_provider(algorithm)) hw_write_event_types = _write_to(hw, events) # assert writer/hash_writer response behavior",
"(4 {c: 5} 6) }, 7]' algorithm = \"md5\" # generate events to",
"of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in",
"file except in compliance with the License. # A copy of the License",
"WARRANTIES OR CONDITIONS OF ANY KIND, either # express or implied. See the",
"# permissions and limitations under the License. from io import BytesIO from amazon.ion.writer",
"hw_bytes), hash_function_provider(algorithm)) hw_write_event_types = _write_to(hw, events) # assert writer/hash_writer response behavior is identical",
"produced the same output assert hw_bytes.getvalue() == expected_bytes.getvalue() def _write_to(w, events): write_event_types =",
"to write the data events = consume(binary_reader_over(ion_str)) _run_test(_writer_provider(\"binary\"), events, algorithm) _run_test(_writer_provider(\"text\"), events, algorithm)",
"is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the \"license\" file",
"# assert writer/hash_writer produced the same output assert hw_bytes.getvalue() == expected_bytes.getvalue() def _write_to(w,",
"== expected_bytes.getvalue() def _write_to(w, events): write_event_types = [] for event in events: write_event_types.append(w.send(event))",
"events = consume(binary_reader_over(ion_str)) _run_test(_writer_provider(\"binary\"), events, algorithm) _run_test(_writer_provider(\"text\"), events, algorithm) def _run_test(writer_provider, events, algorithm):",
"\"license\" file accompanying this file. This file is distributed # on an \"AS",
"_run_test(_writer_provider(\"binary\"), events, algorithm) _run_test(_writer_provider(\"text\"), events, algorithm) def _run_test(writer_provider, events, algorithm): # capture behavior",
"response behavior is identical assert hw_write_event_types == expected_write_event_types # assert writer/hash_writer produced the",
"Reserved. # # Licensed under the Apache License, Version 2.0 (the \"License\"). #",
"def _write_to(w, events): write_event_types = [] for event in events: write_event_types.append(w.send(event)) return write_event_types",
"consume from .util import hash_function_provider def test_hash_writer(): ion_str = '[1, 2, {a: 3,",
"hash_writer(blocking_writer(writer_provider(), hw_bytes), hash_function_provider(algorithm)) hw_write_event_types = _write_to(hw, events) # assert writer/hash_writer response behavior is",
"http://www.apache.org/licenses/LICENSE-2.0 # # or in the \"license\" file accompanying this file. This file",
"ion_str = '[1, 2, {a: 3, b: (4 {c: 5} 6) }, 7]'",
"blocking_writer from amazon.ion.writer_binary import binary_writer from amazon.ion.writer_text import raw_writer from ionhash.hasher import hash_writer",
"from amazon.ion.writer_text import raw_writer from ionhash.hasher import hash_writer from .util import binary_reader_over from",
"b: (4 {c: 5} 6) }, 7]' algorithm = \"md5\" # generate events",
"may not use this file except in compliance with the License. # A",
"in the \"license\" file accompanying this file. This file is distributed # on",
"or in the \"license\" file accompanying this file. This file is distributed #",
"# assert writer/hash_writer response behavior is identical assert hw_write_event_types == expected_write_event_types # assert",
"import hash_writer from .util import binary_reader_over from .util import consume from .util import",
"\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either # express",
"output assert hw_bytes.getvalue() == expected_bytes.getvalue() def _write_to(w, events): write_event_types = [] for event",
"from ionhash.hasher import hash_writer from .util import binary_reader_over from .util import consume from",
"behavior of an ion-python writer expected_bytes = BytesIO() w = blocking_writer(writer_provider(), expected_bytes) expected_write_event_types",
"# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"an ion-python writer expected_bytes = BytesIO() w = blocking_writer(writer_provider(), expected_bytes) expected_write_event_types = _write_to(w,",
"BytesIO() hw = hash_writer(blocking_writer(writer_provider(), hw_bytes), hash_function_provider(algorithm)) hw_write_event_types = _write_to(hw, events) # assert writer/hash_writer",
"ion-python writer expected_bytes = BytesIO() w = blocking_writer(writer_provider(), expected_bytes) expected_write_event_types = _write_to(w, events)",
"# # Licensed under the Apache License, Version 2.0 (the \"License\"). # You",
"# A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"use this file except in compliance with the License. # A copy of",
"events): write_event_types = [] for event in events: write_event_types.append(w.send(event)) return write_event_types def _writer_provider(type):",
"def _f(): if type == \"binary\": return binary_writer() elif type == \"text\": return",
"Apache License, Version 2.0 (the \"License\"). # You may not use this file",
"this file. This file is distributed # on an \"AS IS\" BASIS, WITHOUT",
"file is distributed # on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS",
"_write_to(hw, events) # assert writer/hash_writer response behavior is identical assert hw_write_event_types == expected_write_event_types",
"located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the \"license\" file accompanying",
"events to be used to write the data events = consume(binary_reader_over(ion_str)) _run_test(_writer_provider(\"binary\"), events,",
"OR CONDITIONS OF ANY KIND, either # express or implied. See the License",
"distributed # on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"import blocking_writer from amazon.ion.writer_binary import binary_writer from amazon.ion.writer_text import raw_writer from ionhash.hasher import",
"expected_write_event_types = _write_to(w, events) hw_bytes = BytesIO() hw = hash_writer(blocking_writer(writer_provider(), hw_bytes), hash_function_provider(algorithm)) hw_write_event_types",
"Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the \"License\").",
"\"md5\" # generate events to be used to write the data events =",
"All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the",
"# or in the \"license\" file accompanying this file. This file is distributed",
"import binary_writer from amazon.ion.writer_text import raw_writer from ionhash.hasher import hash_writer from .util import",
"or its affiliates. All Rights Reserved. # # Licensed under the Apache License,",
"or implied. See the License for the specific language governing # permissions and",
".util import binary_reader_over from .util import consume from .util import hash_function_provider def test_hash_writer():",
"type == \"binary\": return binary_writer() elif type == \"text\": return raw_writer() return _f",
"binary_reader_over from .util import consume from .util import hash_function_provider def test_hash_writer(): ion_str =",
"assert hw_bytes.getvalue() == expected_bytes.getvalue() def _write_to(w, events): write_event_types = [] for event in",
"# http://www.apache.org/licenses/LICENSE-2.0 # # or in the \"license\" file accompanying this file. This",
"the License. # A copy of the License is located at # #",
"# capture behavior of an ion-python writer expected_bytes = BytesIO() w = blocking_writer(writer_provider(),",
"BytesIO from amazon.ion.writer import blocking_writer from amazon.ion.writer_binary import binary_writer from amazon.ion.writer_text import raw_writer",
"See the License for the specific language governing # permissions and limitations under",
"= [] for event in events: write_event_types.append(w.send(event)) return write_event_types def _writer_provider(type): def _f():",
"_run_test(writer_provider, events, algorithm): # capture behavior of an ion-python writer expected_bytes = BytesIO()",
"events, algorithm) def _run_test(writer_provider, events, algorithm): # capture behavior of an ion-python writer",
"Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache",
"import consume from .util import hash_function_provider def test_hash_writer(): ion_str = '[1, 2, {a:",
"_run_test(_writer_provider(\"text\"), events, algorithm) def _run_test(writer_provider, events, algorithm): # capture behavior of an ion-python",
"= _write_to(hw, events) # assert writer/hash_writer response behavior is identical assert hw_write_event_types ==",
"file. This file is distributed # on an \"AS IS\" BASIS, WITHOUT WARRANTIES",
"_writer_provider(type): def _f(): if type == \"binary\": return binary_writer() elif type == \"text\":",
"License. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0",
"# Licensed under the Apache License, Version 2.0 (the \"License\"). # You may",
"affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0",
"# # or in the \"license\" file accompanying this file. This file is",
"assert writer/hash_writer produced the same output assert hw_bytes.getvalue() == expected_bytes.getvalue() def _write_to(w, events):",
"either # express or implied. See the License for the specific language governing",
"expected_bytes.getvalue() def _write_to(w, events): write_event_types = [] for event in events: write_event_types.append(w.send(event)) return",
"same output assert hw_bytes.getvalue() == expected_bytes.getvalue() def _write_to(w, events): write_event_types = [] for",
"binary_writer from amazon.ion.writer_text import raw_writer from ionhash.hasher import hash_writer from .util import binary_reader_over",
"an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either #",
"capture behavior of an ion-python writer expected_bytes = BytesIO() w = blocking_writer(writer_provider(), expected_bytes)",
"= blocking_writer(writer_provider(), expected_bytes) expected_write_event_types = _write_to(w, events) hw_bytes = BytesIO() hw = hash_writer(blocking_writer(writer_provider(),",
"the License. from io import BytesIO from amazon.ion.writer import blocking_writer from amazon.ion.writer_binary import",
"{a: 3, b: (4 {c: 5} 6) }, 7]' algorithm = \"md5\" #",
"BytesIO() w = blocking_writer(writer_provider(), expected_bytes) expected_write_event_types = _write_to(w, events) hw_bytes = BytesIO() hw",
"the specific language governing # permissions and limitations under the License. from io",
"amazon.ion.writer import blocking_writer from amazon.ion.writer_binary import binary_writer from amazon.ion.writer_text import raw_writer from ionhash.hasher",
"ionhash.hasher import hash_writer from .util import binary_reader_over from .util import consume from .util",
"# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # #",
"Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed",
"= \"md5\" # generate events to be used to write the data events",
"under the Apache License, Version 2.0 (the \"License\"). # You may not use",
"the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the",
"{c: 5} 6) }, 7]' algorithm = \"md5\" # generate events to be",
"License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the \"license\"",
"blocking_writer(writer_provider(), expected_bytes) expected_write_event_types = _write_to(w, events) hw_bytes = BytesIO() hw = hash_writer(blocking_writer(writer_provider(), hw_bytes),",
"2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under",
"used to write the data events = consume(binary_reader_over(ion_str)) _run_test(_writer_provider(\"binary\"), events, algorithm) _run_test(_writer_provider(\"text\"), events,",
"writer expected_bytes = BytesIO() w = blocking_writer(writer_provider(), expected_bytes) expected_write_event_types = _write_to(w, events) hw_bytes",
"7]' algorithm = \"md5\" # generate events to be used to write the",
"import binary_reader_over from .util import consume from .util import hash_function_provider def test_hash_writer(): ion_str",
"writer/hash_writer response behavior is identical assert hw_write_event_types == expected_write_event_types # assert writer/hash_writer produced",
"copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or",
"KIND, either # express or implied. See the License for the specific language",
"IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either # express or",
"= _write_to(w, events) hw_bytes = BytesIO() hw = hash_writer(blocking_writer(writer_provider(), hw_bytes), hash_function_provider(algorithm)) hw_write_event_types =",
"<filename>tests/test_hash_writer.py<gh_stars>1-10 # Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. #",
"amazon.ion.writer_binary import binary_writer from amazon.ion.writer_text import raw_writer from ionhash.hasher import hash_writer from .util",
"_f(): if type == \"binary\": return binary_writer() elif type == \"text\": return raw_writer()",
"def test_hash_writer(): ion_str = '[1, 2, {a: 3, b: (4 {c: 5} 6)",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the \"license\" file accompanying this",
"behavior is identical assert hw_write_event_types == expected_write_event_types # assert writer/hash_writer produced the same",
"# You may not use this file except in compliance with the License.",
"License. from io import BytesIO from amazon.ion.writer import blocking_writer from amazon.ion.writer_binary import binary_writer",
"the \"license\" file accompanying this file. This file is distributed # on an",
"hash_function_provider(algorithm)) hw_write_event_types = _write_to(hw, events) # assert writer/hash_writer response behavior is identical assert",
"Licensed under the Apache License, Version 2.0 (the \"License\"). # You may not",
"BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either # express or implied.",
"writer/hash_writer produced the same output assert hw_bytes.getvalue() == expected_bytes.getvalue() def _write_to(w, events): write_event_types",
".util import consume from .util import hash_function_provider def test_hash_writer(): ion_str = '[1, 2,",
"Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the",
"for event in events: write_event_types.append(w.send(event)) return write_event_types def _writer_provider(type): def _f(): if type",
"hw_bytes.getvalue() == expected_bytes.getvalue() def _write_to(w, events): write_event_types = [] for event in events:",
"# generate events to be used to write the data events = consume(binary_reader_over(ion_str))",
"hw_bytes = BytesIO() hw = hash_writer(blocking_writer(writer_provider(), hw_bytes), hash_function_provider(algorithm)) hw_write_event_types = _write_to(hw, events) #",
"in events: write_event_types.append(w.send(event)) return write_event_types def _writer_provider(type): def _f(): if type == \"binary\":",
"not use this file except in compliance with the License. # A copy",
"with the License. # A copy of the License is located at #",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either # express or implied. See",
"limitations under the License. from io import BytesIO from amazon.ion.writer import blocking_writer from",
"'[1, 2, {a: 3, b: (4 {c: 5} 6) }, 7]' algorithm =",
".util import hash_function_provider def test_hash_writer(): ion_str = '[1, 2, {a: 3, b: (4",
"consume(binary_reader_over(ion_str)) _run_test(_writer_provider(\"binary\"), events, algorithm) _run_test(_writer_provider(\"text\"), events, algorithm) def _run_test(writer_provider, events, algorithm): # capture",
"2.0 (the \"License\"). # You may not use this file except in compliance",
"from .util import hash_function_provider def test_hash_writer(): ion_str = '[1, 2, {a: 3, b:",
"events) hw_bytes = BytesIO() hw = hash_writer(blocking_writer(writer_provider(), hw_bytes), hash_function_provider(algorithm)) hw_write_event_types = _write_to(hw, events)",
"2, {a: 3, b: (4 {c: 5} 6) }, 7]' algorithm = \"md5\"",
"for the specific language governing # permissions and limitations under the License. from",
"except in compliance with the License. # A copy of the License is",
"the License for the specific language governing # permissions and limitations under the",
"from .util import consume from .util import hash_function_provider def test_hash_writer(): ion_str = '[1,",
"w = blocking_writer(writer_provider(), expected_bytes) expected_write_event_types = _write_to(w, events) hw_bytes = BytesIO() hw =",
"algorithm): # capture behavior of an ion-python writer expected_bytes = BytesIO() w =",
"express or implied. See the License for the specific language governing # permissions",
"is identical assert hw_write_event_types == expected_write_event_types # assert writer/hash_writer produced the same output",
"\"License\"). # You may not use this file except in compliance with the",
"write_event_types def _writer_provider(type): def _f(): if type == \"binary\": return binary_writer() elif type",
"[] for event in events: write_event_types.append(w.send(event)) return write_event_types def _writer_provider(type): def _f(): if",
"language governing # permissions and limitations under the License. from io import BytesIO",
"the data events = consume(binary_reader_over(ion_str)) _run_test(_writer_provider(\"binary\"), events, algorithm) _run_test(_writer_provider(\"text\"), events, algorithm) def _run_test(writer_provider,"
] |
[
"dim=1) contrast_loss = contrast_criterion(features) ce_loss = 0 for label_idx in range(5): tgt =",
"checkpoint def checkpoint(epoch): print('=====> Saving checkpoint...') state = { 'model': model.state_dict(), 'epoch': epoch,",
"contrast_loss + ce_loss * args.ce_weight loss.backward() optimizer.step() train_loss += loss.item() total += targets[0].size(0)",
"print('\\nEpoch: %d' % epoch) net.train() train_loss = 0 correct = 0 total =",
"= contrast_criterion(features) ce_loss = 0 for label_idx in range(5): tgt = targets[label_idx].long() lgt",
"default=1e-4, help='weight decay') parser.add_argument('--momentum', type=float, default=0.9, help='momentum') args = parser.parse_args() args.epochs = args.epoch",
"as tb_logger from models.resnet_cifar_multibn_ensembleFC import resnet18 as ResNet18 import random from fr_util import",
"# # ================================================================== # # Save checkpoint def checkpoint(epoch): print('=====> Saving checkpoint...') state",
"= apex.parallel.convert_syncbn_model(model) model = nn.DataParallel(model) model = model.cuda() cudnn.benchmark = True else: print('single",
"import torch import torch.nn as nn import torch.nn.functional as F import torchvision.transforms as",
"+ torch.zeros_like(x1).uniform_(-self.epsilon, self.epsilon) x_ce = x_ce + torch.zeros_like(x1).uniform_(-self.epsilon, self.epsilon) for i in range(self.num_steps):",
"torch.min(torch.max(x_ce, images_org - self.epsilon), images_org + self.epsilon) x_ce = torch.clamp(x_ce, 0, 1) return",
"label_pseudo_train_list.append(label_pseudo_train) train_dataset = CIFAR10IndexPseudoLabelEnsemble(root='data', transform=transform_train, pseudoLabel_002=label_pseudo_train_list[0], pseudoLabel_010=label_pseudo_train_list[1], pseudoLabel_050=label_pseudo_train_list[2], pseudoLabel_100=label_pseudo_train_list[3], pseudoLabel_500=label_pseudo_train_list[4], download=True) # Data",
"i in range(self.num_steps): x_cl.requires_grad_() x_ce.requires_grad_() with torch.enable_grad(): f_proj, f_pred = self.model(x_cl, bn_name='pgd', contrast=True)",
"= model(x1, bn_name='normal', contrast=True) f2_proj, f2_pred = model(x2, bn_name='normal', contrast=True) f_high_proj, f_high_pred =",
"args.epochs)) / 2 else: args.warmup_to = args.learning_rate start_epoch = 0 # start from",
"* args.ce_weight loss.backward() optimizer.step() train_loss += loss.item() total += targets[0].size(0) progress_bar(batch_idx, len(train_loader), 'Loss:",
"eta_min = args.learning_rate * (args.lr_decay_rate ** 3) args.warmup_to = eta_min + (args.learning_rate -",
"rate for learning rate') parser.add_argument('--weight_decay', type=float, default=1e-4, help='weight decay') parser.add_argument('--momentum', type=float, default=0.9, help='momentum')",
"eta_min) * ( 1 + math.cos(math.pi * args.warm_epochs / args.epochs)) / 2 else:",
"True, 'loss_func': 'xent', } # ================================================================== # # Data and Pre-processing # #",
"if torch.cuda.device_count() > 1: print(\"=====> Let's use\", torch.cuda.device_count(), \"GPUs!\") model = apex.parallel.convert_syncbn_model(model) model",
"upper bound change of L-inf norm on input pixels') parser.add_argument('--iter', type=int, default=5, help='The",
"pseudoLabel_050=label_pseudo_train_list[2], pseudoLabel_100=label_pseudo_train_list[3], pseudoLabel_500=label_pseudo_train_list[4], download=True) # Data Loader train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True, num_workers=n_gpu*4)",
"default=1000, help='total epochs') parser.add_argument('--save-epoch', type=int, default=100, help='save epochs') parser.add_argument('--epsilon', type=float, default=8, help='The upper",
"state = { 'model': model.state_dict(), 'epoch': epoch, 'rng_state': torch.get_rng_state() } save_dir = './checkpoint/{}'.format(args.name)",
"parser = argparse.ArgumentParser() parser.add_argument('--name', type=str, default='advcl_cifar10', help='name of the run') parser.add_argument('--cname', type=str, default='imagenet_clPretrain',",
"torch.nn as nn import torch.nn.functional as F import torchvision.transforms as transforms import torch.utils.data",
"= ['normal', 'pgd', 'pgd_ce'] model = ResNet18(bn_names=bn_names) model = model.cuda() # tb_logger if",
"# # ================================================================== # np.random.seed(args.seed) random.seed(args.seed) torch.manual_seed(args.seed) torch.cuda.manual_seed_all(args.seed) for epoch in range(start_epoch, args.epoch+2):",
"on input pixels') parser.add_argument('--iter', type=int, default=5, help='The number of iterations for iterative attacks')",
"Inputs and Pre-definition # # ================================================================== # # Arguments parser = argparse.ArgumentParser() parser.add_argument('--name',",
"iterations for iterative attacks') parser.add_argument('--radius', type=int, default=8, help='radius of low freq images') parser.add_argument('--ce_weight',",
"f_high_proj, f_high_pred = self.model(x_HFC, bn_name='normal', contrast=True) features = torch.cat([f_proj.unsqueeze(1), f1_proj.unsqueeze(1), f2_proj.unsqueeze(1), f_high_proj.unsqueeze(1)], dim=1)",
"+ (args.learning_rate - eta_min) * ( 1 + math.cos(math.pi * args.warm_epochs / args.epochs))",
"]) transform_train = TwoCropTransformAdv(transform_train, train_transform_org) transform_test = transforms.Compose([ transforms.ToTensor(), ]) label_pseudo_train_list = []",
"# # PGD attack model class AttackPGD(nn.Module): def __init__(self, model, config): super(AttackPGD, self).__init__()",
"epochs') parser.add_argument('--save-epoch', type=int, default=100, help='save epochs') parser.add_argument('--epsilon', type=float, default=8, help='The upper bound change",
"args.warmup_from = 0.01 args.warm_epochs = 10 if args.cosine: eta_min = args.learning_rate * (args.lr_decay_rate",
"Data and Pre-processing # # ================================================================== # print('=====> Preparing data...') # Multi-cuda if",
"= torch.cat([f_proj.unsqueeze(1), f1_proj.unsqueeze(1), f2_proj.unsqueeze(1), f_high_proj.unsqueeze(1)], dim=1) loss_contrast = criterion(features) loss_ce = 0 for",
"len(train_loader), optimizer) # attack contrast optimizer.zero_grad() x1, x2, x_cl, x_ce, x_HFC = net(image_t1,",
"model(x_ce, bn_name='pgd_ce', contrast=True, CF=True, return_logits=True, nonlinear=False) f1_proj, f1_pred = model(x1, bn_name='normal', contrast=True) f2_proj,",
"features = torch.cat([f_proj.unsqueeze(1), f1_proj.unsqueeze(1), f2_proj.unsqueeze(1), f_high_proj.unsqueeze(1)], dim=1) loss_contrast = criterion(features) loss_ce = 0",
"= num_classes_list[i] key_train = 'pseudo_train_{}'.format(class_num) label_pseudo_train = feat_label_dict[key_train] label_pseudo_train_list.append(label_pseudo_train) train_dataset = CIFAR10IndexPseudoLabelEnsemble(root='data', transform=transform_train,",
"= 0 for label_idx in range(5): tgt = targets[label_idx].long() lgt = logits_ce[label_idx] ce_loss",
"2 else: args.warmup_to = args.learning_rate start_epoch = 0 # start from epoch 0",
"train(epoch): print('\\nEpoch: %d' % epoch) net.train() train_loss = 0 correct = 0 total",
"checkpoint...') state = { 'model': model.state_dict(), 'epoch': epoch, 'rng_state': torch.get_rng_state() } save_dir =",
"low freq images') parser.add_argument('--ce_weight', type=float, default=0.2, help='cross entp weight') # contrastive related parser.add_argument('-t',",
"type=int, default=100, help='save epochs') parser.add_argument('--epsilon', type=float, default=8, help='The upper bound change of L-inf",
"f_high_pred = model(x_HFC, bn_name='normal', contrast=True) features = torch.cat( [f_proj.unsqueeze(1), f1_proj.unsqueeze(1), f2_proj.unsqueeze(1), f_high_proj.unsqueeze(1)], dim=1)",
"pseudoLabel_500=label_pseudo_train_list[4], download=True) # Data Loader train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True, num_workers=n_gpu*4) # ==================================================================",
"AttackPGD(nn.Module): def __init__(self, model, config): super(AttackPGD, self).__init__() self.model = model self.rand = config['random_start']",
"AttackPGD(model, config) # Loss and optimizer ce_criterion = nn.CrossEntropyLoss(ignore_index=-1) contrast_criterion = SupConLoss(temperature=args.nce_t) optimizer",
"from utils import progress_bar, TwoCropTransformAdv from losses import SupConLoss import tensorboard_logger as tb_logger",
"transform_train = transforms.Compose([ transforms.RandomResizedCrop(size=32, scale=(0.2, 1.)), transforms.RandomHorizontalFlip(), transforms.RandomApply([ transforms.ColorJitter(0.4, 0.4, 0.4, 0.1) ],",
"transforms.RandomGrayscale(p=0.2), transforms.ToTensor(), ]) train_transform_org = transforms.Compose([ transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), ]) transform_train =",
"Building model...') bn_names = ['normal', 'pgd', 'pgd_ce'] model = ResNet18(bn_names=bn_names) model = model.cuda()",
"= logits_ce[label_idx] ce_loss += ce_criterion(lgt, tgt) / 5. loss = contrast_loss + ce_loss",
"r=args.radius) x_HFC = images_org_high.clone().detach() if self.rand: x_cl = x_cl + torch.zeros_like(x1).uniform_(-self.epsilon, self.epsilon) x_ce",
"print('single gpu version is not supported, please use multiple GPUs!') raise NotImplementedError net",
"CF=True, return_logits=True, nonlinear=False) f1_proj, f1_pred = model(x1, bn_name='normal', contrast=True) f2_proj, f2_pred = model(x2,",
"= image_t2.cuda(non_blocking=True) image_org = image_org.cuda(non_blocking=True) warmup_learning_rate(args, epoch+1, batch_idx, len(train_loader), optimizer) # attack contrast",
"[2, 10, 50, 100, 500] dict_name = 'data/{}_pseudo_labels.pkl'.format(args.cname) f = open(dict_name, 'rb') #",
"TwoCropTransformAdv(transform_train, train_transform_org) transform_test = transforms.Compose([ transforms.ToTensor(), ]) label_pseudo_train_list = [] num_classes_list = [2,",
"= TwoCropTransformAdv(transform_train, train_transform_org) transform_test = transforms.Compose([ transforms.ToTensor(), ]) label_pseudo_train_list = [] num_classes_list =",
"lgt = logits_ce[label_idx] ce_loss += ce_criterion(lgt, tgt) / 5. loss = contrast_loss +",
"image_t2, image_org, targets, contrast_criterion) f_proj, f_pred = model(x_cl, bn_name='pgd', contrast=True) fce_proj, fce_pred, logits_ce",
"bn_name='normal', contrast=True) f_high_proj, f_high_pred = self.model(x_HFC, bn_name='normal', contrast=True) features = torch.cat([f_proj.unsqueeze(1), f1_proj.unsqueeze(1), f2_proj.unsqueeze(1),",
"parser.add_argument('--name', type=str, default='advcl_cifar10', help='name of the run') parser.add_argument('--cname', type=str, default='imagenet_clPretrain', help='') parser.add_argument('--batch-size', type=int,",
"foo1.py is feat_label_dict = pickle.load(f) # dump data to f f.close() for i",
"self.model(x2, bn_name='normal', contrast=True) f_high_proj, f_high_pred = self.model(x_HFC, bn_name='normal', contrast=True) features = torch.cat([f_proj.unsqueeze(1), f1_proj.unsqueeze(1),",
"logname = ('logger/pretrain_{}'.format(args.name)) logger = tb_logger.Logger(logdir=logname, flush_secs=2) if torch.cuda.device_count() > 1: print(\"=====> Let's",
"model = ResNet18(bn_names=bn_names) model = model.cuda() # tb_logger if not os.path.exists('logger'): os.makedirs('logger') logname",
"utils import adjust_learning_rate, warmup_learning_rate import apex # ================================================================== # # Inputs and Pre-definition",
"def __init__(self, model, config): super(AttackPGD, self).__init__() self.model = model self.rand = config['random_start'] self.step_size",
"= self.model(x_ce, bn_name='pgd_ce', contrast=True, CF=True, return_logits=True, nonlinear=False) f1_proj, f1_pred = self.model(x1, bn_name='normal', contrast=True)",
"(%d/%d)' % (train_loss/(batch_idx+1), correct, total)) return train_loss/batch_idx, 0. # ================================================================== # # Checkpoint",
"} save_dir = './checkpoint/{}'.format(args.name) if not os.path.isdir(save_dir): os.makedirs(save_dir) torch.save(state, '{}/epoch_{}.ckpt'.format(save_dir, epoch)) # ==================================================================",
"else 'cpu') args.name = 'AdvCL_Cifar10' config = { 'epsilon': args.epsilon / 255., 'num_steps':",
"from __future__ import print_function import argparse import numpy as np import os, csv",
"* args.ce_weight grad_x_cl, grad_x_ce = torch.autograd.grad(loss, [x_cl, x_ce]) x_cl = x_cl.detach() + self.step_size",
"x_ce]) x_cl = x_cl.detach() + self.step_size * torch.sign(grad_x_cl.detach()) x_cl = torch.min(torch.max(x_cl, images_org -",
"parser.add_argument('--dataset', type=str, default='cifar10', help='dataset') parser.add_argument('--cosine', action='store_true', help='using cosine annealing') parser.add_argument('--warm', action='store_true', help='warm-up for",
"x_cl, x_ce, x_HFC = net(image_t1, image_t2, image_org, targets, contrast_criterion) f_proj, f_pred = model(x_cl,",
"start from epoch 0 or last checkpoint epoch # Device configuration device =",
"# ================================================================== # # Train and Test # # ================================================================== # def train(epoch):",
"self.rand: x_cl = x_cl + torch.zeros_like(x1).uniform_(-self.epsilon, self.epsilon) x_ce = x_ce + torch.zeros_like(x1).uniform_(-self.epsilon, self.epsilon)",
"criterion(features) loss_ce = 0 for label_idx in range(5): tgt = targets[label_idx].long() lgt =",
"tgt = targets[label_idx].long() lgt = logits_ce[label_idx] loss_ce += F.cross_entropy(lgt, tgt, size_average=False, ignore_index=-1) /",
"= [] num_classes_list = [2, 10, 50, 100, 500] dict_name = 'data/{}_pseudo_labels.pkl'.format(args.cname) f",
"'data/{}_pseudo_labels.pkl'.format(args.cname) f = open(dict_name, 'rb') # Pickle file is newly created where foo1.py",
"x_HFC = images_org_high.clone().detach() if self.rand: x_cl = x_cl + torch.zeros_like(x1).uniform_(-self.epsilon, self.epsilon) x_ce =",
"math.cos(math.pi * args.warm_epochs / args.epochs)) / 2 else: args.warmup_to = args.learning_rate start_epoch =",
"n_gpu = torch.cuda.device_count() batch_size = args.batch_size transform_train = transforms.Compose([ transforms.RandomResizedCrop(size=32, scale=(0.2, 1.)), transforms.RandomHorizontalFlip(),",
"args.name = 'AdvCL_Cifar10' config = { 'epsilon': args.epsilon / 255., 'num_steps': args.iter, 'step_size':",
"= inputs image_t1 = image_t1.cuda(non_blocking=True) image_t2 = image_t2.cuda(non_blocking=True) image_org = image_org.cuda(non_blocking=True) warmup_learning_rate(args, epoch+1,",
"# # Run the model # # ================================================================== # np.random.seed(args.seed) random.seed(args.seed) torch.manual_seed(args.seed) torch.cuda.manual_seed_all(args.seed)",
"# Loss and optimizer ce_criterion = nn.CrossEntropyLoss(ignore_index=-1) contrast_criterion = SupConLoss(temperature=args.nce_t) optimizer = torch.optim.SGD(net.parameters(),",
"ignore_index=-1) / 5. loss = loss_contrast + loss_ce * args.ce_weight grad_x_cl, grad_x_ce =",
"nn import torch.nn.functional as F import torchvision.transforms as transforms import torch.utils.data as Data",
"device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') args.name = 'AdvCL_Cifar10' config = {",
"# optimizer = torch.optim.Adam(net.parameters(), lr=args.lr) # ================================================================== # # Train and Test #",
"image_t1.cuda(non_blocking=True) image_t2 = image_t2.cuda(non_blocking=True) image_org = image_org.cuda(non_blocking=True) warmup_learning_rate(args, epoch+1, batch_idx, len(train_loader), optimizer) #",
"targets, ind) in enumerate(train_loader): tt = [] for tt_ in targets: tt.append(tt_.to(device).long()) targets",
"'cpu') args.name = 'AdvCL_Cifar10' config = { 'epsilon': args.epsilon / 255., 'num_steps': args.iter,",
"[] for tt_ in targets: tt.append(tt_.to(device).long()) targets = tt image_t1, image_t2, image_org =",
"nonlinear=False) f1_proj, f1_pred = model(x1, bn_name='normal', contrast=True) f2_proj, f2_pred = model(x2, bn_name='normal', contrast=True)",
"from epoch 0 or last checkpoint epoch # Device configuration device = torch.device('cuda'",
"x2, x_cl, x_ce, x_HFC print('=====> Building model...') bn_names = ['normal', 'pgd', 'pgd_ce'] model",
"> 256: args.warm = True if args.warm: args.warmup_from = 0.01 args.warm_epochs = 10",
"apex # ================================================================== # # Inputs and Pre-definition # # ================================================================== # #",
"decay lr, can be a list') parser.add_argument('--lr_decay_rate', type=float, default=0.1, help='decay rate for learning",
"args = parser.parse_args() args.epochs = args.epoch args.decay = args.weight_decay args.cosine = True import",
"torchvision.transforms as transforms import torch.utils.data as Data import torch.backends.cudnn as cudnn from utils",
"tb_logger.Logger(logdir=logname, flush_secs=2) if torch.cuda.device_count() > 1: print(\"=====> Let's use\", torch.cuda.device_count(), \"GPUs!\") model =",
"torch.zeros_like(x1).uniform_(-self.epsilon, self.epsilon) for i in range(self.num_steps): x_cl.requires_grad_() x_ce.requires_grad_() with torch.enable_grad(): f_proj, f_pred =",
"= self.model(x_cl, bn_name='pgd', contrast=True) fce_proj, fce_pred, logits_ce = self.model(x_ce, bn_name='pgd_ce', contrast=True, CF=True, return_logits=True,",
"tb_logger if not os.path.exists('logger'): os.makedirs('logger') logname = ('logger/pretrain_{}'.format(args.name)) logger = tb_logger.Logger(logdir=logname, flush_secs=2) if",
"help='batch size') parser.add_argument('--epoch', type=int, default=1000, help='total epochs') parser.add_argument('--save-epoch', type=int, default=100, help='save epochs') parser.add_argument('--epsilon',",
"Test # # ================================================================== # def train(epoch): print('\\nEpoch: %d' % epoch) net.train() train_loss",
"= config['num_steps'] assert config['loss_func'] == 'xent', 'Plz use xent for loss function.' def",
"import torch.nn as nn import torch.nn.functional as F import torchvision.transforms as transforms import",
"# ================================================================== # def train(epoch): print('\\nEpoch: %d' % epoch) net.train() train_loss = 0",
"torch.save(state, '{}/epoch_{}.ckpt'.format(save_dir, epoch)) # ================================================================== # # Run the model # # ==================================================================",
"cosine annealing') parser.add_argument('--warm', action='store_true', help='warm-up for large batch training') parser.add_argument('--learning_rate', type=float, default=0.5, help='learning",
"from utils import adjust_learning_rate, warmup_learning_rate import apex # ================================================================== # # Inputs and",
"(inputs, _, targets, ind) in enumerate(train_loader): tt = [] for tt_ in targets:",
"in range(5): tgt = targets[label_idx].long() lgt = logits_ce[label_idx] ce_loss += ce_criterion(lgt, tgt) /",
"config = { 'epsilon': args.epsilon / 255., 'num_steps': args.iter, 'step_size': 2.0 / 255,",
"torch.enable_grad(): f_proj, f_pred = self.model(x_cl, bn_name='pgd', contrast=True) fce_proj, fce_pred, logits_ce = self.model(x_ce, bn_name='pgd_ce',",
"================================================================== # # Run the model # # ================================================================== # np.random.seed(args.seed) random.seed(args.seed) torch.manual_seed(args.seed)",
"# print('=====> Preparing data...') # Multi-cuda if torch.cuda.is_available(): n_gpu = torch.cuda.device_count() batch_size =",
"= x_ce + torch.zeros_like(x1).uniform_(-self.epsilon, self.epsilon) for i in range(self.num_steps): x_cl.requires_grad_() x_ce.requires_grad_() with torch.enable_grad():",
"image_t1 = image_t1.cuda(non_blocking=True) image_t2 = image_t2.cuda(non_blocking=True) image_org = image_org.cuda(non_blocking=True) warmup_learning_rate(args, epoch+1, batch_idx, len(train_loader),",
"= { 'model': model.state_dict(), 'epoch': epoch, 'rng_state': torch.get_rng_state() } save_dir = './checkpoint/{}'.format(args.name) if",
"config) # Loss and optimizer ce_criterion = nn.CrossEntropyLoss(ignore_index=-1) contrast_criterion = SupConLoss(temperature=args.nce_t) optimizer =",
"num_classes_list[i] key_train = 'pseudo_train_{}'.format(class_num) label_pseudo_train = feat_label_dict[key_train] label_pseudo_train_list.append(label_pseudo_train) train_dataset = CIFAR10IndexPseudoLabelEnsemble(root='data', transform=transform_train, pseudoLabel_002=label_pseudo_train_list[0],",
"train(epoch) logger.log_value('train_loss', train_loss, epoch) logger.log_value('learning_rate', optimizer.param_groups[0]['lr'], epoch) if epoch % args.save_epoch == 0:",
"= self.model(x2, bn_name='normal', contrast=True) f_high_proj, f_high_pred = self.model(x_HFC, bn_name='normal', contrast=True) features = torch.cat([f_proj.unsqueeze(1),",
"= model(x2, bn_name='normal', contrast=True) f_high_proj, f_high_pred = model(x_HFC, bn_name='normal', contrast=True) features = torch.cat(",
"self.epsilon) for i in range(self.num_steps): x_cl.requires_grad_() x_ce.requires_grad_() with torch.enable_grad(): f_proj, f_pred = self.model(x_cl,",
"loss function.' def forward(self, images_t1, images_t2, images_org, targets, criterion): x1 = images_t1.clone().detach() x2",
"from fr_util import generate_high from utils import adjust_learning_rate, warmup_learning_rate import apex # ==================================================================",
"Optimizer # # ================================================================== # # PGD attack model class AttackPGD(nn.Module): def __init__(self,",
"args.learning_rate * (args.lr_decay_rate ** 3) args.warmup_to = eta_min + (args.learning_rate - eta_min) *",
"# Data and Pre-processing # # ================================================================== # print('=====> Preparing data...') # Multi-cuda",
"ResNet18(bn_names=bn_names) model = model.cuda() # tb_logger if not os.path.exists('logger'): os.makedirs('logger') logname = ('logger/pretrain_{}'.format(args.name))",
"enumerate(train_loader): tt = [] for tt_ in targets: tt.append(tt_.to(device).long()) targets = tt image_t1,",
"pseudoLabel_002=label_pseudo_train_list[0], pseudoLabel_010=label_pseudo_train_list[1], pseudoLabel_050=label_pseudo_train_list[2], pseudoLabel_100=label_pseudo_train_list[3], pseudoLabel_500=label_pseudo_train_list[4], download=True) # Data Loader train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size,",
"in enumerate(train_loader): tt = [] for tt_ in targets: tt.append(tt_.to(device).long()) targets = tt",
"type=str, default='advcl_cifar10', help='name of the run') parser.add_argument('--cname', type=str, default='imagenet_clPretrain', help='') parser.add_argument('--batch-size', type=int, default=512,",
"bn_names = ['normal', 'pgd', 'pgd_ce'] model = ResNet18(bn_names=bn_names) model = model.cuda() # tb_logger",
"apex.parallel.convert_syncbn_model(model) model = nn.DataParallel(model) model = model.cuda() cudnn.benchmark = True else: print('single gpu",
"%d' % epoch) net.train() train_loss = 0 correct = 0 total = 0",
"parser.add_argument('-t', '--nce_t', default=0.5, type=float, help='temperature') parser.add_argument('--seed', default=0, type=float, help='random seed') parser.add_argument('--dataset', type=str, default='cifar10',",
"rate') parser.add_argument('--lr_decay_epochs', type=str, default='700,800,900', help='where to decay lr, can be a list') parser.add_argument('--lr_decay_rate',",
"torch.cuda.is_available(): n_gpu = torch.cuda.device_count() batch_size = args.batch_size transform_train = transforms.Compose([ transforms.RandomResizedCrop(size=32, scale=(0.2, 1.)),",
"torch.utils.data as Data import torch.backends.cudnn as cudnn from utils import progress_bar, TwoCropTransformAdv from",
"x_ce.requires_grad_() with torch.enable_grad(): f_proj, f_pred = self.model(x_cl, bn_name='pgd', contrast=True) fce_proj, fce_pred, logits_ce =",
"self.step_size * torch.sign(grad_x_cl.detach()) x_cl = torch.min(torch.max(x_cl, images_org - self.epsilon), images_org + self.epsilon) x_cl",
"f2_pred = model(x2, bn_name='normal', contrast=True) f_high_proj, f_high_pred = model(x_HFC, bn_name='normal', contrast=True) features =",
"'epoch': epoch, 'rng_state': torch.get_rng_state() } save_dir = './checkpoint/{}'.format(args.name) if not os.path.isdir(save_dir): os.makedirs(save_dir) torch.save(state,",
"images_t1, images_t2, images_org, targets, criterion): x1 = images_t1.clone().detach() x2 = images_t2.clone().detach() x_cl =",
"= True if args.warm: args.warmup_from = 0.01 args.warm_epochs = 10 if args.cosine: eta_min",
"losses import SupConLoss import tensorboard_logger as tb_logger from models.resnet_cifar_multibn_ensembleFC import resnet18 as ResNet18",
"else: print('single gpu version is not supported, please use multiple GPUs!') raise NotImplementedError",
"nn.CrossEntropyLoss(ignore_index=-1) contrast_criterion = SupConLoss(temperature=args.nce_t) optimizer = torch.optim.SGD(net.parameters(), lr=args.learning_rate, momentum=0.9, weight_decay=args.decay) # optimizer =",
"as F import torchvision.transforms as transforms import torch.utils.data as Data import torch.backends.cudnn as",
"= 0.01 args.warm_epochs = 10 if args.cosine: eta_min = args.learning_rate * (args.lr_decay_rate **",
"0.1) ], p=0.8), transforms.RandomGrayscale(p=0.2), transforms.ToTensor(), ]) train_transform_org = transforms.Compose([ transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(),",
"dict_name = 'data/{}_pseudo_labels.pkl'.format(args.cname) f = open(dict_name, 'rb') # Pickle file is newly created",
"image_t2 = image_t2.cuda(non_blocking=True) image_org = image_org.cuda(non_blocking=True) warmup_learning_rate(args, epoch+1, batch_idx, len(train_loader), optimizer) # attack",
"import apex # ================================================================== # # Inputs and Pre-definition # # ================================================================== #",
"args.warm = True if args.warm: args.warmup_from = 0.01 args.warm_epochs = 10 if args.cosine:",
"multiple GPUs!') raise NotImplementedError net = AttackPGD(model, config) # Loss and optimizer ce_criterion",
"for label_idx in range(5): tgt = targets[label_idx].long() lgt = logits_ce[label_idx] ce_loss += ce_criterion(lgt,",
"# # Checkpoint # # ================================================================== # # Save checkpoint def checkpoint(epoch): print('=====>",
"help='radius of low freq images') parser.add_argument('--ce_weight', type=float, default=0.2, help='cross entp weight') # contrastive",
"image_org.cuda(non_blocking=True) warmup_learning_rate(args, epoch+1, batch_idx, len(train_loader), optimizer) # attack contrast optimizer.zero_grad() x1, x2, x_cl,",
"parser.add_argument('--batch-size', type=int, default=512, help='batch size') parser.add_argument('--epoch', type=int, default=1000, help='total epochs') parser.add_argument('--save-epoch', type=int, default=100,",
"model...') bn_names = ['normal', 'pgd', 'pgd_ce'] model = ResNet18(bn_names=bn_names) model = model.cuda() #",
"('logger/pretrain_{}'.format(args.name)) logger = tb_logger.Logger(logdir=logname, flush_secs=2) if torch.cuda.device_count() > 1: print(\"=====> Let's use\", torch.cuda.device_count(),",
"parser.add_argument('--lr_decay_rate', type=float, default=0.1, help='decay rate for learning rate') parser.add_argument('--weight_decay', type=float, default=1e-4, help='weight decay')",
"/ 2 else: args.warmup_to = args.learning_rate start_epoch = 0 # start from epoch",
"supported, please use multiple GPUs!') raise NotImplementedError net = AttackPGD(model, config) # Loss",
"'xent', 'Plz use xent for loss function.' def forward(self, images_t1, images_t2, images_org, targets,",
"bn_name='normal', contrast=True) f2_proj, f2_pred = model(x2, bn_name='normal', contrast=True) f_high_proj, f_high_pred = model(x_HFC, bn_name='normal',",
"self).__init__() self.model = model self.rand = config['random_start'] self.step_size = config['step_size'] self.epsilon = config['epsilon']",
"# ================================================================== # np.random.seed(args.seed) random.seed(args.seed) torch.manual_seed(args.seed) torch.cuda.manual_seed_all(args.seed) for epoch in range(start_epoch, args.epoch+2): adjust_learning_rate(args,",
"= [2, 10, 50, 100, 500] dict_name = 'data/{}_pseudo_labels.pkl'.format(args.cname) f = open(dict_name, 'rb')",
"'rb') # Pickle file is newly created where foo1.py is feat_label_dict = pickle.load(f)",
"targets[0].size(0) progress_bar(batch_idx, len(train_loader), 'Loss: %.3f (%d/%d)' % (train_loss/(batch_idx+1), correct, total)) return train_loss/batch_idx, 0.",
"= 'AdvCL_Cifar10' config = { 'epsilon': args.epsilon / 255., 'num_steps': args.iter, 'step_size': 2.0",
"= True import math if args.batch_size > 256: args.warm = True if args.warm:",
"f.close() for i in range(5): class_num = num_classes_list[i] key_train = 'pseudo_train_{}'.format(class_num) label_pseudo_train =",
"(args.lr_decay_rate ** 3) args.warmup_to = eta_min + (args.learning_rate - eta_min) * ( 1",
"x_ce, x_HFC = net(image_t1, image_t2, image_org, targets, contrast_criterion) f_proj, f_pred = model(x_cl, bn_name='pgd',",
"help='save epochs') parser.add_argument('--epsilon', type=float, default=8, help='The upper bound change of L-inf norm on",
"ind) in enumerate(train_loader): tt = [] for tt_ in targets: tt.append(tt_.to(device).long()) targets =",
"f_high_proj.unsqueeze(1)], dim=1) contrast_loss = contrast_criterion(features) ce_loss = 0 for label_idx in range(5): tgt",
"]) train_transform_org = transforms.Compose([ transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), ]) transform_train = TwoCropTransformAdv(transform_train, train_transform_org)",
"args.decay = args.weight_decay args.cosine = True import math if args.batch_size > 256: args.warm",
"= open(dict_name, 'rb') # Pickle file is newly created where foo1.py is feat_label_dict",
"raise NotImplementedError net = AttackPGD(model, config) # Loss and optimizer ce_criterion = nn.CrossEntropyLoss(ignore_index=-1)",
"args.ce_weight loss.backward() optimizer.step() train_loss += loss.item() total += targets[0].size(0) progress_bar(batch_idx, len(train_loader), 'Loss: %.3f",
"bound change of L-inf norm on input pixels') parser.add_argument('--iter', type=int, default=5, help='The number",
"with torch.enable_grad(): f_proj, f_pred = self.model(x_cl, bn_name='pgd', contrast=True) fce_proj, fce_pred, logits_ce = self.model(x_ce,",
"generate_high(x_cl.clone(), r=args.radius) x_HFC = images_org_high.clone().detach() if self.rand: x_cl = x_cl + torch.zeros_like(x1).uniform_(-self.epsilon, self.epsilon)",
"help='weight decay') parser.add_argument('--momentum', type=float, default=0.9, help='momentum') args = parser.parse_args() args.epochs = args.epoch args.decay",
"help='using cosine annealing') parser.add_argument('--warm', action='store_true', help='warm-up for large batch training') parser.add_argument('--learning_rate', type=float, default=0.5,",
"train_transform_org = transforms.Compose([ transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), ]) transform_train = TwoCropTransformAdv(transform_train, train_transform_org) transform_test",
"input pixels') parser.add_argument('--iter', type=int, default=5, help='The number of iterations for iterative attacks') parser.add_argument('--radius',",
"torch.clamp(x_ce, 0, 1) return x1, x2, x_cl, x_ce, x_HFC print('=====> Building model...') bn_names",
"for learning rate') parser.add_argument('--weight_decay', type=float, default=1e-4, help='weight decay') parser.add_argument('--momentum', type=float, default=0.9, help='momentum') args",
"transforms.RandomApply([ transforms.ColorJitter(0.4, 0.4, 0.4, 0.1) ], p=0.8), transforms.RandomGrayscale(p=0.2), transforms.ToTensor(), ]) train_transform_org = transforms.Compose([",
"config['random_start'] self.step_size = config['step_size'] self.epsilon = config['epsilon'] self.num_steps = config['num_steps'] assert config['loss_func'] ==",
"weight_decay=args.decay) # optimizer = torch.optim.Adam(net.parameters(), lr=args.lr) # ================================================================== # # Train and Test",
"progress_bar(batch_idx, len(train_loader), 'Loss: %.3f (%d/%d)' % (train_loss/(batch_idx+1), correct, total)) return train_loss/batch_idx, 0. #",
"logger.log_value('train_loss', train_loss, epoch) logger.log_value('learning_rate', optimizer.param_groups[0]['lr'], epoch) if epoch % args.save_epoch == 0: checkpoint(epoch)",
"loss_contrast + loss_ce * args.ce_weight grad_x_cl, grad_x_ce = torch.autograd.grad(loss, [x_cl, x_ce]) x_cl =",
"xent for loss function.' def forward(self, images_t1, images_t2, images_org, targets, criterion): x1 =",
"CIFAR10IndexPseudoLabelEnsemble(root='data', transform=transform_train, pseudoLabel_002=label_pseudo_train_list[0], pseudoLabel_010=label_pseudo_train_list[1], pseudoLabel_050=label_pseudo_train_list[2], pseudoLabel_100=label_pseudo_train_list[3], pseudoLabel_500=label_pseudo_train_list[4], download=True) # Data Loader train_loader =",
"3) args.warmup_to = eta_min + (args.learning_rate - eta_min) * ( 1 + math.cos(math.pi",
"total += targets[0].size(0) progress_bar(batch_idx, len(train_loader), 'Loss: %.3f (%d/%d)' % (train_loss/(batch_idx+1), correct, total)) return",
"transforms import torch.utils.data as Data import torch.backends.cudnn as cudnn from utils import progress_bar,",
"default=512, help='batch size') parser.add_argument('--epoch', type=int, default=1000, help='total epochs') parser.add_argument('--save-epoch', type=int, default=100, help='save epochs')",
"# # Train and Test # # ================================================================== # def train(epoch): print('\\nEpoch: %d'",
"contrast_criterion(features) ce_loss = 0 for label_idx in range(5): tgt = targets[label_idx].long() lgt =",
"= './checkpoint/{}'.format(args.name) if not os.path.isdir(save_dir): os.makedirs(save_dir) torch.save(state, '{}/epoch_{}.ckpt'.format(save_dir, epoch)) # ================================================================== # #",
"image_org = image_org.cuda(non_blocking=True) warmup_learning_rate(args, epoch+1, batch_idx, len(train_loader), optimizer) # attack contrast optimizer.zero_grad() x1,",
"'xent', } # ================================================================== # # Data and Pre-processing # # ================================================================== #",
"= 0 total = 0 for batch_idx, (inputs, _, targets, ind) in enumerate(train_loader):",
"= ('logger/pretrain_{}'.format(args.name)) logger = tb_logger.Logger(logdir=logname, flush_secs=2) if torch.cuda.device_count() > 1: print(\"=====> Let's use\",",
"args.warm_epochs = 10 if args.cosine: eta_min = args.learning_rate * (args.lr_decay_rate ** 3) args.warmup_to",
"checkpoint(epoch): print('=====> Saving checkpoint...') state = { 'model': model.state_dict(), 'epoch': epoch, 'rng_state': torch.get_rng_state()",
"================================================================== # # PGD attack model class AttackPGD(nn.Module): def __init__(self, model, config): super(AttackPGD,",
"bn_name='pgd', contrast=True) fce_proj, fce_pred, logits_ce = model(x_ce, bn_name='pgd_ce', contrast=True, CF=True, return_logits=True, nonlinear=False) f1_proj,",
"0 total = 0 for batch_idx, (inputs, _, targets, ind) in enumerate(train_loader): tt",
"return x1, x2, x_cl, x_ce, x_HFC print('=====> Building model...') bn_names = ['normal', 'pgd',",
"model = model.cuda() # tb_logger if not os.path.exists('logger'): os.makedirs('logger') logname = ('logger/pretrain_{}'.format(args.name)) logger",
"/ 5. loss = loss_contrast + loss_ce * args.ce_weight grad_x_cl, grad_x_ce = torch.autograd.grad(loss,",
"pickle import torch import torch.nn as nn import torch.nn.functional as F import torchvision.transforms",
"decay') parser.add_argument('--momentum', type=float, default=0.9, help='momentum') args = parser.parse_args() args.epochs = args.epoch args.decay =",
"config['loss_func'] == 'xent', 'Plz use xent for loss function.' def forward(self, images_t1, images_t2,",
"use xent for loss function.' def forward(self, images_t1, images_t2, images_org, targets, criterion): x1",
"dim=1) loss_contrast = criterion(features) loss_ce = 0 for label_idx in range(5): tgt =",
"0 or last checkpoint epoch # Device configuration device = torch.device('cuda' if torch.cuda.is_available()",
"tgt) / 5. loss = contrast_loss + ce_loss * args.ce_weight loss.backward() optimizer.step() train_loss",
"f1_proj.unsqueeze(1), f2_proj.unsqueeze(1), f_high_proj.unsqueeze(1)], dim=1) contrast_loss = contrast_criterion(features) ce_loss = 0 for label_idx in",
"to f f.close() for i in range(5): class_num = num_classes_list[i] key_train = 'pseudo_train_{}'.format(class_num)",
"'model': model.state_dict(), 'epoch': epoch, 'rng_state': torch.get_rng_state() } save_dir = './checkpoint/{}'.format(args.name) if not os.path.isdir(save_dir):",
"self.epsilon), images_org + self.epsilon) x_ce = torch.clamp(x_ce, 0, 1) return x1, x2, x_cl,",
"# Train and Test # # ================================================================== # def train(epoch): print('\\nEpoch: %d' %",
"fce_proj, fce_pred, logits_ce = model(x_ce, bn_name='pgd_ce', contrast=True, CF=True, return_logits=True, nonlinear=False) f1_proj, f1_pred =",
"= pickle.load(f) # dump data to f f.close() for i in range(5): class_num",
"= parser.parse_args() args.epochs = args.epoch args.decay = args.weight_decay args.cosine = True import math",
"# ================================================================== # # Data and Pre-processing # # ================================================================== # print('=====> Preparing",
"= torch.autograd.grad(loss, [x_cl, x_ce]) x_cl = x_cl.detach() + self.step_size * torch.sign(grad_x_cl.detach()) x_cl =",
"= 10 if args.cosine: eta_min = args.learning_rate * (args.lr_decay_rate ** 3) args.warmup_to =",
"# # Data and Pre-processing # # ================================================================== # print('=====> Preparing data...') #",
"= True else: print('single gpu version is not supported, please use multiple GPUs!')",
"================================================================== # def train(epoch): print('\\nEpoch: %d' % epoch) net.train() train_loss = 0 correct",
"0 for label_idx in range(5): tgt = targets[label_idx].long() lgt = logits_ce[label_idx] ce_loss +=",
"loss.backward() optimizer.step() train_loss += loss.item() total += targets[0].size(0) progress_bar(batch_idx, len(train_loader), 'Loss: %.3f (%d/%d)'",
"# Inputs and Pre-definition # # ================================================================== # # Arguments parser = argparse.ArgumentParser()",
"csv from dataset import CIFAR10IndexPseudoLabelEnsemble import pickle import torch import torch.nn as nn",
"os.makedirs(save_dir) torch.save(state, '{}/epoch_{}.ckpt'.format(save_dir, epoch)) # ================================================================== # # Run the model # #",
"random.seed(args.seed) torch.manual_seed(args.seed) torch.cuda.manual_seed_all(args.seed) for epoch in range(start_epoch, args.epoch+2): adjust_learning_rate(args, optimizer, epoch+1) train_loss, train_acc",
"# # ================================================================== # # PGD attack model class AttackPGD(nn.Module): def __init__(self, model,",
"epoch+1) train_loss, train_acc = train(epoch) logger.log_value('train_loss', train_loss, epoch) logger.log_value('learning_rate', optimizer.param_groups[0]['lr'], epoch) if epoch",
"open(dict_name, 'rb') # Pickle file is newly created where foo1.py is feat_label_dict =",
"if args.batch_size > 256: args.warm = True if args.warm: args.warmup_from = 0.01 args.warm_epochs",
"Save checkpoint def checkpoint(epoch): print('=====> Saving checkpoint...') state = { 'model': model.state_dict(), 'epoch':",
"targets[label_idx].long() lgt = logits_ce[label_idx] loss_ce += F.cross_entropy(lgt, tgt, size_average=False, ignore_index=-1) / 5. loss",
"train_loss/batch_idx, 0. # ================================================================== # # Checkpoint # # ================================================================== # # Save",
"x_cl, x_ce, x_HFC print('=====> Building model...') bn_names = ['normal', 'pgd', 'pgd_ce'] model =",
"= args.learning_rate * (args.lr_decay_rate ** 3) args.warmup_to = eta_min + (args.learning_rate - eta_min)",
"default='imagenet_clPretrain', help='') parser.add_argument('--batch-size', type=int, default=512, help='batch size') parser.add_argument('--epoch', type=int, default=1000, help='total epochs') parser.add_argument('--save-epoch',",
"0. # ================================================================== # # Checkpoint # # ================================================================== # # Save checkpoint",
"= image_t1.cuda(non_blocking=True) image_t2 = image_t2.cuda(non_blocking=True) image_org = image_org.cuda(non_blocking=True) warmup_learning_rate(args, epoch+1, batch_idx, len(train_loader), optimizer)",
"last checkpoint epoch # Device configuration device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')",
"Model, Loss and Optimizer # # ================================================================== # # PGD attack model class",
"parser.add_argument('--cosine', action='store_true', help='using cosine annealing') parser.add_argument('--warm', action='store_true', help='warm-up for large batch training') parser.add_argument('--learning_rate',",
"size_average=False, ignore_index=-1) / 5. loss = loss_contrast + loss_ce * args.ce_weight grad_x_cl, grad_x_ce",
"for large batch training') parser.add_argument('--learning_rate', type=float, default=0.5, help='learning rate') parser.add_argument('--lr_decay_epochs', type=str, default='700,800,900', help='where",
"transforms.Compose([ transforms.ToTensor(), ]) label_pseudo_train_list = [] num_classes_list = [2, 10, 50, 100, 500]",
"feat_label_dict[key_train] label_pseudo_train_list.append(label_pseudo_train) train_dataset = CIFAR10IndexPseudoLabelEnsemble(root='data', transform=transform_train, pseudoLabel_002=label_pseudo_train_list[0], pseudoLabel_010=label_pseudo_train_list[1], pseudoLabel_050=label_pseudo_train_list[2], pseudoLabel_100=label_pseudo_train_list[3], pseudoLabel_500=label_pseudo_train_list[4], download=True) #",
"x2, x_cl, x_ce, x_HFC = net(image_t1, image_t2, image_org, targets, contrast_criterion) f_proj, f_pred =",
"in range(start_epoch, args.epoch+2): adjust_learning_rate(args, optimizer, epoch+1) train_loss, train_acc = train(epoch) logger.log_value('train_loss', train_loss, epoch)",
"print(\"=====> Let's use\", torch.cuda.device_count(), \"GPUs!\") model = apex.parallel.convert_syncbn_model(model) model = nn.DataParallel(model) model =",
"L-inf norm on input pixels') parser.add_argument('--iter', type=int, default=5, help='The number of iterations for",
"f_high_pred = self.model(x_HFC, bn_name='normal', contrast=True) features = torch.cat([f_proj.unsqueeze(1), f1_proj.unsqueeze(1), f2_proj.unsqueeze(1), f_high_proj.unsqueeze(1)], dim=1) loss_contrast",
"x1, x2, x_cl, x_ce, x_HFC = net(image_t1, image_t2, image_org, targets, contrast_criterion) f_proj, f_pred",
"as Data import torch.backends.cudnn as cudnn from utils import progress_bar, TwoCropTransformAdv from losses",
"range(5): tgt = targets[label_idx].long() lgt = logits_ce[label_idx] loss_ce += F.cross_entropy(lgt, tgt, size_average=False, ignore_index=-1)",
"= args.batch_size transform_train = transforms.Compose([ transforms.RandomResizedCrop(size=32, scale=(0.2, 1.)), transforms.RandomHorizontalFlip(), transforms.RandomApply([ transforms.ColorJitter(0.4, 0.4, 0.4,",
"args.cosine: eta_min = args.learning_rate * (args.lr_decay_rate ** 3) args.warmup_to = eta_min + (args.learning_rate",
"x_ce.detach() + self.step_size * torch.sign(grad_x_ce.detach()) x_ce = torch.min(torch.max(x_ce, images_org - self.epsilon), images_org +",
"model(x_cl, bn_name='pgd', contrast=True) fce_proj, fce_pred, logits_ce = model(x_ce, bn_name='pgd_ce', contrast=True, CF=True, return_logits=True, nonlinear=False)",
"is feat_label_dict = pickle.load(f) # dump data to f f.close() for i in",
"================================================================== # # Arguments parser = argparse.ArgumentParser() parser.add_argument('--name', type=str, default='advcl_cifar10', help='name of the",
"torch.cuda.device_count() > 1: print(\"=====> Let's use\", torch.cuda.device_count(), \"GPUs!\") model = apex.parallel.convert_syncbn_model(model) model =",
"criterion): x1 = images_t1.clone().detach() x2 = images_t2.clone().detach() x_cl = images_org.clone().detach() x_ce = images_org.clone().detach()",
"+ loss_ce * args.ce_weight grad_x_cl, grad_x_ce = torch.autograd.grad(loss, [x_cl, x_ce]) x_cl = x_cl.detach()",
"loss_ce = 0 for label_idx in range(5): tgt = targets[label_idx].long() lgt = logits_ce[label_idx]",
"targets[label_idx].long() lgt = logits_ce[label_idx] ce_loss += ce_criterion(lgt, tgt) / 5. loss = contrast_loss",
"0.4, 0.4, 0.1) ], p=0.8), transforms.RandomGrayscale(p=0.2), transforms.ToTensor(), ]) train_transform_org = transforms.Compose([ transforms.RandomCrop(32, padding=4),",
"== 'xent', 'Plz use xent for loss function.' def forward(self, images_t1, images_t2, images_org,",
"grad_x_cl, grad_x_ce = torch.autograd.grad(loss, [x_cl, x_ce]) x_cl = x_cl.detach() + self.step_size * torch.sign(grad_x_cl.detach())",
"transform_train = TwoCropTransformAdv(transform_train, train_transform_org) transform_test = transforms.Compose([ transforms.ToTensor(), ]) label_pseudo_train_list = [] num_classes_list",
"0.4, 0.1) ], p=0.8), transforms.RandomGrayscale(p=0.2), transforms.ToTensor(), ]) train_transform_org = transforms.Compose([ transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(),",
"Loss and optimizer ce_criterion = nn.CrossEntropyLoss(ignore_index=-1) contrast_criterion = SupConLoss(temperature=args.nce_t) optimizer = torch.optim.SGD(net.parameters(), lr=args.learning_rate,",
"x_HFC = net(image_t1, image_t2, image_org, targets, contrast_criterion) f_proj, f_pred = model(x_cl, bn_name='pgd', contrast=True)",
"type=float, default=1e-4, help='weight decay') parser.add_argument('--momentum', type=float, default=0.9, help='momentum') args = parser.parse_args() args.epochs =",
"x_ce = x_ce + torch.zeros_like(x1).uniform_(-self.epsilon, self.epsilon) for i in range(self.num_steps): x_cl.requires_grad_() x_ce.requires_grad_() with",
"torch.cat( [f_proj.unsqueeze(1), f1_proj.unsqueeze(1), f2_proj.unsqueeze(1), f_high_proj.unsqueeze(1)], dim=1) contrast_loss = contrast_criterion(features) ce_loss = 0 for",
"ce_loss * args.ce_weight loss.backward() optimizer.step() train_loss += loss.item() total += targets[0].size(0) progress_bar(batch_idx, len(train_loader),",
"+= ce_criterion(lgt, tgt) / 5. loss = contrast_loss + ce_loss * args.ce_weight loss.backward()",
"= loss_contrast + loss_ce * args.ce_weight grad_x_cl, grad_x_ce = torch.autograd.grad(loss, [x_cl, x_ce]) x_cl",
"bn_name='normal', contrast=True) features = torch.cat([f_proj.unsqueeze(1), f1_proj.unsqueeze(1), f2_proj.unsqueeze(1), f_high_proj.unsqueeze(1)], dim=1) loss_contrast = criterion(features) loss_ce",
"import pickle import torch import torch.nn as nn import torch.nn.functional as F import",
"# Device configuration device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') args.name = 'AdvCL_Cifar10'",
"import SupConLoss import tensorboard_logger as tb_logger from models.resnet_cifar_multibn_ensembleFC import resnet18 as ResNet18 import",
"= torch.min(torch.max(x_cl, images_org - self.epsilon), images_org + self.epsilon) x_cl = torch.clamp(x_cl, 0, 1)",
"help='decay rate for learning rate') parser.add_argument('--weight_decay', type=float, default=1e-4, help='weight decay') parser.add_argument('--momentum', type=float, default=0.9,",
"type=float, default=0.5, help='learning rate') parser.add_argument('--lr_decay_epochs', type=str, default='700,800,900', help='where to decay lr, can be",
"contrast=True) features = torch.cat([f_proj.unsqueeze(1), f1_proj.unsqueeze(1), f2_proj.unsqueeze(1), f_high_proj.unsqueeze(1)], dim=1) loss_contrast = criterion(features) loss_ce =",
"+ torch.zeros_like(x1).uniform_(-self.epsilon, self.epsilon) for i in range(self.num_steps): x_cl.requires_grad_() x_ce.requires_grad_() with torch.enable_grad(): f_proj, f_pred",
"x_cl.requires_grad_() x_ce.requires_grad_() with torch.enable_grad(): f_proj, f_pred = self.model(x_cl, bn_name='pgd', contrast=True) fce_proj, fce_pred, logits_ce",
"logits_ce = self.model(x_ce, bn_name='pgd_ce', contrast=True, CF=True, return_logits=True, nonlinear=False) f1_proj, f1_pred = self.model(x1, bn_name='normal',",
"and Optimizer # # ================================================================== # # PGD attack model class AttackPGD(nn.Module): def",
"* torch.sign(grad_x_ce.detach()) x_ce = torch.min(torch.max(x_ce, images_org - self.epsilon), images_org + self.epsilon) x_ce =",
"ce_loss += ce_criterion(lgt, tgt) / 5. loss = contrast_loss + ce_loss * args.ce_weight",
"f_high_proj.unsqueeze(1)], dim=1) loss_contrast = criterion(features) loss_ce = 0 for label_idx in range(5): tgt",
"args.batch_size > 256: args.warm = True if args.warm: args.warmup_from = 0.01 args.warm_epochs =",
"print('=====> Preparing data...') # Multi-cuda if torch.cuda.is_available(): n_gpu = torch.cuda.device_count() batch_size = args.batch_size",
"rate') parser.add_argument('--weight_decay', type=float, default=1e-4, help='weight decay') parser.add_argument('--momentum', type=float, default=0.9, help='momentum') args = parser.parse_args()",
"contrast optimizer.zero_grad() x1, x2, x_cl, x_ce, x_HFC = net(image_t1, image_t2, image_org, targets, contrast_criterion)",
"'./checkpoint/{}'.format(args.name) if not os.path.isdir(save_dir): os.makedirs(save_dir) torch.save(state, '{}/epoch_{}.ckpt'.format(save_dir, epoch)) # ================================================================== # # Run",
"f1_proj, f1_pred = model(x1, bn_name='normal', contrast=True) f2_proj, f2_pred = model(x2, bn_name='normal', contrast=True) f_high_proj,",
"self.model = model self.rand = config['random_start'] self.step_size = config['step_size'] self.epsilon = config['epsilon'] self.num_steps",
"args.epoch args.decay = args.weight_decay args.cosine = True import math if args.batch_size > 256:",
"from models.resnet_cifar_multibn_ensembleFC import resnet18 as ResNet18 import random from fr_util import generate_high from",
"os, csv from dataset import CIFAR10IndexPseudoLabelEnsemble import pickle import torch import torch.nn as",
"training') parser.add_argument('--learning_rate', type=float, default=0.5, help='learning rate') parser.add_argument('--lr_decay_epochs', type=str, default='700,800,900', help='where to decay lr,",
"], p=0.8), transforms.RandomGrayscale(p=0.2), transforms.ToTensor(), ]) train_transform_org = transforms.Compose([ transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), ])",
"# Data Loader train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True, num_workers=n_gpu*4) # ================================================================== # #",
"a list') parser.add_argument('--lr_decay_rate', type=float, default=0.1, help='decay rate for learning rate') parser.add_argument('--weight_decay', type=float, default=1e-4,",
"x2 = images_t2.clone().detach() x_cl = images_org.clone().detach() x_ce = images_org.clone().detach() images_org_high = generate_high(x_cl.clone(), r=args.radius)",
"default=8, help='The upper bound change of L-inf norm on input pixels') parser.add_argument('--iter', type=int,",
"'step_size': 2.0 / 255, 'random_start': True, 'loss_func': 'xent', } # ================================================================== # #",
"images_org.clone().detach() images_org_high = generate_high(x_cl.clone(), r=args.radius) x_HFC = images_org_high.clone().detach() if self.rand: x_cl = x_cl",
"torch.cat([f_proj.unsqueeze(1), f1_proj.unsqueeze(1), f2_proj.unsqueeze(1), f_high_proj.unsqueeze(1)], dim=1) loss_contrast = criterion(features) loss_ce = 0 for label_idx",
"to decay lr, can be a list') parser.add_argument('--lr_decay_rate', type=float, default=0.1, help='decay rate for",
"Checkpoint # # ================================================================== # # Save checkpoint def checkpoint(epoch): print('=====> Saving checkpoint...')",
"eta_min + (args.learning_rate - eta_min) * ( 1 + math.cos(math.pi * args.warm_epochs /",
"parser.add_argument('--radius', type=int, default=8, help='radius of low freq images') parser.add_argument('--ce_weight', type=float, default=0.2, help='cross entp",
"epoch 0 or last checkpoint epoch # Device configuration device = torch.device('cuda' if",
"logits_ce[label_idx] loss_ce += F.cross_entropy(lgt, tgt, size_average=False, ignore_index=-1) / 5. loss = loss_contrast +",
"loss.item() total += targets[0].size(0) progress_bar(batch_idx, len(train_loader), 'Loss: %.3f (%d/%d)' % (train_loss/(batch_idx+1), correct, total))",
"x_cl = torch.clamp(x_cl, 0, 1) x_ce = x_ce.detach() + self.step_size * torch.sign(grad_x_ce.detach()) x_ce",
"parser.add_argument('--momentum', type=float, default=0.9, help='momentum') args = parser.parse_args() args.epochs = args.epoch args.decay = args.weight_decay",
"import argparse import numpy as np import os, csv from dataset import CIFAR10IndexPseudoLabelEnsemble",
"images_org + self.epsilon) x_ce = torch.clamp(x_ce, 0, 1) return x1, x2, x_cl, x_ce,",
"torch.min(torch.max(x_cl, images_org - self.epsilon), images_org + self.epsilon) x_cl = torch.clamp(x_cl, 0, 1) x_ce",
"contrast_criterion = SupConLoss(temperature=args.nce_t) optimizer = torch.optim.SGD(net.parameters(), lr=args.learning_rate, momentum=0.9, weight_decay=args.decay) # optimizer = torch.optim.Adam(net.parameters(),",
"net.train() train_loss = 0 correct = 0 total = 0 for batch_idx, (inputs,",
"utils import progress_bar, TwoCropTransformAdv from losses import SupConLoss import tensorboard_logger as tb_logger from",
"file is newly created where foo1.py is feat_label_dict = pickle.load(f) # dump data",
"shuffle=True, num_workers=n_gpu*4) # ================================================================== # # Model, Loss and Optimizer # # ==================================================================",
"True if args.warm: args.warmup_from = 0.01 args.warm_epochs = 10 if args.cosine: eta_min =",
"args.epochs = args.epoch args.decay = args.weight_decay args.cosine = True import math if args.batch_size",
"train_loss += loss.item() total += targets[0].size(0) progress_bar(batch_idx, len(train_loader), 'Loss: %.3f (%d/%d)' % (train_loss/(batch_idx+1),",
"import generate_high from utils import adjust_learning_rate, warmup_learning_rate import apex # ================================================================== # #",
"else: args.warmup_to = args.learning_rate start_epoch = 0 # start from epoch 0 or",
"parser.add_argument('--iter', type=int, default=5, help='The number of iterations for iterative attacks') parser.add_argument('--radius', type=int, default=8,",
"================================================================== # # Data and Pre-processing # # ================================================================== # print('=====> Preparing data...')",
"help='warm-up for large batch training') parser.add_argument('--learning_rate', type=float, default=0.5, help='learning rate') parser.add_argument('--lr_decay_epochs', type=str, default='700,800,900',",
"of iterations for iterative attacks') parser.add_argument('--radius', type=int, default=8, help='radius of low freq images')",
"loss = contrast_loss + ce_loss * args.ce_weight loss.backward() optimizer.step() train_loss += loss.item() total",
"transforms.Compose([ transforms.RandomResizedCrop(size=32, scale=(0.2, 1.)), transforms.RandomHorizontalFlip(), transforms.RandomApply([ transforms.ColorJitter(0.4, 0.4, 0.4, 0.1) ], p=0.8), transforms.RandomGrayscale(p=0.2),",
"= criterion(features) loss_ce = 0 for label_idx in range(5): tgt = targets[label_idx].long() lgt",
"= logits_ce[label_idx] loss_ce += F.cross_entropy(lgt, tgt, size_average=False, ignore_index=-1) / 5. loss = loss_contrast",
"please use multiple GPUs!') raise NotImplementedError net = AttackPGD(model, config) # Loss and",
"image_t2, image_org = inputs image_t1 = image_t1.cuda(non_blocking=True) image_t2 = image_t2.cuda(non_blocking=True) image_org = image_org.cuda(non_blocking=True)",
"help='total epochs') parser.add_argument('--save-epoch', type=int, default=100, help='save epochs') parser.add_argument('--epsilon', type=float, default=8, help='The upper bound",
"attacks') parser.add_argument('--radius', type=int, default=8, help='radius of low freq images') parser.add_argument('--ce_weight', type=float, default=0.2, help='cross",
"num_classes_list = [2, 10, 50, 100, 500] dict_name = 'data/{}_pseudo_labels.pkl'.format(args.cname) f = open(dict_name,",
"- self.epsilon), images_org + self.epsilon) x_cl = torch.clamp(x_cl, 0, 1) x_ce = x_ce.detach()",
"f_proj, f_pred = self.model(x_cl, bn_name='pgd', contrast=True) fce_proj, fce_pred, logits_ce = self.model(x_ce, bn_name='pgd_ce', contrast=True,",
"= model(x_cl, bn_name='pgd', contrast=True) fce_proj, fce_pred, logits_ce = model(x_ce, bn_name='pgd_ce', contrast=True, CF=True, return_logits=True,",
"resnet18 as ResNet18 import random from fr_util import generate_high from utils import adjust_learning_rate,",
"iterative attacks') parser.add_argument('--radius', type=int, default=8, help='radius of low freq images') parser.add_argument('--ce_weight', type=float, default=0.2,",
"logits_ce = model(x_ce, bn_name='pgd_ce', contrast=True, CF=True, return_logits=True, nonlinear=False) f1_proj, f1_pred = model(x1, bn_name='normal',",
"forward(self, images_t1, images_t2, images_org, targets, criterion): x1 = images_t1.clone().detach() x2 = images_t2.clone().detach() x_cl",
"transforms.ToTensor(), ]) label_pseudo_train_list = [] num_classes_list = [2, 10, 50, 100, 500] dict_name",
"_, targets, ind) in enumerate(train_loader): tt = [] for tt_ in targets: tt.append(tt_.to(device).long())",
"super(AttackPGD, self).__init__() self.model = model self.rand = config['random_start'] self.step_size = config['step_size'] self.epsilon =",
"parser.add_argument('--warm', action='store_true', help='warm-up for large batch training') parser.add_argument('--learning_rate', type=float, default=0.5, help='learning rate') parser.add_argument('--lr_decay_epochs',",
"correct = 0 total = 0 for batch_idx, (inputs, _, targets, ind) in",
"'rng_state': torch.get_rng_state() } save_dir = './checkpoint/{}'.format(args.name) if not os.path.isdir(save_dir): os.makedirs(save_dir) torch.save(state, '{}/epoch_{}.ckpt'.format(save_dir, epoch))",
"key_train = 'pseudo_train_{}'.format(class_num) label_pseudo_train = feat_label_dict[key_train] label_pseudo_train_list.append(label_pseudo_train) train_dataset = CIFAR10IndexPseudoLabelEnsemble(root='data', transform=transform_train, pseudoLabel_002=label_pseudo_train_list[0], pseudoLabel_010=label_pseudo_train_list[1],",
"= images_org.clone().detach() images_org_high = generate_high(x_cl.clone(), r=args.radius) x_HFC = images_org_high.clone().detach() if self.rand: x_cl =",
"default=100, help='save epochs') parser.add_argument('--epsilon', type=float, default=8, help='The upper bound change of L-inf norm",
"in range(5): class_num = num_classes_list[i] key_train = 'pseudo_train_{}'.format(class_num) label_pseudo_train = feat_label_dict[key_train] label_pseudo_train_list.append(label_pseudo_train) train_dataset",
"type=int, default=5, help='The number of iterations for iterative attacks') parser.add_argument('--radius', type=int, default=8, help='radius",
"'--nce_t', default=0.5, type=float, help='temperature') parser.add_argument('--seed', default=0, type=float, help='random seed') parser.add_argument('--dataset', type=str, default='cifar10', help='dataset')",
"os.makedirs('logger') logname = ('logger/pretrain_{}'.format(args.name)) logger = tb_logger.Logger(logdir=logname, flush_secs=2) if torch.cuda.device_count() > 1: print(\"=====>",
"net(image_t1, image_t2, image_org, targets, contrast_criterion) f_proj, f_pred = model(x_cl, bn_name='pgd', contrast=True) fce_proj, fce_pred,",
"# ================================================================== # # Model, Loss and Optimizer # # ================================================================== # #",
"total = 0 for batch_idx, (inputs, _, targets, ind) in enumerate(train_loader): tt =",
"f1_pred = model(x1, bn_name='normal', contrast=True) f2_proj, f2_pred = model(x2, bn_name='normal', contrast=True) f_high_proj, f_high_pred",
"= transforms.Compose([ transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), ]) transform_train = TwoCropTransformAdv(transform_train, train_transform_org) transform_test =",
"feat_label_dict = pickle.load(f) # dump data to f f.close() for i in range(5):",
"f = open(dict_name, 'rb') # Pickle file is newly created where foo1.py is",
"freq images') parser.add_argument('--ce_weight', type=float, default=0.2, help='cross entp weight') # contrastive related parser.add_argument('-t', '--nce_t',",
"# # Model, Loss and Optimizer # # ================================================================== # # PGD attack",
"if not os.path.exists('logger'): os.makedirs('logger') logname = ('logger/pretrain_{}'.format(args.name)) logger = tb_logger.Logger(logdir=logname, flush_secs=2) if torch.cuda.device_count()",
"run') parser.add_argument('--cname', type=str, default='imagenet_clPretrain', help='') parser.add_argument('--batch-size', type=int, default=512, help='batch size') parser.add_argument('--epoch', type=int, default=1000,",
"print_function import argparse import numpy as np import os, csv from dataset import",
"random from fr_util import generate_high from utils import adjust_learning_rate, warmup_learning_rate import apex #",
"be a list') parser.add_argument('--lr_decay_rate', type=float, default=0.1, help='decay rate for learning rate') parser.add_argument('--weight_decay', type=float,",
"NotImplementedError net = AttackPGD(model, config) # Loss and optimizer ce_criterion = nn.CrossEntropyLoss(ignore_index=-1) contrast_criterion",
"torch.manual_seed(args.seed) torch.cuda.manual_seed_all(args.seed) for epoch in range(start_epoch, args.epoch+2): adjust_learning_rate(args, optimizer, epoch+1) train_loss, train_acc =",
"x_ce = torch.min(torch.max(x_ce, images_org - self.epsilon), images_org + self.epsilon) x_ce = torch.clamp(x_ce, 0,",
"learning rate') parser.add_argument('--weight_decay', type=float, default=1e-4, help='weight decay') parser.add_argument('--momentum', type=float, default=0.9, help='momentum') args =",
"= { 'epsilon': args.epsilon / 255., 'num_steps': args.iter, 'step_size': 2.0 / 255, 'random_start':",
"fce_proj, fce_pred, logits_ce = self.model(x_ce, bn_name='pgd_ce', contrast=True, CF=True, return_logits=True, nonlinear=False) f1_proj, f1_pred =",
"batch_idx, (inputs, _, targets, ind) in enumerate(train_loader): tt = [] for tt_ in",
"type=float, help='random seed') parser.add_argument('--dataset', type=str, default='cifar10', help='dataset') parser.add_argument('--cosine', action='store_true', help='using cosine annealing') parser.add_argument('--warm',",
"help='learning rate') parser.add_argument('--lr_decay_epochs', type=str, default='700,800,900', help='where to decay lr, can be a list')",
"# Multi-cuda if torch.cuda.is_available(): n_gpu = torch.cuda.device_count() batch_size = args.batch_size transform_train = transforms.Compose([",
"not os.path.exists('logger'): os.makedirs('logger') logname = ('logger/pretrain_{}'.format(args.name)) logger = tb_logger.Logger(logdir=logname, flush_secs=2) if torch.cuda.device_count() >",
"# ================================================================== # print('=====> Preparing data...') # Multi-cuda if torch.cuda.is_available(): n_gpu = torch.cuda.device_count()",
"epoch # Device configuration device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') args.name =",
"1) return x1, x2, x_cl, x_ce, x_HFC print('=====> Building model...') bn_names = ['normal',",
"Loss and Optimizer # # ================================================================== # # PGD attack model class AttackPGD(nn.Module):",
"as cudnn from utils import progress_bar, TwoCropTransformAdv from losses import SupConLoss import tensorboard_logger",
"# contrastive related parser.add_argument('-t', '--nce_t', default=0.5, type=float, help='temperature') parser.add_argument('--seed', default=0, type=float, help='random seed')",
"self.epsilon) x_ce = torch.clamp(x_ce, 0, 1) return x1, x2, x_cl, x_ce, x_HFC print('=====>",
"self.num_steps = config['num_steps'] assert config['loss_func'] == 'xent', 'Plz use xent for loss function.'",
"torch.optim.Adam(net.parameters(), lr=args.lr) # ================================================================== # # Train and Test # # ================================================================== #",
"'random_start': True, 'loss_func': 'xent', } # ================================================================== # # Data and Pre-processing #",
"can be a list') parser.add_argument('--lr_decay_rate', type=float, default=0.1, help='decay rate for learning rate') parser.add_argument('--weight_decay',",
"targets, contrast_criterion) f_proj, f_pred = model(x_cl, bn_name='pgd', contrast=True) fce_proj, fce_pred, logits_ce = model(x_ce,",
"from dataset import CIFAR10IndexPseudoLabelEnsemble import pickle import torch import torch.nn as nn import",
"CIFAR10IndexPseudoLabelEnsemble import pickle import torch import torch.nn as nn import torch.nn.functional as F",
"default=0.5, help='learning rate') parser.add_argument('--lr_decay_epochs', type=str, default='700,800,900', help='where to decay lr, can be a",
"help='temperature') parser.add_argument('--seed', default=0, type=float, help='random seed') parser.add_argument('--dataset', type=str, default='cifar10', help='dataset') parser.add_argument('--cosine', action='store_true', help='using",
"= 0 for batch_idx, (inputs, _, targets, ind) in enumerate(train_loader): tt = []",
"range(start_epoch, args.epoch+2): adjust_learning_rate(args, optimizer, epoch+1) train_loss, train_acc = train(epoch) logger.log_value('train_loss', train_loss, epoch) logger.log_value('learning_rate',",
"i in range(5): class_num = num_classes_list[i] key_train = 'pseudo_train_{}'.format(class_num) label_pseudo_train = feat_label_dict[key_train] label_pseudo_train_list.append(label_pseudo_train)",
"transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), ]) transform_train = TwoCropTransformAdv(transform_train, train_transform_org) transform_test = transforms.Compose([ transforms.ToTensor(),",
"# tb_logger if not os.path.exists('logger'): os.makedirs('logger') logname = ('logger/pretrain_{}'.format(args.name)) logger = tb_logger.Logger(logdir=logname, flush_secs=2)",
"newly created where foo1.py is feat_label_dict = pickle.load(f) # dump data to f",
"contrast=True) fce_proj, fce_pred, logits_ce = model(x_ce, bn_name='pgd_ce', contrast=True, CF=True, return_logits=True, nonlinear=False) f1_proj, f1_pred",
"F.cross_entropy(lgt, tgt, size_average=False, ignore_index=-1) / 5. loss = loss_contrast + loss_ce * args.ce_weight",
"import os, csv from dataset import CIFAR10IndexPseudoLabelEnsemble import pickle import torch import torch.nn",
"args.warm: args.warmup_from = 0.01 args.warm_epochs = 10 if args.cosine: eta_min = args.learning_rate *",
"contrast=True, CF=True, return_logits=True, nonlinear=False) f1_proj, f1_pred = model(x1, bn_name='normal', contrast=True) f2_proj, f2_pred =",
"= train(epoch) logger.log_value('train_loss', train_loss, epoch) logger.log_value('learning_rate', optimizer.param_groups[0]['lr'], epoch) if epoch % args.save_epoch ==",
"SupConLoss(temperature=args.nce_t) optimizer = torch.optim.SGD(net.parameters(), lr=args.learning_rate, momentum=0.9, weight_decay=args.decay) # optimizer = torch.optim.Adam(net.parameters(), lr=args.lr) #",
"{ 'model': model.state_dict(), 'epoch': epoch, 'rng_state': torch.get_rng_state() } save_dir = './checkpoint/{}'.format(args.name) if not",
"pseudoLabel_010=label_pseudo_train_list[1], pseudoLabel_050=label_pseudo_train_list[2], pseudoLabel_100=label_pseudo_train_list[3], pseudoLabel_500=label_pseudo_train_list[4], download=True) # Data Loader train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True,",
"total)) return train_loss/batch_idx, 0. # ================================================================== # # Checkpoint # # ================================================================== #",
"self.model(x1, bn_name='normal', contrast=True) f2_proj, f2_pred = self.model(x2, bn_name='normal', contrast=True) f_high_proj, f_high_pred = self.model(x_HFC,",
"# Checkpoint # # ================================================================== # # Save checkpoint def checkpoint(epoch): print('=====> Saving",
"images_org.clone().detach() x_ce = images_org.clone().detach() images_org_high = generate_high(x_cl.clone(), r=args.radius) x_HFC = images_org_high.clone().detach() if self.rand:",
"not os.path.isdir(save_dir): os.makedirs(save_dir) torch.save(state, '{}/epoch_{}.ckpt'.format(save_dir, epoch)) # ================================================================== # # Run the model",
"config['epsilon'] self.num_steps = config['num_steps'] assert config['loss_func'] == 'xent', 'Plz use xent for loss",
"x_cl + torch.zeros_like(x1).uniform_(-self.epsilon, self.epsilon) x_ce = x_ce + torch.zeros_like(x1).uniform_(-self.epsilon, self.epsilon) for i in",
"torch.optim.SGD(net.parameters(), lr=args.learning_rate, momentum=0.9, weight_decay=args.decay) # optimizer = torch.optim.Adam(net.parameters(), lr=args.lr) # ================================================================== # #",
"'loss_func': 'xent', } # ================================================================== # # Data and Pre-processing # # ==================================================================",
"= torch.clamp(x_cl, 0, 1) x_ce = x_ce.detach() + self.step_size * torch.sign(grad_x_ce.detach()) x_ce =",
"image_org = inputs image_t1 = image_t1.cuda(non_blocking=True) image_t2 = image_t2.cuda(non_blocking=True) image_org = image_org.cuda(non_blocking=True) warmup_learning_rate(args,",
"logger = tb_logger.Logger(logdir=logname, flush_secs=2) if torch.cuda.device_count() > 1: print(\"=====> Let's use\", torch.cuda.device_count(), \"GPUs!\")",
"start_epoch = 0 # start from epoch 0 or last checkpoint epoch #",
"configuration device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') args.name = 'AdvCL_Cifar10' config =",
"# Run the model # # ================================================================== # np.random.seed(args.seed) random.seed(args.seed) torch.manual_seed(args.seed) torch.cuda.manual_seed_all(args.seed) for",
"0.01 args.warm_epochs = 10 if args.cosine: eta_min = args.learning_rate * (args.lr_decay_rate ** 3)",
"help='The number of iterations for iterative attacks') parser.add_argument('--radius', type=int, default=8, help='radius of low",
"tt_ in targets: tt.append(tt_.to(device).long()) targets = tt image_t1, image_t2, image_org = inputs image_t1",
"default=5, help='The number of iterations for iterative attacks') parser.add_argument('--radius', type=int, default=8, help='radius of",
"x1 = images_t1.clone().detach() x2 = images_t2.clone().detach() x_cl = images_org.clone().detach() x_ce = images_org.clone().detach() images_org_high",
"dataset import CIFAR10IndexPseudoLabelEnsemble import pickle import torch import torch.nn as nn import torch.nn.functional",
"np import os, csv from dataset import CIFAR10IndexPseudoLabelEnsemble import pickle import torch import",
"+ self.step_size * torch.sign(grad_x_ce.detach()) x_ce = torch.min(torch.max(x_ce, images_org - self.epsilon), images_org + self.epsilon)",
"image_org, targets, contrast_criterion) f_proj, f_pred = model(x_cl, bn_name='pgd', contrast=True) fce_proj, fce_pred, logits_ce =",
"* args.warm_epochs / args.epochs)) / 2 else: args.warmup_to = args.learning_rate start_epoch = 0",
"+ self.epsilon) x_ce = torch.clamp(x_ce, 0, 1) return x1, x2, x_cl, x_ce, x_HFC",
"256: args.warm = True if args.warm: args.warmup_from = 0.01 args.warm_epochs = 10 if",
"# Save checkpoint def checkpoint(epoch): print('=====> Saving checkpoint...') state = { 'model': model.state_dict(),",
"= self.model(x_HFC, bn_name='normal', contrast=True) features = torch.cat([f_proj.unsqueeze(1), f1_proj.unsqueeze(1), f2_proj.unsqueeze(1), f_high_proj.unsqueeze(1)], dim=1) loss_contrast =",
"'Loss: %.3f (%d/%d)' % (train_loss/(batch_idx+1), correct, total)) return train_loss/batch_idx, 0. # ================================================================== #",
"the model # # ================================================================== # np.random.seed(args.seed) random.seed(args.seed) torch.manual_seed(args.seed) torch.cuda.manual_seed_all(args.seed) for epoch in",
"if args.warm: args.warmup_from = 0.01 args.warm_epochs = 10 if args.cosine: eta_min = args.learning_rate",
"self.epsilon), images_org + self.epsilon) x_cl = torch.clamp(x_cl, 0, 1) x_ce = x_ce.detach() +",
"for label_idx in range(5): tgt = targets[label_idx].long() lgt = logits_ce[label_idx] loss_ce += F.cross_entropy(lgt,",
"TwoCropTransformAdv from losses import SupConLoss import tensorboard_logger as tb_logger from models.resnet_cifar_multibn_ensembleFC import resnet18",
"self.model(x_ce, bn_name='pgd_ce', contrast=True, CF=True, return_logits=True, nonlinear=False) f1_proj, f1_pred = self.model(x1, bn_name='normal', contrast=True) f2_proj,",
"* ( 1 + math.cos(math.pi * args.warm_epochs / args.epochs)) / 2 else: args.warmup_to",
"ce_criterion(lgt, tgt) / 5. loss = contrast_loss + ce_loss * args.ce_weight loss.backward() optimizer.step()",
"]) label_pseudo_train_list = [] num_classes_list = [2, 10, 50, 100, 500] dict_name =",
"for epoch in range(start_epoch, args.epoch+2): adjust_learning_rate(args, optimizer, epoch+1) train_loss, train_acc = train(epoch) logger.log_value('train_loss',",
"model.cuda() cudnn.benchmark = True else: print('single gpu version is not supported, please use",
"os.path.isdir(save_dir): os.makedirs(save_dir) torch.save(state, '{}/epoch_{}.ckpt'.format(save_dir, epoch)) # ================================================================== # # Run the model #",
"loss_ce += F.cross_entropy(lgt, tgt, size_average=False, ignore_index=-1) / 5. loss = loss_contrast + loss_ce",
"data...') # Multi-cuda if torch.cuda.is_available(): n_gpu = torch.cuda.device_count() batch_size = args.batch_size transform_train =",
"= torch.min(torch.max(x_ce, images_org - self.epsilon), images_org + self.epsilon) x_ce = torch.clamp(x_ce, 0, 1)",
"def checkpoint(epoch): print('=====> Saving checkpoint...') state = { 'model': model.state_dict(), 'epoch': epoch, 'rng_state':",
"transforms.Compose([ transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), ]) transform_train = TwoCropTransformAdv(transform_train, train_transform_org) transform_test = transforms.Compose([",
"'pgd_ce'] model = ResNet18(bn_names=bn_names) model = model.cuda() # tb_logger if not os.path.exists('logger'): os.makedirs('logger')",
"if torch.cuda.is_available(): n_gpu = torch.cuda.device_count() batch_size = args.batch_size transform_train = transforms.Compose([ transforms.RandomResizedCrop(size=32, scale=(0.2,",
"print('=====> Building model...') bn_names = ['normal', 'pgd', 'pgd_ce'] model = ResNet18(bn_names=bn_names) model =",
"inputs image_t1 = image_t1.cuda(non_blocking=True) image_t2 = image_t2.cuda(non_blocking=True) image_org = image_org.cuda(non_blocking=True) warmup_learning_rate(args, epoch+1, batch_idx,",
"x_ce + torch.zeros_like(x1).uniform_(-self.epsilon, self.epsilon) for i in range(self.num_steps): x_cl.requires_grad_() x_ce.requires_grad_() with torch.enable_grad(): f_proj,",
"ce_loss = 0 for label_idx in range(5): tgt = targets[label_idx].long() lgt = logits_ce[label_idx]",
"= contrast_loss + ce_loss * args.ce_weight loss.backward() optimizer.step() train_loss += loss.item() total +=",
"action='store_true', help='using cosine annealing') parser.add_argument('--warm', action='store_true', help='warm-up for large batch training') parser.add_argument('--learning_rate', type=float,",
"= 0 # start from epoch 0 or last checkpoint epoch # Device",
"================================================================== # print('=====> Preparing data...') # Multi-cuda if torch.cuda.is_available(): n_gpu = torch.cuda.device_count() batch_size",
"model(x_HFC, bn_name='normal', contrast=True) features = torch.cat( [f_proj.unsqueeze(1), f1_proj.unsqueeze(1), f2_proj.unsqueeze(1), f_high_proj.unsqueeze(1)], dim=1) contrast_loss =",
"parser.add_argument('--save-epoch', type=int, default=100, help='save epochs') parser.add_argument('--epsilon', type=float, default=8, help='The upper bound change of",
"** 3) args.warmup_to = eta_min + (args.learning_rate - eta_min) * ( 1 +",
"================================================================== # # Checkpoint # # ================================================================== # # Save checkpoint def checkpoint(epoch):",
"x_cl = images_org.clone().detach() x_ce = images_org.clone().detach() images_org_high = generate_high(x_cl.clone(), r=args.radius) x_HFC = images_org_high.clone().detach()",
"contrast_criterion) f_proj, f_pred = model(x_cl, bn_name='pgd', contrast=True) fce_proj, fce_pred, logits_ce = model(x_ce, bn_name='pgd_ce',",
"nn.DataParallel(model) model = model.cuda() cudnn.benchmark = True else: print('single gpu version is not",
"0, 1) return x1, x2, x_cl, x_ce, x_HFC print('=====> Building model...') bn_names =",
"0 correct = 0 total = 0 for batch_idx, (inputs, _, targets, ind)",
"import resnet18 as ResNet18 import random from fr_util import generate_high from utils import",
"class_num = num_classes_list[i] key_train = 'pseudo_train_{}'.format(class_num) label_pseudo_train = feat_label_dict[key_train] label_pseudo_train_list.append(label_pseudo_train) train_dataset = CIFAR10IndexPseudoLabelEnsemble(root='data',",
"Loader train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True, num_workers=n_gpu*4) # ================================================================== # # Model, Loss",
"range(self.num_steps): x_cl.requires_grad_() x_ce.requires_grad_() with torch.enable_grad(): f_proj, f_pred = self.model(x_cl, bn_name='pgd', contrast=True) fce_proj, fce_pred,",
"parser.add_argument('--lr_decay_epochs', type=str, default='700,800,900', help='where to decay lr, can be a list') parser.add_argument('--lr_decay_rate', type=float,",
"epoch in range(start_epoch, args.epoch+2): adjust_learning_rate(args, optimizer, epoch+1) train_loss, train_acc = train(epoch) logger.log_value('train_loss', train_loss,",
"default='cifar10', help='dataset') parser.add_argument('--cosine', action='store_true', help='using cosine annealing') parser.add_argument('--warm', action='store_true', help='warm-up for large batch",
"image_t2.cuda(non_blocking=True) image_org = image_org.cuda(non_blocking=True) warmup_learning_rate(args, epoch+1, batch_idx, len(train_loader), optimizer) # attack contrast optimizer.zero_grad()",
"torch.sign(grad_x_cl.detach()) x_cl = torch.min(torch.max(x_cl, images_org - self.epsilon), images_org + self.epsilon) x_cl = torch.clamp(x_cl,",
"= torch.optim.SGD(net.parameters(), lr=args.learning_rate, momentum=0.9, weight_decay=args.decay) # optimizer = torch.optim.Adam(net.parameters(), lr=args.lr) # ================================================================== #",
"tensorboard_logger as tb_logger from models.resnet_cifar_multibn_ensembleFC import resnet18 as ResNet18 import random from fr_util",
"return train_loss/batch_idx, 0. # ================================================================== # # Checkpoint # # ================================================================== # #",
"parser.add_argument('--weight_decay', type=float, default=1e-4, help='weight decay') parser.add_argument('--momentum', type=float, default=0.9, help='momentum') args = parser.parse_args() args.epochs",
"for batch_idx, (inputs, _, targets, ind) in enumerate(train_loader): tt = [] for tt_",
"args.epsilon / 255., 'num_steps': args.iter, 'step_size': 2.0 / 255, 'random_start': True, 'loss_func': 'xent',",
"= net(image_t1, image_t2, image_org, targets, contrast_criterion) f_proj, f_pred = model(x_cl, bn_name='pgd', contrast=True) fce_proj,",
"for loss function.' def forward(self, images_t1, images_t2, images_org, targets, criterion): x1 = images_t1.clone().detach()",
"f2_proj.unsqueeze(1), f_high_proj.unsqueeze(1)], dim=1) contrast_loss = contrast_criterion(features) ce_loss = 0 for label_idx in range(5):",
"self.step_size * torch.sign(grad_x_ce.detach()) x_ce = torch.min(torch.max(x_ce, images_org - self.epsilon), images_org + self.epsilon) x_ce",
"optimizer) # attack contrast optimizer.zero_grad() x1, x2, x_cl, x_ce, x_HFC = net(image_t1, image_t2,",
"self.model(x_cl, bn_name='pgd', contrast=True) fce_proj, fce_pred, logits_ce = self.model(x_ce, bn_name='pgd_ce', contrast=True, CF=True, return_logits=True, nonlinear=False)",
"bn_name='pgd_ce', contrast=True, CF=True, return_logits=True, nonlinear=False) f1_proj, f1_pred = model(x1, bn_name='normal', contrast=True) f2_proj, f2_pred",
"is newly created where foo1.py is feat_label_dict = pickle.load(f) # dump data to",
"x_cl = x_cl + torch.zeros_like(x1).uniform_(-self.epsilon, self.epsilon) x_ce = x_ce + torch.zeros_like(x1).uniform_(-self.epsilon, self.epsilon) for",
"download=True) # Data Loader train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True, num_workers=n_gpu*4) # ================================================================== #",
"default='700,800,900', help='where to decay lr, can be a list') parser.add_argument('--lr_decay_rate', type=float, default=0.1, help='decay",
"label_idx in range(5): tgt = targets[label_idx].long() lgt = logits_ce[label_idx] ce_loss += ce_criterion(lgt, tgt)",
"loss = loss_contrast + loss_ce * args.ce_weight grad_x_cl, grad_x_ce = torch.autograd.grad(loss, [x_cl, x_ce])",
"1: print(\"=====> Let's use\", torch.cuda.device_count(), \"GPUs!\") model = apex.parallel.convert_syncbn_model(model) model = nn.DataParallel(model) model",
"* (args.lr_decay_rate ** 3) args.warmup_to = eta_min + (args.learning_rate - eta_min) * (",
"os.path.exists('logger'): os.makedirs('logger') logname = ('logger/pretrain_{}'.format(args.name)) logger = tb_logger.Logger(logdir=logname, flush_secs=2) if torch.cuda.device_count() > 1:",
"type=float, help='temperature') parser.add_argument('--seed', default=0, type=float, help='random seed') parser.add_argument('--dataset', type=str, default='cifar10', help='dataset') parser.add_argument('--cosine', action='store_true',",
"pixels') parser.add_argument('--iter', type=int, default=5, help='The number of iterations for iterative attacks') parser.add_argument('--radius', type=int,",
"self.model(x_HFC, bn_name='normal', contrast=True) features = torch.cat([f_proj.unsqueeze(1), f1_proj.unsqueeze(1), f2_proj.unsqueeze(1), f_high_proj.unsqueeze(1)], dim=1) loss_contrast = criterion(features)",
"parser.parse_args() args.epochs = args.epoch args.decay = args.weight_decay args.cosine = True import math if",
"self.rand = config['random_start'] self.step_size = config['step_size'] self.epsilon = config['epsilon'] self.num_steps = config['num_steps'] assert",
"label_pseudo_train_list = [] num_classes_list = [2, 10, 50, 100, 500] dict_name = 'data/{}_pseudo_labels.pkl'.format(args.cname)",
"bn_name='pgd', contrast=True) fce_proj, fce_pred, logits_ce = self.model(x_ce, bn_name='pgd_ce', contrast=True, CF=True, return_logits=True, nonlinear=False) f1_proj,",
"parser.add_argument('--epsilon', type=float, default=8, help='The upper bound change of L-inf norm on input pixels')",
"nonlinear=False) f1_proj, f1_pred = self.model(x1, bn_name='normal', contrast=True) f2_proj, f2_pred = self.model(x2, bn_name='normal', contrast=True)",
"SupConLoss import tensorboard_logger as tb_logger from models.resnet_cifar_multibn_ensembleFC import resnet18 as ResNet18 import random",
"type=float, default=8, help='The upper bound change of L-inf norm on input pixels') parser.add_argument('--iter',",
"255, 'random_start': True, 'loss_func': 'xent', } # ================================================================== # # Data and Pre-processing",
"f f.close() for i in range(5): class_num = num_classes_list[i] key_train = 'pseudo_train_{}'.format(class_num) label_pseudo_train",
"train_loss = 0 correct = 0 total = 0 for batch_idx, (inputs, _,",
"================================================================== # np.random.seed(args.seed) random.seed(args.seed) torch.manual_seed(args.seed) torch.cuda.manual_seed_all(args.seed) for epoch in range(start_epoch, args.epoch+2): adjust_learning_rate(args, optimizer,",
"= 0 for label_idx in range(5): tgt = targets[label_idx].long() lgt = logits_ce[label_idx] loss_ce",
"= x_cl + torch.zeros_like(x1).uniform_(-self.epsilon, self.epsilon) x_ce = x_ce + torch.zeros_like(x1).uniform_(-self.epsilon, self.epsilon) for i",
"self.step_size = config['step_size'] self.epsilon = config['epsilon'] self.num_steps = config['num_steps'] assert config['loss_func'] == 'xent',",
"help='The upper bound change of L-inf norm on input pixels') parser.add_argument('--iter', type=int, default=5,",
"= images_org.clone().detach() x_ce = images_org.clone().detach() images_org_high = generate_high(x_cl.clone(), r=args.radius) x_HFC = images_org_high.clone().detach() if",
"argparse.ArgumentParser() parser.add_argument('--name', type=str, default='advcl_cifar10', help='name of the run') parser.add_argument('--cname', type=str, default='imagenet_clPretrain', help='') parser.add_argument('--batch-size',",
"GPUs!') raise NotImplementedError net = AttackPGD(model, config) # Loss and optimizer ce_criterion =",
"bn_name='normal', contrast=True) features = torch.cat( [f_proj.unsqueeze(1), f1_proj.unsqueeze(1), f2_proj.unsqueeze(1), f_high_proj.unsqueeze(1)], dim=1) contrast_loss = contrast_criterion(features)",
"Run the model # # ================================================================== # np.random.seed(args.seed) random.seed(args.seed) torch.manual_seed(args.seed) torch.cuda.manual_seed_all(args.seed) for epoch",
"images_org + self.epsilon) x_cl = torch.clamp(x_cl, 0, 1) x_ce = x_ce.detach() + self.step_size",
"fce_pred, logits_ce = model(x_ce, bn_name='pgd_ce', contrast=True, CF=True, return_logits=True, nonlinear=False) f1_proj, f1_pred = model(x1,",
"grad_x_ce = torch.autograd.grad(loss, [x_cl, x_ce]) x_cl = x_cl.detach() + self.step_size * torch.sign(grad_x_cl.detach()) x_cl",
"'{}/epoch_{}.ckpt'.format(save_dir, epoch)) # ================================================================== # # Run the model # # ================================================================== #",
"f_pred = model(x_cl, bn_name='pgd', contrast=True) fce_proj, fce_pred, logits_ce = model(x_ce, bn_name='pgd_ce', contrast=True, CF=True,",
"Device configuration device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') args.name = 'AdvCL_Cifar10' config",
"# # Arguments parser = argparse.ArgumentParser() parser.add_argument('--name', type=str, default='advcl_cifar10', help='name of the run')",
"= [] for tt_ in targets: tt.append(tt_.to(device).long()) targets = tt image_t1, image_t2, image_org",
"'AdvCL_Cifar10' config = { 'epsilon': args.epsilon / 255., 'num_steps': args.iter, 'step_size': 2.0 /",
"x_cl = torch.min(torch.max(x_cl, images_org - self.epsilon), images_org + self.epsilon) x_cl = torch.clamp(x_cl, 0,",
"Let's use\", torch.cuda.device_count(), \"GPUs!\") model = apex.parallel.convert_syncbn_model(model) model = nn.DataParallel(model) model = model.cuda()",
"train_loss, train_acc = train(epoch) logger.log_value('train_loss', train_loss, epoch) logger.log_value('learning_rate', optimizer.param_groups[0]['lr'], epoch) if epoch %",
"x_ce = images_org.clone().detach() images_org_high = generate_high(x_cl.clone(), r=args.radius) x_HFC = images_org_high.clone().detach() if self.rand: x_cl",
"= 'pseudo_train_{}'.format(class_num) label_pseudo_train = feat_label_dict[key_train] label_pseudo_train_list.append(label_pseudo_train) train_dataset = CIFAR10IndexPseudoLabelEnsemble(root='data', transform=transform_train, pseudoLabel_002=label_pseudo_train_list[0], pseudoLabel_010=label_pseudo_train_list[1], pseudoLabel_050=label_pseudo_train_list[2],",
"net = AttackPGD(model, config) # Loss and optimizer ce_criterion = nn.CrossEntropyLoss(ignore_index=-1) contrast_criterion =",
"and Test # # ================================================================== # def train(epoch): print('\\nEpoch: %d' % epoch) net.train()",
"size') parser.add_argument('--epoch', type=int, default=1000, help='total epochs') parser.add_argument('--save-epoch', type=int, default=100, help='save epochs') parser.add_argument('--epsilon', type=float,",
"from losses import SupConLoss import tensorboard_logger as tb_logger from models.resnet_cifar_multibn_ensembleFC import resnet18 as",
"0 for label_idx in range(5): tgt = targets[label_idx].long() lgt = logits_ce[label_idx] loss_ce +=",
"import numpy as np import os, csv from dataset import CIFAR10IndexPseudoLabelEnsemble import pickle",
"'epsilon': args.epsilon / 255., 'num_steps': args.iter, 'step_size': 2.0 / 255, 'random_start': True, 'loss_func':",
"type=float, default=0.9, help='momentum') args = parser.parse_args() args.epochs = args.epoch args.decay = args.weight_decay args.cosine",
"of the run') parser.add_argument('--cname', type=str, default='imagenet_clPretrain', help='') parser.add_argument('--batch-size', type=int, default=512, help='batch size') parser.add_argument('--epoch',",
"self.epsilon) x_cl = torch.clamp(x_cl, 0, 1) x_ce = x_ce.detach() + self.step_size * torch.sign(grad_x_ce.detach())",
"default=0.5, type=float, help='temperature') parser.add_argument('--seed', default=0, type=float, help='random seed') parser.add_argument('--dataset', type=str, default='cifar10', help='dataset') parser.add_argument('--cosine',",
"as nn import torch.nn.functional as F import torchvision.transforms as transforms import torch.utils.data as",
"# ================================================================== # # Save checkpoint def checkpoint(epoch): print('=====> Saving checkpoint...') state =",
"annealing') parser.add_argument('--warm', action='store_true', help='warm-up for large batch training') parser.add_argument('--learning_rate', type=float, default=0.5, help='learning rate')",
"the run') parser.add_argument('--cname', type=str, default='imagenet_clPretrain', help='') parser.add_argument('--batch-size', type=int, default=512, help='batch size') parser.add_argument('--epoch', type=int,",
"bn_name='normal', contrast=True) f2_proj, f2_pred = self.model(x2, bn_name='normal', contrast=True) f_high_proj, f_high_pred = self.model(x_HFC, bn_name='normal',",
"import torch.nn.functional as F import torchvision.transforms as transforms import torch.utils.data as Data import",
"warmup_learning_rate import apex # ================================================================== # # Inputs and Pre-definition # # ==================================================================",
"as transforms import torch.utils.data as Data import torch.backends.cudnn as cudnn from utils import",
"# ================================================================== # # Arguments parser = argparse.ArgumentParser() parser.add_argument('--name', type=str, default='advcl_cifar10', help='name of",
"import random from fr_util import generate_high from utils import adjust_learning_rate, warmup_learning_rate import apex",
"optimizer = torch.optim.Adam(net.parameters(), lr=args.lr) # ================================================================== # # Train and Test # #",
"help='momentum') args = parser.parse_args() args.epochs = args.epoch args.decay = args.weight_decay args.cosine = True",
"= tb_logger.Logger(logdir=logname, flush_secs=2) if torch.cuda.device_count() > 1: print(\"=====> Let's use\", torch.cuda.device_count(), \"GPUs!\") model",
"np.random.seed(args.seed) random.seed(args.seed) torch.manual_seed(args.seed) torch.cuda.manual_seed_all(args.seed) for epoch in range(start_epoch, args.epoch+2): adjust_learning_rate(args, optimizer, epoch+1) train_loss,",
"checkpoint epoch # Device configuration device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') args.name",
"f_pred = self.model(x_cl, bn_name='pgd', contrast=True) fce_proj, fce_pred, logits_ce = self.model(x_ce, bn_name='pgd_ce', contrast=True, CF=True,",
"= torch.clamp(x_ce, 0, 1) return x1, x2, x_cl, x_ce, x_HFC print('=====> Building model...')",
"= torch.cat( [f_proj.unsqueeze(1), f1_proj.unsqueeze(1), f2_proj.unsqueeze(1), f_high_proj.unsqueeze(1)], dim=1) contrast_loss = contrast_criterion(features) ce_loss = 0",
"and optimizer ce_criterion = nn.CrossEntropyLoss(ignore_index=-1) contrast_criterion = SupConLoss(temperature=args.nce_t) optimizer = torch.optim.SGD(net.parameters(), lr=args.learning_rate, momentum=0.9,",
"# PGD attack model class AttackPGD(nn.Module): def __init__(self, model, config): super(AttackPGD, self).__init__() self.model",
"1 + math.cos(math.pi * args.warm_epochs / args.epochs)) / 2 else: args.warmup_to = args.learning_rate",
"torch.clamp(x_cl, 0, 1) x_ce = x_ce.detach() + self.step_size * torch.sign(grad_x_ce.detach()) x_ce = torch.min(torch.max(x_ce,",
"model, config): super(AttackPGD, self).__init__() self.model = model self.rand = config['random_start'] self.step_size = config['step_size']",
"+ ce_loss * args.ce_weight loss.backward() optimizer.step() train_loss += loss.item() total += targets[0].size(0) progress_bar(batch_idx,",
"or last checkpoint epoch # Device configuration device = torch.device('cuda' if torch.cuda.is_available() else",
"Data import torch.backends.cudnn as cudnn from utils import progress_bar, TwoCropTransformAdv from losses import",
"help='dataset') parser.add_argument('--cosine', action='store_true', help='using cosine annealing') parser.add_argument('--warm', action='store_true', help='warm-up for large batch training')",
"= model.cuda() # tb_logger if not os.path.exists('logger'): os.makedirs('logger') logname = ('logger/pretrain_{}'.format(args.name)) logger =",
"= tt image_t1, image_t2, image_org = inputs image_t1 = image_t1.cuda(non_blocking=True) image_t2 = image_t2.cuda(non_blocking=True)",
"self.epsilon) x_ce = x_ce + torch.zeros_like(x1).uniform_(-self.epsilon, self.epsilon) for i in range(self.num_steps): x_cl.requires_grad_() x_ce.requires_grad_()",
"epoch, 'rng_state': torch.get_rng_state() } save_dir = './checkpoint/{}'.format(args.name) if not os.path.isdir(save_dir): os.makedirs(save_dir) torch.save(state, '{}/epoch_{}.ckpt'.format(save_dir,",
"import torch.backends.cudnn as cudnn from utils import progress_bar, TwoCropTransformAdv from losses import SupConLoss",
"self.epsilon = config['epsilon'] self.num_steps = config['num_steps'] assert config['loss_func'] == 'xent', 'Plz use xent",
"type=str, default='cifar10', help='dataset') parser.add_argument('--cosine', action='store_true', help='using cosine annealing') parser.add_argument('--warm', action='store_true', help='warm-up for large",
"0 # start from epoch 0 or last checkpoint epoch # Device configuration",
"loss_ce * args.ce_weight grad_x_cl, grad_x_ce = torch.autograd.grad(loss, [x_cl, x_ce]) x_cl = x_cl.detach() +",
"[] num_classes_list = [2, 10, 50, 100, 500] dict_name = 'data/{}_pseudo_labels.pkl'.format(args.cname) f =",
"x_ce = torch.clamp(x_ce, 0, 1) return x1, x2, x_cl, x_ce, x_HFC print('=====> Building",
"} # ================================================================== # # Data and Pre-processing # # ================================================================== # print('=====>",
"tb_logger from models.resnet_cifar_multibn_ensembleFC import resnet18 as ResNet18 import random from fr_util import generate_high",
"scale=(0.2, 1.)), transforms.RandomHorizontalFlip(), transforms.RandomApply([ transforms.ColorJitter(0.4, 0.4, 0.4, 0.1) ], p=0.8), transforms.RandomGrayscale(p=0.2), transforms.ToTensor(), ])",
"images_t1.clone().detach() x2 = images_t2.clone().detach() x_cl = images_org.clone().detach() x_ce = images_org.clone().detach() images_org_high = generate_high(x_cl.clone(),",
"type=str, default='imagenet_clPretrain', help='') parser.add_argument('--batch-size', type=int, default=512, help='batch size') parser.add_argument('--epoch', type=int, default=1000, help='total epochs')",
"= nn.CrossEntropyLoss(ignore_index=-1) contrast_criterion = SupConLoss(temperature=args.nce_t) optimizer = torch.optim.SGD(net.parameters(), lr=args.learning_rate, momentum=0.9, weight_decay=args.decay) # optimizer",
"= generate_high(x_cl.clone(), r=args.radius) x_HFC = images_org_high.clone().detach() if self.rand: x_cl = x_cl + torch.zeros_like(x1).uniform_(-self.epsilon,",
"% (train_loss/(batch_idx+1), correct, total)) return train_loss/batch_idx, 0. # ================================================================== # # Checkpoint #",
"= config['step_size'] self.epsilon = config['epsilon'] self.num_steps = config['num_steps'] assert config['loss_func'] == 'xent', 'Plz",
"list') parser.add_argument('--lr_decay_rate', type=float, default=0.1, help='decay rate for learning rate') parser.add_argument('--weight_decay', type=float, default=1e-4, help='weight",
"num_workers=n_gpu*4) # ================================================================== # # Model, Loss and Optimizer # # ================================================================== #",
"50, 100, 500] dict_name = 'data/{}_pseudo_labels.pkl'.format(args.cname) f = open(dict_name, 'rb') # Pickle file",
"contrast=True) f_high_proj, f_high_pred = model(x_HFC, bn_name='normal', contrast=True) features = torch.cat( [f_proj.unsqueeze(1), f1_proj.unsqueeze(1), f2_proj.unsqueeze(1),",
"epoch)) # ================================================================== # # Run the model # # ================================================================== # np.random.seed(args.seed)",
"> 1: print(\"=====> Let's use\", torch.cuda.device_count(), \"GPUs!\") model = apex.parallel.convert_syncbn_model(model) model = nn.DataParallel(model)",
"# Arguments parser = argparse.ArgumentParser() parser.add_argument('--name', type=str, default='advcl_cifar10', help='name of the run') parser.add_argument('--cname',",
"pseudoLabel_100=label_pseudo_train_list[3], pseudoLabel_500=label_pseudo_train_list[4], download=True) # Data Loader train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True, num_workers=n_gpu*4) #",
"= torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True, num_workers=n_gpu*4) # ================================================================== # # Model, Loss and Optimizer",
"help='where to decay lr, can be a list') parser.add_argument('--lr_decay_rate', type=float, default=0.1, help='decay rate",
"+ math.cos(math.pi * args.warm_epochs / args.epochs)) / 2 else: args.warmup_to = args.learning_rate start_epoch",
"model class AttackPGD(nn.Module): def __init__(self, model, config): super(AttackPGD, self).__init__() self.model = model self.rand",
"def train(epoch): print('\\nEpoch: %d' % epoch) net.train() train_loss = 0 correct = 0",
"= self.model(x1, bn_name='normal', contrast=True) f2_proj, f2_pred = self.model(x2, bn_name='normal', contrast=True) f_high_proj, f_high_pred =",
"as np import os, csv from dataset import CIFAR10IndexPseudoLabelEnsemble import pickle import torch",
"default=0.2, help='cross entp weight') # contrastive related parser.add_argument('-t', '--nce_t', default=0.5, type=float, help='temperature') parser.add_argument('--seed',",
"dump data to f f.close() for i in range(5): class_num = num_classes_list[i] key_train",
"in range(self.num_steps): x_cl.requires_grad_() x_ce.requires_grad_() with torch.enable_grad(): f_proj, f_pred = self.model(x_cl, bn_name='pgd', contrast=True) fce_proj,",
"images_org_high.clone().detach() if self.rand: x_cl = x_cl + torch.zeros_like(x1).uniform_(-self.epsilon, self.epsilon) x_ce = x_ce +",
"= SupConLoss(temperature=args.nce_t) optimizer = torch.optim.SGD(net.parameters(), lr=args.learning_rate, momentum=0.9, weight_decay=args.decay) # optimizer = torch.optim.Adam(net.parameters(), lr=args.lr)",
"+= loss.item() total += targets[0].size(0) progress_bar(batch_idx, len(train_loader), 'Loss: %.3f (%d/%d)' % (train_loss/(batch_idx+1), correct,",
"import adjust_learning_rate, warmup_learning_rate import apex # ================================================================== # # Inputs and Pre-definition #",
"model(x2, bn_name='normal', contrast=True) f_high_proj, f_high_pred = model(x_HFC, bn_name='normal', contrast=True) features = torch.cat( [f_proj.unsqueeze(1),",
"type=int, default=512, help='batch size') parser.add_argument('--epoch', type=int, default=1000, help='total epochs') parser.add_argument('--save-epoch', type=int, default=100, help='save",
"if torch.cuda.is_available() else 'cpu') args.name = 'AdvCL_Cifar10' config = { 'epsilon': args.epsilon /",
"args.ce_weight grad_x_cl, grad_x_ce = torch.autograd.grad(loss, [x_cl, x_ce]) x_cl = x_cl.detach() + self.step_size *",
"% epoch) net.train() train_loss = 0 correct = 0 total = 0 for",
"[f_proj.unsqueeze(1), f1_proj.unsqueeze(1), f2_proj.unsqueeze(1), f_high_proj.unsqueeze(1)], dim=1) contrast_loss = contrast_criterion(features) ce_loss = 0 for label_idx",
"f1_proj.unsqueeze(1), f2_proj.unsqueeze(1), f_high_proj.unsqueeze(1)], dim=1) loss_contrast = criterion(features) loss_ce = 0 for label_idx in",
"# ================================================================== # # Inputs and Pre-definition # # ================================================================== # # Arguments",
"[x_cl, x_ce]) x_cl = x_cl.detach() + self.step_size * torch.sign(grad_x_cl.detach()) x_cl = torch.min(torch.max(x_cl, images_org",
"model self.rand = config['random_start'] self.step_size = config['step_size'] self.epsilon = config['epsilon'] self.num_steps = config['num_steps']",
"fr_util import generate_high from utils import adjust_learning_rate, warmup_learning_rate import apex # ================================================================== #",
"contrast=True) fce_proj, fce_pred, logits_ce = self.model(x_ce, bn_name='pgd_ce', contrast=True, CF=True, return_logits=True, nonlinear=False) f1_proj, f1_pred",
"is not supported, please use multiple GPUs!') raise NotImplementedError net = AttackPGD(model, config)",
"optimizer = torch.optim.SGD(net.parameters(), lr=args.learning_rate, momentum=0.9, weight_decay=args.decay) # optimizer = torch.optim.Adam(net.parameters(), lr=args.lr) # ==================================================================",
"args.warmup_to = args.learning_rate start_epoch = 0 # start from epoch 0 or last",
"# # ================================================================== # def train(epoch): print('\\nEpoch: %d' % epoch) net.train() train_loss =",
"= eta_min + (args.learning_rate - eta_min) * ( 1 + math.cos(math.pi * args.warm_epochs",
"change of L-inf norm on input pixels') parser.add_argument('--iter', type=int, default=5, help='The number of",
"image_t1, image_t2, image_org = inputs image_t1 = image_t1.cuda(non_blocking=True) image_t2 = image_t2.cuda(non_blocking=True) image_org =",
"5. loss = contrast_loss + ce_loss * args.ce_weight loss.backward() optimizer.step() train_loss += loss.item()",
"= args.epoch args.decay = args.weight_decay args.cosine = True import math if args.batch_size >",
"pickle.load(f) # dump data to f f.close() for i in range(5): class_num =",
"(train_loss/(batch_idx+1), correct, total)) return train_loss/batch_idx, 0. # ================================================================== # # Checkpoint # #",
"Pre-definition # # ================================================================== # # Arguments parser = argparse.ArgumentParser() parser.add_argument('--name', type=str, default='advcl_cifar10',",
"/ args.epochs)) / 2 else: args.warmup_to = args.learning_rate start_epoch = 0 # start",
"PGD attack model class AttackPGD(nn.Module): def __init__(self, model, config): super(AttackPGD, self).__init__() self.model =",
"- self.epsilon), images_org + self.epsilon) x_ce = torch.clamp(x_ce, 0, 1) return x1, x2,",
"parser.add_argument('--learning_rate', type=float, default=0.5, help='learning rate') parser.add_argument('--lr_decay_epochs', type=str, default='700,800,900', help='where to decay lr, can",
"Arguments parser = argparse.ArgumentParser() parser.add_argument('--name', type=str, default='advcl_cifar10', help='name of the run') parser.add_argument('--cname', type=str,",
"def forward(self, images_t1, images_t2, images_org, targets, criterion): x1 = images_t1.clone().detach() x2 = images_t2.clone().detach()",
"f2_pred = self.model(x2, bn_name='normal', contrast=True) f_high_proj, f_high_pred = self.model(x_HFC, bn_name='normal', contrast=True) features =",
"where foo1.py is feat_label_dict = pickle.load(f) # dump data to f f.close() for",
"version is not supported, please use multiple GPUs!') raise NotImplementedError net = AttackPGD(model,",
"args.epoch+2): adjust_learning_rate(args, optimizer, epoch+1) train_loss, train_acc = train(epoch) logger.log_value('train_loss', train_loss, epoch) logger.log_value('learning_rate', optimizer.param_groups[0]['lr'],",
"x_ce = x_ce.detach() + self.step_size * torch.sign(grad_x_ce.detach()) x_ce = torch.min(torch.max(x_ce, images_org - self.epsilon),",
"# ================================================================== # # Checkpoint # # ================================================================== # # Save checkpoint def",
"import torchvision.transforms as transforms import torch.utils.data as Data import torch.backends.cudnn as cudnn from",
"gpu version is not supported, please use multiple GPUs!') raise NotImplementedError net =",
"( 1 + math.cos(math.pi * args.warm_epochs / args.epochs)) / 2 else: args.warmup_to =",
"Multi-cuda if torch.cuda.is_available(): n_gpu = torch.cuda.device_count() batch_size = args.batch_size transform_train = transforms.Compose([ transforms.RandomResizedCrop(size=32,",
"================================================================== # # Model, Loss and Optimizer # # ================================================================== # # PGD",
"if self.rand: x_cl = x_cl + torch.zeros_like(x1).uniform_(-self.epsilon, self.epsilon) x_ce = x_ce + torch.zeros_like(x1).uniform_(-self.epsilon,",
"f_high_proj, f_high_pred = model(x_HFC, bn_name='normal', contrast=True) features = torch.cat( [f_proj.unsqueeze(1), f1_proj.unsqueeze(1), f2_proj.unsqueeze(1), f_high_proj.unsqueeze(1)],",
"import math if args.batch_size > 256: args.warm = True if args.warm: args.warmup_from =",
"for iterative attacks') parser.add_argument('--radius', type=int, default=8, help='radius of low freq images') parser.add_argument('--ce_weight', type=float,",
"batch_size=batch_size, shuffle=True, num_workers=n_gpu*4) # ================================================================== # # Model, Loss and Optimizer # #",
"= torch.cuda.device_count() batch_size = args.batch_size transform_train = transforms.Compose([ transforms.RandomResizedCrop(size=32, scale=(0.2, 1.)), transforms.RandomHorizontalFlip(), transforms.RandomApply([",
"epochs') parser.add_argument('--epsilon', type=float, default=8, help='The upper bound change of L-inf norm on input",
"# # ================================================================== # # Arguments parser = argparse.ArgumentParser() parser.add_argument('--name', type=str, default='advcl_cifar10', help='name",
"import tensorboard_logger as tb_logger from models.resnet_cifar_multibn_ensembleFC import resnet18 as ResNet18 import random from",
"= ResNet18(bn_names=bn_names) model = model.cuda() # tb_logger if not os.path.exists('logger'): os.makedirs('logger') logname =",
"use\", torch.cuda.device_count(), \"GPUs!\") model = apex.parallel.convert_syncbn_model(model) model = nn.DataParallel(model) model = model.cuda() cudnn.benchmark",
"model = nn.DataParallel(model) model = model.cuda() cudnn.benchmark = True else: print('single gpu version",
"cudnn.benchmark = True else: print('single gpu version is not supported, please use multiple",
"= torch.optim.Adam(net.parameters(), lr=args.lr) # ================================================================== # # Train and Test # # ==================================================================",
"torch.cuda.manual_seed_all(args.seed) for epoch in range(start_epoch, args.epoch+2): adjust_learning_rate(args, optimizer, epoch+1) train_loss, train_acc = train(epoch)",
"optimizer, epoch+1) train_loss, train_acc = train(epoch) logger.log_value('train_loss', train_loss, epoch) logger.log_value('learning_rate', optimizer.param_groups[0]['lr'], epoch) if",
"import print_function import argparse import numpy as np import os, csv from dataset",
"contrast=True) features = torch.cat( [f_proj.unsqueeze(1), f1_proj.unsqueeze(1), f2_proj.unsqueeze(1), f_high_proj.unsqueeze(1)], dim=1) contrast_loss = contrast_criterion(features) ce_loss",
"= 'data/{}_pseudo_labels.pkl'.format(args.cname) f = open(dict_name, 'rb') # Pickle file is newly created where",
"args.warmup_to = eta_min + (args.learning_rate - eta_min) * ( 1 + math.cos(math.pi *",
"(args.learning_rate - eta_min) * ( 1 + math.cos(math.pi * args.warm_epochs / args.epochs)) /",
"of low freq images') parser.add_argument('--ce_weight', type=float, default=0.2, help='cross entp weight') # contrastive related",
"range(5): class_num = num_classes_list[i] key_train = 'pseudo_train_{}'.format(class_num) label_pseudo_train = feat_label_dict[key_train] label_pseudo_train_list.append(label_pseudo_train) train_dataset =",
"fce_pred, logits_ce = self.model(x_ce, bn_name='pgd_ce', contrast=True, CF=True, return_logits=True, nonlinear=False) f1_proj, f1_pred = self.model(x1,",
"return_logits=True, nonlinear=False) f1_proj, f1_pred = model(x1, bn_name='normal', contrast=True) f2_proj, f2_pred = model(x2, bn_name='normal',",
"= torch.device('cuda' if torch.cuda.is_available() else 'cpu') args.name = 'AdvCL_Cifar10' config = { 'epsilon':",
"print('=====> Saving checkpoint...') state = { 'model': model.state_dict(), 'epoch': epoch, 'rng_state': torch.get_rng_state() }",
"images') parser.add_argument('--ce_weight', type=float, default=0.2, help='cross entp weight') # contrastive related parser.add_argument('-t', '--nce_t', default=0.5,",
"x_cl.detach() + self.step_size * torch.sign(grad_x_cl.detach()) x_cl = torch.min(torch.max(x_cl, images_org - self.epsilon), images_org +",
"default=0, type=float, help='random seed') parser.add_argument('--dataset', type=str, default='cifar10', help='dataset') parser.add_argument('--cosine', action='store_true', help='using cosine annealing')",
"True import math if args.batch_size > 256: args.warm = True if args.warm: args.warmup_from",
"batch_size = args.batch_size transform_train = transforms.Compose([ transforms.RandomResizedCrop(size=32, scale=(0.2, 1.)), transforms.RandomHorizontalFlip(), transforms.RandomApply([ transforms.ColorJitter(0.4, 0.4,",
"args.learning_rate start_epoch = 0 # start from epoch 0 or last checkpoint epoch",
"'pgd', 'pgd_ce'] model = ResNet18(bn_names=bn_names) model = model.cuda() # tb_logger if not os.path.exists('logger'):",
"train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True, num_workers=n_gpu*4) # ================================================================== # # Model, Loss and",
"created where foo1.py is feat_label_dict = pickle.load(f) # dump data to f f.close()",
"transforms.ColorJitter(0.4, 0.4, 0.4, 0.1) ], p=0.8), transforms.RandomGrayscale(p=0.2), transforms.ToTensor(), ]) train_transform_org = transforms.Compose([ transforms.RandomCrop(32,",
"large batch training') parser.add_argument('--learning_rate', type=float, default=0.5, help='learning rate') parser.add_argument('--lr_decay_epochs', type=str, default='700,800,900', help='where to",
"torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True, num_workers=n_gpu*4) # ================================================================== # # Model, Loss and Optimizer #",
"torch.cuda.is_available() else 'cpu') args.name = 'AdvCL_Cifar10' config = { 'epsilon': args.epsilon / 255.,",
"data to f f.close() for i in range(5): class_num = num_classes_list[i] key_train =",
"{ 'epsilon': args.epsilon / 255., 'num_steps': args.iter, 'step_size': 2.0 / 255, 'random_start': True,",
"x_ce, x_HFC print('=====> Building model...') bn_names = ['normal', 'pgd', 'pgd_ce'] model = ResNet18(bn_names=bn_names)",
"bn_name='normal', contrast=True) f_high_proj, f_high_pred = model(x_HFC, bn_name='normal', contrast=True) features = torch.cat( [f_proj.unsqueeze(1), f1_proj.unsqueeze(1),",
"True else: print('single gpu version is not supported, please use multiple GPUs!') raise",
"contrast=True) f_high_proj, f_high_pred = self.model(x_HFC, bn_name='normal', contrast=True) features = torch.cat([f_proj.unsqueeze(1), f1_proj.unsqueeze(1), f2_proj.unsqueeze(1), f_high_proj.unsqueeze(1)],",
"train_dataset = CIFAR10IndexPseudoLabelEnsemble(root='data', transform=transform_train, pseudoLabel_002=label_pseudo_train_list[0], pseudoLabel_010=label_pseudo_train_list[1], pseudoLabel_050=label_pseudo_train_list[2], pseudoLabel_100=label_pseudo_train_list[3], pseudoLabel_500=label_pseudo_train_list[4], download=True) # Data Loader",
"ResNet18 import random from fr_util import generate_high from utils import adjust_learning_rate, warmup_learning_rate import",
"# # Inputs and Pre-definition # # ================================================================== # # Arguments parser =",
"torch.backends.cudnn as cudnn from utils import progress_bar, TwoCropTransformAdv from losses import SupConLoss import",
"# Pickle file is newly created where foo1.py is feat_label_dict = pickle.load(f) #",
"'num_steps': args.iter, 'step_size': 2.0 / 255, 'random_start': True, 'loss_func': 'xent', } # ==================================================================",
"255., 'num_steps': args.iter, 'step_size': 2.0 / 255, 'random_start': True, 'loss_func': 'xent', } #",
"f_proj, f_pred = model(x_cl, bn_name='pgd', contrast=True) fce_proj, fce_pred, logits_ce = model(x_ce, bn_name='pgd_ce', contrast=True,",
"/ 5. loss = contrast_loss + ce_loss * args.ce_weight loss.backward() optimizer.step() train_loss +=",
"images_t2, images_org, targets, criterion): x1 = images_t1.clone().detach() x2 = images_t2.clone().detach() x_cl = images_org.clone().detach()",
"lr=args.lr) # ================================================================== # # Train and Test # # ================================================================== # def",
"config['step_size'] self.epsilon = config['epsilon'] self.num_steps = config['num_steps'] assert config['loss_func'] == 'xent', 'Plz use",
"type=str, default='700,800,900', help='where to decay lr, can be a list') parser.add_argument('--lr_decay_rate', type=float, default=0.1,",
"for i in range(5): class_num = num_classes_list[i] key_train = 'pseudo_train_{}'.format(class_num) label_pseudo_train = feat_label_dict[key_train]",
"tgt, size_average=False, ignore_index=-1) / 5. loss = loss_contrast + loss_ce * args.ce_weight grad_x_cl,",
"optimizer.zero_grad() x1, x2, x_cl, x_ce, x_HFC = net(image_t1, image_t2, image_org, targets, contrast_criterion) f_proj,",
"import CIFAR10IndexPseudoLabelEnsemble import pickle import torch import torch.nn as nn import torch.nn.functional as",
"help='cross entp weight') # contrastive related parser.add_argument('-t', '--nce_t', default=0.5, type=float, help='temperature') parser.add_argument('--seed', default=0,",
"x_cl = x_cl.detach() + self.step_size * torch.sign(grad_x_cl.detach()) x_cl = torch.min(torch.max(x_cl, images_org - self.epsilon),",
"500] dict_name = 'data/{}_pseudo_labels.pkl'.format(args.cname) f = open(dict_name, 'rb') # Pickle file is newly",
"images_org - self.epsilon), images_org + self.epsilon) x_cl = torch.clamp(x_cl, 0, 1) x_ce =",
"contrast=True) f2_proj, f2_pred = model(x2, bn_name='normal', contrast=True) f_high_proj, f_high_pred = model(x_HFC, bn_name='normal', contrast=True)",
"= model(x_HFC, bn_name='normal', contrast=True) features = torch.cat( [f_proj.unsqueeze(1), f1_proj.unsqueeze(1), f2_proj.unsqueeze(1), f_high_proj.unsqueeze(1)], dim=1) contrast_loss",
"= argparse.ArgumentParser() parser.add_argument('--name', type=str, default='advcl_cifar10', help='name of the run') parser.add_argument('--cname', type=str, default='imagenet_clPretrain', help='')",
"= args.learning_rate start_epoch = 0 # start from epoch 0 or last checkpoint",
"f2_proj, f2_pred = model(x2, bn_name='normal', contrast=True) f_high_proj, f_high_pred = model(x_HFC, bn_name='normal', contrast=True) features",
"1) x_ce = x_ce.detach() + self.step_size * torch.sign(grad_x_ce.detach()) x_ce = torch.min(torch.max(x_ce, images_org -",
"# # ================================================================== # print('=====> Preparing data...') # Multi-cuda if torch.cuda.is_available(): n_gpu =",
"Pickle file is newly created where foo1.py is feat_label_dict = pickle.load(f) # dump",
"epoch+1, batch_idx, len(train_loader), optimizer) # attack contrast optimizer.zero_grad() x1, x2, x_cl, x_ce, x_HFC",
"Pre-processing # # ================================================================== # print('=====> Preparing data...') # Multi-cuda if torch.cuda.is_available(): n_gpu",
"torch.cuda.device_count() batch_size = args.batch_size transform_train = transforms.Compose([ transforms.RandomResizedCrop(size=32, scale=(0.2, 1.)), transforms.RandomHorizontalFlip(), transforms.RandomApply([ transforms.ColorJitter(0.4,",
"assert config['loss_func'] == 'xent', 'Plz use xent for loss function.' def forward(self, images_t1,",
"= targets[label_idx].long() lgt = logits_ce[label_idx] ce_loss += ce_criterion(lgt, tgt) / 5. loss =",
"model.state_dict(), 'epoch': epoch, 'rng_state': torch.get_rng_state() } save_dir = './checkpoint/{}'.format(args.name) if not os.path.isdir(save_dir): os.makedirs(save_dir)",
"bn_name='pgd_ce', contrast=True, CF=True, return_logits=True, nonlinear=False) f1_proj, f1_pred = self.model(x1, bn_name='normal', contrast=True) f2_proj, f2_pred",
"transforms.RandomHorizontalFlip(), transforms.RandomApply([ transforms.ColorJitter(0.4, 0.4, 0.4, 0.1) ], p=0.8), transforms.RandomGrayscale(p=0.2), transforms.ToTensor(), ]) train_transform_org =",
"for i in range(self.num_steps): x_cl.requires_grad_() x_ce.requires_grad_() with torch.enable_grad(): f_proj, f_pred = self.model(x_cl, bn_name='pgd',",
"lr=args.learning_rate, momentum=0.9, weight_decay=args.decay) # optimizer = torch.optim.Adam(net.parameters(), lr=args.lr) # ================================================================== # # Train",
"tt image_t1, image_t2, image_org = inputs image_t1 = image_t1.cuda(non_blocking=True) image_t2 = image_t2.cuda(non_blocking=True) image_org",
"# attack contrast optimizer.zero_grad() x1, x2, x_cl, x_ce, x_HFC = net(image_t1, image_t2, image_org,",
"targets = tt image_t1, image_t2, image_org = inputs image_t1 = image_t1.cuda(non_blocking=True) image_t2 =",
"save_dir = './checkpoint/{}'.format(args.name) if not os.path.isdir(save_dir): os.makedirs(save_dir) torch.save(state, '{}/epoch_{}.ckpt'.format(save_dir, epoch)) # ================================================================== #",
"f2_proj.unsqueeze(1), f_high_proj.unsqueeze(1)], dim=1) loss_contrast = criterion(features) loss_ce = 0 for label_idx in range(5):",
"= image_org.cuda(non_blocking=True) warmup_learning_rate(args, epoch+1, batch_idx, len(train_loader), optimizer) # attack contrast optimizer.zero_grad() x1, x2,",
"model = apex.parallel.convert_syncbn_model(model) model = nn.DataParallel(model) model = model.cuda() cudnn.benchmark = True else:",
"# start from epoch 0 or last checkpoint epoch # Device configuration device",
"type=int, default=8, help='radius of low freq images') parser.add_argument('--ce_weight', type=float, default=0.2, help='cross entp weight')",
"= CIFAR10IndexPseudoLabelEnsemble(root='data', transform=transform_train, pseudoLabel_002=label_pseudo_train_list[0], pseudoLabel_010=label_pseudo_train_list[1], pseudoLabel_050=label_pseudo_train_list[2], pseudoLabel_100=label_pseudo_train_list[3], pseudoLabel_500=label_pseudo_train_list[4], download=True) # Data Loader train_loader",
"attack model class AttackPGD(nn.Module): def __init__(self, model, config): super(AttackPGD, self).__init__() self.model = model",
"= args.weight_decay args.cosine = True import math if args.batch_size > 256: args.warm =",
"# dump data to f f.close() for i in range(5): class_num = num_classes_list[i]",
"if not os.path.isdir(save_dir): os.makedirs(save_dir) torch.save(state, '{}/epoch_{}.ckpt'.format(save_dir, epoch)) # ================================================================== # # Run the",
"+ self.step_size * torch.sign(grad_x_cl.detach()) x_cl = torch.min(torch.max(x_cl, images_org - self.epsilon), images_org + self.epsilon)",
"/ 255., 'num_steps': args.iter, 'step_size': 2.0 / 255, 'random_start': True, 'loss_func': 'xent', }",
"\"GPUs!\") model = apex.parallel.convert_syncbn_model(model) model = nn.DataParallel(model) model = model.cuda() cudnn.benchmark = True",
"transform=transform_train, pseudoLabel_002=label_pseudo_train_list[0], pseudoLabel_010=label_pseudo_train_list[1], pseudoLabel_050=label_pseudo_train_list[2], pseudoLabel_100=label_pseudo_train_list[3], pseudoLabel_500=label_pseudo_train_list[4], download=True) # Data Loader train_loader = torch.utils.data.DataLoader(dataset=train_dataset,",
"and Pre-definition # # ================================================================== # # Arguments parser = argparse.ArgumentParser() parser.add_argument('--name', type=str,",
"default=0.1, help='decay rate for learning rate') parser.add_argument('--weight_decay', type=float, default=1e-4, help='weight decay') parser.add_argument('--momentum', type=float,",
"torch.autograd.grad(loss, [x_cl, x_ce]) x_cl = x_cl.detach() + self.step_size * torch.sign(grad_x_cl.detach()) x_cl = torch.min(torch.max(x_cl,",
"optimizer.step() train_loss += loss.item() total += targets[0].size(0) progress_bar(batch_idx, len(train_loader), 'Loss: %.3f (%d/%d)' %",
"default=8, help='radius of low freq images') parser.add_argument('--ce_weight', type=float, default=0.2, help='cross entp weight') #",
"= images_org_high.clone().detach() if self.rand: x_cl = x_cl + torch.zeros_like(x1).uniform_(-self.epsilon, self.epsilon) x_ce = x_ce",
"f2_proj, f2_pred = self.model(x2, bn_name='normal', contrast=True) f_high_proj, f_high_pred = self.model(x_HFC, bn_name='normal', contrast=True) features",
"10, 50, 100, 500] dict_name = 'data/{}_pseudo_labels.pkl'.format(args.cname) f = open(dict_name, 'rb') # Pickle",
"adjust_learning_rate(args, optimizer, epoch+1) train_loss, train_acc = train(epoch) logger.log_value('train_loss', train_loss, epoch) logger.log_value('learning_rate', optimizer.param_groups[0]['lr'], epoch)",
"= config['random_start'] self.step_size = config['step_size'] self.epsilon = config['epsilon'] self.num_steps = config['num_steps'] assert config['loss_func']",
"import torch.utils.data as Data import torch.backends.cudnn as cudnn from utils import progress_bar, TwoCropTransformAdv",
"+ self.epsilon) x_cl = torch.clamp(x_cl, 0, 1) x_ce = x_ce.detach() + self.step_size *",
"batch training') parser.add_argument('--learning_rate', type=float, default=0.5, help='learning rate') parser.add_argument('--lr_decay_epochs', type=str, default='700,800,900', help='where to decay",
"p=0.8), transforms.RandomGrayscale(p=0.2), transforms.ToTensor(), ]) train_transform_org = transforms.Compose([ transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), ]) transform_train",
"help='name of the run') parser.add_argument('--cname', type=str, default='imagenet_clPretrain', help='') parser.add_argument('--batch-size', type=int, default=512, help='batch size')",
"= nn.DataParallel(model) model = model.cuda() cudnn.benchmark = True else: print('single gpu version is",
"contrastive related parser.add_argument('-t', '--nce_t', default=0.5, type=float, help='temperature') parser.add_argument('--seed', default=0, type=float, help='random seed') parser.add_argument('--dataset',",
"models.resnet_cifar_multibn_ensembleFC import resnet18 as ResNet18 import random from fr_util import generate_high from utils",
"default='advcl_cifar10', help='name of the run') parser.add_argument('--cname', type=str, default='imagenet_clPretrain', help='') parser.add_argument('--batch-size', type=int, default=512, help='batch",
"10 if args.cosine: eta_min = args.learning_rate * (args.lr_decay_rate ** 3) args.warmup_to = eta_min",
"torch import torch.nn as nn import torch.nn.functional as F import torchvision.transforms as transforms",
"in range(5): tgt = targets[label_idx].long() lgt = logits_ce[label_idx] loss_ce += F.cross_entropy(lgt, tgt, size_average=False,",
"weight') # contrastive related parser.add_argument('-t', '--nce_t', default=0.5, type=float, help='temperature') parser.add_argument('--seed', default=0, type=float, help='random",
"targets, criterion): x1 = images_t1.clone().detach() x2 = images_t2.clone().detach() x_cl = images_org.clone().detach() x_ce =",
"+= F.cross_entropy(lgt, tgt, size_average=False, ignore_index=-1) / 5. loss = loss_contrast + loss_ce *",
"cudnn from utils import progress_bar, TwoCropTransformAdv from losses import SupConLoss import tensorboard_logger as",
"as ResNet18 import random from fr_util import generate_high from utils import adjust_learning_rate, warmup_learning_rate",
"entp weight') # contrastive related parser.add_argument('-t', '--nce_t', default=0.5, type=float, help='temperature') parser.add_argument('--seed', default=0, type=float,",
"config): super(AttackPGD, self).__init__() self.model = model self.rand = config['random_start'] self.step_size = config['step_size'] self.epsilon",
"features = torch.cat( [f_proj.unsqueeze(1), f1_proj.unsqueeze(1), f2_proj.unsqueeze(1), f_high_proj.unsqueeze(1)], dim=1) contrast_loss = contrast_criterion(features) ce_loss =",
"%.3f (%d/%d)' % (train_loss/(batch_idx+1), correct, total)) return train_loss/batch_idx, 0. # ================================================================== # #",
"= model self.rand = config['random_start'] self.step_size = config['step_size'] self.epsilon = config['epsilon'] self.num_steps =",
"padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), ]) transform_train = TwoCropTransformAdv(transform_train, train_transform_org) transform_test = transforms.Compose([ transforms.ToTensor(), ])",
"class AttackPGD(nn.Module): def __init__(self, model, config): super(AttackPGD, self).__init__() self.model = model self.rand =",
"args.warm_epochs / args.epochs)) / 2 else: args.warmup_to = args.learning_rate start_epoch = 0 #",
"of L-inf norm on input pixels') parser.add_argument('--iter', type=int, default=5, help='The number of iterations",
"['normal', 'pgd', 'pgd_ce'] model = ResNet18(bn_names=bn_names) model = model.cuda() # tb_logger if not",
"= config['epsilon'] self.num_steps = config['num_steps'] assert config['loss_func'] == 'xent', 'Plz use xent for",
"torch.cuda.device_count(), \"GPUs!\") model = apex.parallel.convert_syncbn_model(model) model = nn.DataParallel(model) model = model.cuda() cudnn.benchmark =",
"default=0.9, help='momentum') args = parser.parse_args() args.epochs = args.epoch args.decay = args.weight_decay args.cosine =",
"images_org, targets, criterion): x1 = images_t1.clone().detach() x2 = images_t2.clone().detach() x_cl = images_org.clone().detach() x_ce",
"= feat_label_dict[key_train] label_pseudo_train_list.append(label_pseudo_train) train_dataset = CIFAR10IndexPseudoLabelEnsemble(root='data', transform=transform_train, pseudoLabel_002=label_pseudo_train_list[0], pseudoLabel_010=label_pseudo_train_list[1], pseudoLabel_050=label_pseudo_train_list[2], pseudoLabel_100=label_pseudo_train_list[3], pseudoLabel_500=label_pseudo_train_list[4], download=True)",
"Train and Test # # ================================================================== # def train(epoch): print('\\nEpoch: %d' % epoch)",
"model # # ================================================================== # np.random.seed(args.seed) random.seed(args.seed) torch.manual_seed(args.seed) torch.cuda.manual_seed_all(args.seed) for epoch in range(start_epoch,",
"numpy as np import os, csv from dataset import CIFAR10IndexPseudoLabelEnsemble import pickle import",
"use multiple GPUs!') raise NotImplementedError net = AttackPGD(model, config) # Loss and optimizer",
"tt = [] for tt_ in targets: tt.append(tt_.to(device).long()) targets = tt image_t1, image_t2,",
"tt.append(tt_.to(device).long()) targets = tt image_t1, image_t2, image_org = inputs image_t1 = image_t1.cuda(non_blocking=True) image_t2",
"label_idx in range(5): tgt = targets[label_idx].long() lgt = logits_ce[label_idx] loss_ce += F.cross_entropy(lgt, tgt,",
"2.0 / 255, 'random_start': True, 'loss_func': 'xent', } # ================================================================== # # Data",
"images_org - self.epsilon), images_org + self.epsilon) x_ce = torch.clamp(x_ce, 0, 1) return x1,",
"= model(x_ce, bn_name='pgd_ce', contrast=True, CF=True, return_logits=True, nonlinear=False) f1_proj, f1_pred = model(x1, bn_name='normal', contrast=True)",
"= x_ce.detach() + self.step_size * torch.sign(grad_x_ce.detach()) x_ce = torch.min(torch.max(x_ce, images_org - self.epsilon), images_org",
"parser.add_argument('--ce_weight', type=float, default=0.2, help='cross entp weight') # contrastive related parser.add_argument('-t', '--nce_t', default=0.5, type=float,",
"attack contrast optimizer.zero_grad() x1, x2, x_cl, x_ce, x_HFC = net(image_t1, image_t2, image_org, targets,",
"action='store_true', help='warm-up for large batch training') parser.add_argument('--learning_rate', type=float, default=0.5, help='learning rate') parser.add_argument('--lr_decay_epochs', type=str,",
"================================================================== # # Inputs and Pre-definition # # ================================================================== # # Arguments parser",
"__future__ import print_function import argparse import numpy as np import os, csv from",
"help='') parser.add_argument('--batch-size', type=int, default=512, help='batch size') parser.add_argument('--epoch', type=int, default=1000, help='total epochs') parser.add_argument('--save-epoch', type=int,",
"'pseudo_train_{}'.format(class_num) label_pseudo_train = feat_label_dict[key_train] label_pseudo_train_list.append(label_pseudo_train) train_dataset = CIFAR10IndexPseudoLabelEnsemble(root='data', transform=transform_train, pseudoLabel_002=label_pseudo_train_list[0], pseudoLabel_010=label_pseudo_train_list[1], pseudoLabel_050=label_pseudo_train_list[2], pseudoLabel_100=label_pseudo_train_list[3],",
"/ 255, 'random_start': True, 'loss_func': 'xent', } # ================================================================== # # Data and",
"images_t2.clone().detach() x_cl = images_org.clone().detach() x_ce = images_org.clone().detach() images_org_high = generate_high(x_cl.clone(), r=args.radius) x_HFC =",
"lgt = logits_ce[label_idx] loss_ce += F.cross_entropy(lgt, tgt, size_average=False, ignore_index=-1) / 5. loss =",
"================================================================== # # Train and Test # # ================================================================== # def train(epoch): print('\\nEpoch:",
"# def train(epoch): print('\\nEpoch: %d' % epoch) net.train() train_loss = 0 correct =",
"for tt_ in targets: tt.append(tt_.to(device).long()) targets = tt image_t1, image_t2, image_org = inputs",
"args.iter, 'step_size': 2.0 / 255, 'random_start': True, 'loss_func': 'xent', } # ================================================================== #",
"contrast=True, CF=True, return_logits=True, nonlinear=False) f1_proj, f1_pred = self.model(x1, bn_name='normal', contrast=True) f2_proj, f2_pred =",
"0 for batch_idx, (inputs, _, targets, ind) in enumerate(train_loader): tt = [] for",
"and Pre-processing # # ================================================================== # print('=====> Preparing data...') # Multi-cuda if torch.cuda.is_available():",
"args.batch_size transform_train = transforms.Compose([ transforms.RandomResizedCrop(size=32, scale=(0.2, 1.)), transforms.RandomHorizontalFlip(), transforms.RandomApply([ transforms.ColorJitter(0.4, 0.4, 0.4, 0.1)",
"progress_bar, TwoCropTransformAdv from losses import SupConLoss import tensorboard_logger as tb_logger from models.resnet_cifar_multibn_ensembleFC import",
"Preparing data...') # Multi-cuda if torch.cuda.is_available(): n_gpu = torch.cuda.device_count() batch_size = args.batch_size transform_train",
"contrast_loss = contrast_criterion(features) ce_loss = 0 for label_idx in range(5): tgt = targets[label_idx].long()",
"model = model.cuda() cudnn.benchmark = True else: print('single gpu version is not supported,",
"x_HFC print('=====> Building model...') bn_names = ['normal', 'pgd', 'pgd_ce'] model = ResNet18(bn_names=bn_names) model",
"# ================================================================== # # Run the model # # ================================================================== # np.random.seed(args.seed) random.seed(args.seed)",
"batch_idx, len(train_loader), optimizer) # attack contrast optimizer.zero_grad() x1, x2, x_cl, x_ce, x_HFC =",
"parser.add_argument('--cname', type=str, default='imagenet_clPretrain', help='') parser.add_argument('--batch-size', type=int, default=512, help='batch size') parser.add_argument('--epoch', type=int, default=1000, help='total",
"0, 1) x_ce = x_ce.detach() + self.step_size * torch.sign(grad_x_ce.detach()) x_ce = torch.min(torch.max(x_ce, images_org",
"# np.random.seed(args.seed) random.seed(args.seed) torch.manual_seed(args.seed) torch.cuda.manual_seed_all(args.seed) for epoch in range(start_epoch, args.epoch+2): adjust_learning_rate(args, optimizer, epoch+1)",
"transforms.RandomResizedCrop(size=32, scale=(0.2, 1.)), transforms.RandomHorizontalFlip(), transforms.RandomApply([ transforms.ColorJitter(0.4, 0.4, 0.4, 0.1) ], p=0.8), transforms.RandomGrayscale(p=0.2), transforms.ToTensor(),",
"correct, total)) return train_loss/batch_idx, 0. # ================================================================== # # Checkpoint # # ==================================================================",
"# Model, Loss and Optimizer # # ================================================================== # # PGD attack model",
"= transforms.Compose([ transforms.RandomResizedCrop(size=32, scale=(0.2, 1.)), transforms.RandomHorizontalFlip(), transforms.RandomApply([ transforms.ColorJitter(0.4, 0.4, 0.4, 0.1) ], p=0.8),",
"F import torchvision.transforms as transforms import torch.utils.data as Data import torch.backends.cudnn as cudnn",
"train_transform_org) transform_test = transforms.Compose([ transforms.ToTensor(), ]) label_pseudo_train_list = [] num_classes_list = [2, 10,",
"model.cuda() # tb_logger if not os.path.exists('logger'): os.makedirs('logger') logname = ('logger/pretrain_{}'.format(args.name)) logger = tb_logger.Logger(logdir=logname,",
"tgt = targets[label_idx].long() lgt = logits_ce[label_idx] ce_loss += ce_criterion(lgt, tgt) / 5. loss",
"parser.add_argument('--epoch', type=int, default=1000, help='total epochs') parser.add_argument('--save-epoch', type=int, default=100, help='save epochs') parser.add_argument('--epsilon', type=float, default=8,",
"Data Loader train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True, num_workers=n_gpu*4) # ================================================================== # # Model,",
"in targets: tt.append(tt_.to(device).long()) targets = tt image_t1, image_t2, image_org = inputs image_t1 =",
"logits_ce[label_idx] ce_loss += ce_criterion(lgt, tgt) / 5. loss = contrast_loss + ce_loss *",
"================================================================== # # Save checkpoint def checkpoint(epoch): print('=====> Saving checkpoint...') state = {",
"transforms.RandomHorizontalFlip(), transforms.ToTensor(), ]) transform_train = TwoCropTransformAdv(transform_train, train_transform_org) transform_test = transforms.Compose([ transforms.ToTensor(), ]) label_pseudo_train_list",
"import progress_bar, TwoCropTransformAdv from losses import SupConLoss import tensorboard_logger as tb_logger from models.resnet_cifar_multibn_ensembleFC",
"x1, x2, x_cl, x_ce, x_HFC print('=====> Building model...') bn_names = ['normal', 'pgd', 'pgd_ce']",
"momentum=0.9, weight_decay=args.decay) # optimizer = torch.optim.Adam(net.parameters(), lr=args.lr) # ================================================================== # # Train and",
"args.weight_decay args.cosine = True import math if args.batch_size > 256: args.warm = True",
"= AttackPGD(model, config) # Loss and optimizer ce_criterion = nn.CrossEntropyLoss(ignore_index=-1) contrast_criterion = SupConLoss(temperature=args.nce_t)",
"torch.get_rng_state() } save_dir = './checkpoint/{}'.format(args.name) if not os.path.isdir(save_dir): os.makedirs(save_dir) torch.save(state, '{}/epoch_{}.ckpt'.format(save_dir, epoch)) #",
"= targets[label_idx].long() lgt = logits_ce[label_idx] loss_ce += F.cross_entropy(lgt, tgt, size_average=False, ignore_index=-1) / 5.",
"CF=True, return_logits=True, nonlinear=False) f1_proj, f1_pred = self.model(x1, bn_name='normal', contrast=True) f2_proj, f2_pred = self.model(x2,",
"targets: tt.append(tt_.to(device).long()) targets = tt image_t1, image_t2, image_org = inputs image_t1 = image_t1.cuda(non_blocking=True)",
"transform_test = transforms.Compose([ transforms.ToTensor(), ]) label_pseudo_train_list = [] num_classes_list = [2, 10, 50,",
"norm on input pixels') parser.add_argument('--iter', type=int, default=5, help='The number of iterations for iterative",
"help='random seed') parser.add_argument('--dataset', type=str, default='cifar10', help='dataset') parser.add_argument('--cosine', action='store_true', help='using cosine annealing') parser.add_argument('--warm', action='store_true',",
"= 0 correct = 0 total = 0 for batch_idx, (inputs, _, targets,",
"= transforms.Compose([ transforms.ToTensor(), ]) label_pseudo_train_list = [] num_classes_list = [2, 10, 50, 100,",
"5. loss = loss_contrast + loss_ce * args.ce_weight grad_x_cl, grad_x_ce = torch.autograd.grad(loss, [x_cl,",
"type=int, default=1000, help='total epochs') parser.add_argument('--save-epoch', type=int, default=100, help='save epochs') parser.add_argument('--epsilon', type=float, default=8, help='The",
"'Plz use xent for loss function.' def forward(self, images_t1, images_t2, images_org, targets, criterion):",
"images_org_high = generate_high(x_cl.clone(), r=args.radius) x_HFC = images_org_high.clone().detach() if self.rand: x_cl = x_cl +",
"torch.nn.functional as F import torchvision.transforms as transforms import torch.utils.data as Data import torch.backends.cudnn",
"optimizer ce_criterion = nn.CrossEntropyLoss(ignore_index=-1) contrast_criterion = SupConLoss(temperature=args.nce_t) optimizer = torch.optim.SGD(net.parameters(), lr=args.learning_rate, momentum=0.9, weight_decay=args.decay)",
"contrast=True) f2_proj, f2_pred = self.model(x2, bn_name='normal', contrast=True) f_high_proj, f_high_pred = self.model(x_HFC, bn_name='normal', contrast=True)",
"generate_high from utils import adjust_learning_rate, warmup_learning_rate import apex # ================================================================== # # Inputs",
"# ================================================================== # # PGD attack model class AttackPGD(nn.Module): def __init__(self, model, config):",
"torch.zeros_like(x1).uniform_(-self.epsilon, self.epsilon) x_ce = x_ce + torch.zeros_like(x1).uniform_(-self.epsilon, self.epsilon) for i in range(self.num_steps): x_cl.requires_grad_()",
"loss_contrast = criterion(features) loss_ce = 0 for label_idx in range(5): tgt = targets[label_idx].long()",
"not supported, please use multiple GPUs!') raise NotImplementedError net = AttackPGD(model, config) #",
"seed') parser.add_argument('--dataset', type=str, default='cifar10', help='dataset') parser.add_argument('--cosine', action='store_true', help='using cosine annealing') parser.add_argument('--warm', action='store_true', help='warm-up",
"# # Save checkpoint def checkpoint(epoch): print('=====> Saving checkpoint...') state = { 'model':",
"Saving checkpoint...') state = { 'model': model.state_dict(), 'epoch': epoch, 'rng_state': torch.get_rng_state() } save_dir",
"__init__(self, model, config): super(AttackPGD, self).__init__() self.model = model self.rand = config['random_start'] self.step_size =",
"ce_criterion = nn.CrossEntropyLoss(ignore_index=-1) contrast_criterion = SupConLoss(temperature=args.nce_t) optimizer = torch.optim.SGD(net.parameters(), lr=args.learning_rate, momentum=0.9, weight_decay=args.decay) #",
"train_acc = train(epoch) logger.log_value('train_loss', train_loss, epoch) logger.log_value('learning_rate', optimizer.param_groups[0]['lr'], epoch) if epoch % args.save_epoch",
"type=float, default=0.1, help='decay rate for learning rate') parser.add_argument('--weight_decay', type=float, default=1e-4, help='weight decay') parser.add_argument('--momentum',",
"if args.cosine: eta_min = args.learning_rate * (args.lr_decay_rate ** 3) args.warmup_to = eta_min +",
"math if args.batch_size > 256: args.warm = True if args.warm: args.warmup_from = 0.01",
"= images_t2.clone().detach() x_cl = images_org.clone().detach() x_ce = images_org.clone().detach() images_org_high = generate_high(x_cl.clone(), r=args.radius) x_HFC",
"parser.add_argument('--seed', default=0, type=float, help='random seed') parser.add_argument('--dataset', type=str, default='cifar10', help='dataset') parser.add_argument('--cosine', action='store_true', help='using cosine",
"return_logits=True, nonlinear=False) f1_proj, f1_pred = self.model(x1, bn_name='normal', contrast=True) f2_proj, f2_pred = self.model(x2, bn_name='normal',",
"1.)), transforms.RandomHorizontalFlip(), transforms.RandomApply([ transforms.ColorJitter(0.4, 0.4, 0.4, 0.1) ], p=0.8), transforms.RandomGrayscale(p=0.2), transforms.ToTensor(), ]) train_transform_org",
"len(train_loader), 'Loss: %.3f (%d/%d)' % (train_loss/(batch_idx+1), correct, total)) return train_loss/batch_idx, 0. # ==================================================================",
"= images_t1.clone().detach() x2 = images_t2.clone().detach() x_cl = images_org.clone().detach() x_ce = images_org.clone().detach() images_org_high =",
"number of iterations for iterative attacks') parser.add_argument('--radius', type=int, default=8, help='radius of low freq",
"args.cosine = True import math if args.batch_size > 256: args.warm = True if",
"= model.cuda() cudnn.benchmark = True else: print('single gpu version is not supported, please",
"= x_cl.detach() + self.step_size * torch.sign(grad_x_cl.detach()) x_cl = torch.min(torch.max(x_cl, images_org - self.epsilon), images_org",
"+= targets[0].size(0) progress_bar(batch_idx, len(train_loader), 'Loss: %.3f (%d/%d)' % (train_loss/(batch_idx+1), correct, total)) return train_loss/batch_idx,",
"transforms.ToTensor(), ]) transform_train = TwoCropTransformAdv(transform_train, train_transform_org) transform_test = transforms.Compose([ transforms.ToTensor(), ]) label_pseudo_train_list =",
"transforms.ToTensor(), ]) train_transform_org = transforms.Compose([ transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), ]) transform_train = TwoCropTransformAdv(transform_train,",
"f1_pred = self.model(x1, bn_name='normal', contrast=True) f2_proj, f2_pred = self.model(x2, bn_name='normal', contrast=True) f_high_proj, f_high_pred",
"warmup_learning_rate(args, epoch+1, batch_idx, len(train_loader), optimizer) # attack contrast optimizer.zero_grad() x1, x2, x_cl, x_ce,",
"type=float, default=0.2, help='cross entp weight') # contrastive related parser.add_argument('-t', '--nce_t', default=0.5, type=float, help='temperature')",
"label_pseudo_train = feat_label_dict[key_train] label_pseudo_train_list.append(label_pseudo_train) train_dataset = CIFAR10IndexPseudoLabelEnsemble(root='data', transform=transform_train, pseudoLabel_002=label_pseudo_train_list[0], pseudoLabel_010=label_pseudo_train_list[1], pseudoLabel_050=label_pseudo_train_list[2], pseudoLabel_100=label_pseudo_train_list[3], pseudoLabel_500=label_pseudo_train_list[4],",
"config['num_steps'] assert config['loss_func'] == 'xent', 'Plz use xent for loss function.' def forward(self,",
"torch.sign(grad_x_ce.detach()) x_ce = torch.min(torch.max(x_ce, images_org - self.epsilon), images_org + self.epsilon) x_ce = torch.clamp(x_ce,",
"flush_secs=2) if torch.cuda.device_count() > 1: print(\"=====> Let's use\", torch.cuda.device_count(), \"GPUs!\") model = apex.parallel.convert_syncbn_model(model)",
"range(5): tgt = targets[label_idx].long() lgt = logits_ce[label_idx] ce_loss += ce_criterion(lgt, tgt) / 5.",
"torch.device('cuda' if torch.cuda.is_available() else 'cpu') args.name = 'AdvCL_Cifar10' config = { 'epsilon': args.epsilon",
"100, 500] dict_name = 'data/{}_pseudo_labels.pkl'.format(args.cname) f = open(dict_name, 'rb') # Pickle file is",
"argparse import numpy as np import os, csv from dataset import CIFAR10IndexPseudoLabelEnsemble import",
"* torch.sign(grad_x_cl.detach()) x_cl = torch.min(torch.max(x_cl, images_org - self.epsilon), images_org + self.epsilon) x_cl =",
"related parser.add_argument('-t', '--nce_t', default=0.5, type=float, help='temperature') parser.add_argument('--seed', default=0, type=float, help='random seed') parser.add_argument('--dataset', type=str,",
"- eta_min) * ( 1 + math.cos(math.pi * args.warm_epochs / args.epochs)) / 2",
"model(x1, bn_name='normal', contrast=True) f2_proj, f2_pred = model(x2, bn_name='normal', contrast=True) f_high_proj, f_high_pred = model(x_HFC,",
"adjust_learning_rate, warmup_learning_rate import apex # ================================================================== # # Inputs and Pre-definition # #",
"epoch) net.train() train_loss = 0 correct = 0 total = 0 for batch_idx,",
"f1_proj, f1_pred = self.model(x1, bn_name='normal', contrast=True) f2_proj, f2_pred = self.model(x2, bn_name='normal', contrast=True) f_high_proj,",
"lr, can be a list') parser.add_argument('--lr_decay_rate', type=float, default=0.1, help='decay rate for learning rate')",
"function.' def forward(self, images_t1, images_t2, images_org, targets, criterion): x1 = images_t1.clone().detach() x2 ="
] |
[
"the figure format: # e.g., nameFig = 'Position.png' or nameFig = 'linearVelocity.eps' import",
"nameFig = os.path.join(\"/content/Figures/\",nameFig) fig.savefig(nameFig, dpi=300, bbox_inches='tight') #--- # Save Figure: def saveFig(fig,nameFig): #",
"the name must contain the figure format: # e.g., nameFig = 'Position.png' or",
"#--- # Save Figure: def saveFig_old(fig,nameFig): # ------- the name must contain the",
"nameFig = 'Position.png' or nameFig = 'linearVelocity.eps' import os nameFig = os.path.join(\"/content/Figures/\",nameFig) fig.savefig(nameFig,",
"def saveFig(fig,nameFig): # ------- the name must contain the figure format: # e.g.,",
"contain the figure format: # e.g., nameFig = 'Position.png' or nameFig = 'linearVelocity.eps'",
"------- the name must contain the figure format: # e.g., nameFig = 'Position.png'",
"must contain the figure format: # e.g., nameFig = 'Position.png' or nameFig =",
"= 'linearVelocity.eps' import os if not(os.path.isdir('../content/Figures/')): os.mkdir('../content/Figures/') nameFig = os.path.join(\"../content/Figures/\",nameFig) fig.savefig(nameFig, dpi=600, bbox_inches='tight')",
"= 'Position.png' or nameFig = 'linearVelocity.eps' import os nameFig = os.path.join(\"/content/Figures/\",nameFig) fig.savefig(nameFig, dpi=300,",
"figure format: # e.g., nameFig = 'Position.png' or nameFig = 'linearVelocity.eps' import os",
"e.g., nameFig = 'Position.png' or nameFig = 'linearVelocity.eps' import os if not(os.path.isdir('../content/Figures/')): os.mkdir('../content/Figures/')",
"#--- # Save Figure: def saveFig(fig,nameFig): # ------- the name must contain the",
"= 'Position.png' or nameFig = 'linearVelocity.eps' import os if not(os.path.isdir('../content/Figures/')): os.mkdir('../content/Figures/') nameFig =",
"format: # e.g., nameFig = 'Position.png' or nameFig = 'linearVelocity.eps' import os nameFig",
"# e.g., nameFig = 'Position.png' or nameFig = 'linearVelocity.eps' import os nameFig =",
"bbox_inches='tight') #--- # Save Figure: def saveFig(fig,nameFig): # ------- the name must contain",
"'linearVelocity.eps' import os nameFig = os.path.join(\"/content/Figures/\",nameFig) fig.savefig(nameFig, dpi=300, bbox_inches='tight') #--- # Save Figure:",
"saveFig(fig,nameFig): # ------- the name must contain the figure format: # e.g., nameFig",
"nameFig = 'Position.png' or nameFig = 'linearVelocity.eps' import os if not(os.path.isdir('../content/Figures/')): os.mkdir('../content/Figures/') nameFig",
"e.g., nameFig = 'Position.png' or nameFig = 'linearVelocity.eps' import os nameFig = os.path.join(\"/content/Figures/\",nameFig)",
"# Save Figure: def saveFig_old(fig,nameFig): # ------- the name must contain the figure",
"Figure: def saveFig(fig,nameFig): # ------- the name must contain the figure format: #",
"# e.g., nameFig = 'Position.png' or nameFig = 'linearVelocity.eps' import os if not(os.path.isdir('../content/Figures/')):",
"Figure: def saveFig_old(fig,nameFig): # ------- the name must contain the figure format: #",
"os nameFig = os.path.join(\"/content/Figures/\",nameFig) fig.savefig(nameFig, dpi=300, bbox_inches='tight') #--- # Save Figure: def saveFig(fig,nameFig):",
"nameFig = 'linearVelocity.eps' import os if not(os.path.isdir('../content/Figures/')): os.mkdir('../content/Figures/') nameFig = os.path.join(\"../content/Figures/\",nameFig) fig.savefig(nameFig, dpi=600,",
"saveFig_old(fig,nameFig): # ------- the name must contain the figure format: # e.g., nameFig",
"name must contain the figure format: # e.g., nameFig = 'Position.png' or nameFig",
"or nameFig = 'linearVelocity.eps' import os if not(os.path.isdir('../content/Figures/')): os.mkdir('../content/Figures/') nameFig = os.path.join(\"../content/Figures/\",nameFig) fig.savefig(nameFig,",
"'Position.png' or nameFig = 'linearVelocity.eps' import os nameFig = os.path.join(\"/content/Figures/\",nameFig) fig.savefig(nameFig, dpi=300, bbox_inches='tight')",
"nameFig = 'linearVelocity.eps' import os nameFig = os.path.join(\"/content/Figures/\",nameFig) fig.savefig(nameFig, dpi=300, bbox_inches='tight') #--- #",
"def saveFig_old(fig,nameFig): # ------- the name must contain the figure format: # e.g.,",
"'Position.png' or nameFig = 'linearVelocity.eps' import os if not(os.path.isdir('../content/Figures/')): os.mkdir('../content/Figures/') nameFig = os.path.join(\"../content/Figures/\",nameFig)",
"Save Figure: def saveFig_old(fig,nameFig): # ------- the name must contain the figure format:",
"import os nameFig = os.path.join(\"/content/Figures/\",nameFig) fig.savefig(nameFig, dpi=300, bbox_inches='tight') #--- # Save Figure: def",
"# Save Figure: def saveFig(fig,nameFig): # ------- the name must contain the figure",
"<gh_stars>0 #--- # Save Figure: def saveFig_old(fig,nameFig): # ------- the name must contain",
"format: # e.g., nameFig = 'Position.png' or nameFig = 'linearVelocity.eps' import os if",
"or nameFig = 'linearVelocity.eps' import os nameFig = os.path.join(\"/content/Figures/\",nameFig) fig.savefig(nameFig, dpi=300, bbox_inches='tight') #---",
"fig.savefig(nameFig, dpi=300, bbox_inches='tight') #--- # Save Figure: def saveFig(fig,nameFig): # ------- the name",
"= 'linearVelocity.eps' import os nameFig = os.path.join(\"/content/Figures/\",nameFig) fig.savefig(nameFig, dpi=300, bbox_inches='tight') #--- # Save",
"Save Figure: def saveFig(fig,nameFig): # ------- the name must contain the figure format:",
"os.path.join(\"/content/Figures/\",nameFig) fig.savefig(nameFig, dpi=300, bbox_inches='tight') #--- # Save Figure: def saveFig(fig,nameFig): # ------- the",
"# ------- the name must contain the figure format: # e.g., nameFig =",
"= os.path.join(\"/content/Figures/\",nameFig) fig.savefig(nameFig, dpi=300, bbox_inches='tight') #--- # Save Figure: def saveFig(fig,nameFig): # -------",
"dpi=300, bbox_inches='tight') #--- # Save Figure: def saveFig(fig,nameFig): # ------- the name must"
] |
[
"elif (layer.strip() == \"t2m\"): ylab = 'T2m (K)' elif (layer.strip() == \"d2m\"): ylab",
"\"u10\"): ylab = 'windspeed u component (m s-1)' elif (layer.strip() == \"v10\"): ylab",
"getPixelVals(netcdffile, layer, longitude, latitude): \"\"\" Function to query pixels values for a given",
"West, South, East. Default: global 'year': str(i_year), 'month': [ '01', '02', '03', '04',",
"== \"t2m\"): ylab = 'T2m (K)' elif (layer.strip() == \"d2m\"): ylab = 'Dewpoint",
"# ylab = 'Surface air pressure (Pa)' elif (layer.strip() == \"tp\"): ylab =",
"arr[arr == fillva] = np.nan arr[arr == -fillva] = np.nan if layer ==",
"'01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', ],",
"north, west, south, east, ], # North, West, South, East. Default: global 'year':",
"NETCDF file and convert to Python datetime ncfile = netCDF4.Dataset(netcdffile, 'r') tim =",
"'26', '27', '28', '29', '30', '31', ], 'time': [ '00:00', '01:00', '02:00', '03:00',",
"\"\"\" fig, ax = plt.subplots() ax.plot_date(time_convert, array, 'g-') if (layer.strip() == \"ssrd\"): ylab",
"= np.nan arr[arr == -nodata] = np.nan # Fill in value is sometimes",
"], 'format': 'netcdf', }, out_dir + '/ERA5_' + prefix + '_' + str(i_year)",
"s-1)' elif (layer.strip() == \"v10\"): ylab = 'windspeed v component (m s-1)' elif",
"nodata, fillva) lat, lon = nc.variables['latitude'], nc.variables['longitude'] # extract lat/lon values (in degrees)",
"# Select all of the temporal instances of the pixel arr = nc.variables[layer][:,",
"array, 'g-') if (layer.strip() == \"ssrd\"): ylab = 'surface downwelling shortwave flux in",
"[ '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12',",
"'08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00',",
"y in range(dist_grid.shape[0]): if dist_grid[y][x] == minval: ix_min = x iy_min = y",
"plot the array data with time \"\"\" fig, ax = plt.subplots() ax.plot_date(time_convert, array,",
"distance_2d(longitude, latitude, xx, yy) minval = dist_grid.min() for x in range(dist_grid.shape[1]): for y",
"nodata = int(dict_nc['missing_value']) fillva = int(dict_nc['_FillValue']) # print(offset, scale, nodata, fillva) lat, lon",
"temperature to actual vapour pressure (hPa) \"\"\" return (0.6108 * np.exp((17.27 * d2m)",
"in air (J m-2)' elif (layer.strip() == \"u10\"): ylab = 'windspeed u component",
"= netCDF4.num2date(tim[:], tim.units, tim.calendar, only_use_cftime_datetimes=False) return time_convert def getPixelVals(netcdffile, layer, longitude, latitude): \"\"\"",
"# fig.savefig(\"test.png\") plt.show() def d2m2eact(d2m): \"\"\" Converts dew point temperature to actual vapour",
"layer, longitude, latitude): \"\"\" Function to query pixels values for a given layer",
"xgrid, ygrid): #print(longitude, latitude) #print(xgrid, xgrid.dtype) #print(ygrid, ygrid.dtype) return np.hypot(np.subtract(xgrid,np.float(longitude)), np.subtract(ygrid,np.float(latitude))) dist_grid =",
"(Pa)' elif (layer.strip() == \"tp\"): ylab = 'Total precipitation (m)' else: ylab =",
"= lon[:] #print(lonvals.shape) #print(latvals.shape) xl = np.linspace(lonvals.min(), lonvals.max(), lonvals.shape[0]) yl = np.linspace(latvals.min(), latvals.max(),",
"iy_min, ix_min] if layer == 'ssrd': arr[arr == 0] = np.nan # Replace",
"[ 'surface_solar_radiation_downwards', '10m_u_component_of_wind', '10m_v_component_of_wind', '2m_temperature', 'surface_pressure', 'total_precipitation', '2m_dewpoint_temperature' # 'evaporation', 'potential_evaporation', # 'snow_density',",
"#print(xgrid, xgrid.dtype) #print(ygrid, ygrid.dtype) return np.hypot(np.subtract(xgrid,np.float(longitude)), np.subtract(ygrid,np.float(latitude))) dist_grid = distance_2d(longitude, latitude, xx, yy)",
"with NAN arr[arr == nodata] = np.nan arr[arr == -nodata] = np.nan #",
"'minimum_total_precipitation_rate_since_previous_post_processing', # 'orography', 'potential_evaporation', 'precipitation_type', # 'snow_density', 'snow_depth', 'soil_temperature_level_1', # 'soil_temperature_level_2', 'soil_temperature_level_3', 'soil_temperature_level_4',",
"(in degrees) to numpy arrays latvals = lat[:] lonvals = lon[:] #print(lonvals.shape) #print(latvals.shape)",
"for a given layer at a given Lat/long \"\"\" nc = netCDF4.Dataset(netcdffile) dict_nc",
"Function to query pixels values for a given layer at a given Lat/long",
"yl, sparse=True) def distance_2d(longitude, latitude, xgrid, ygrid): #print(longitude, latitude) #print(xgrid, xgrid.dtype) #print(ygrid, ygrid.dtype)",
"elif (layer.strip() == \"u10\"): ylab = 'windspeed u component (m s-1)' elif (layer.strip()",
"#print(ygrid, ygrid.dtype) return np.hypot(np.subtract(xgrid,np.float(longitude)), np.subtract(ygrid,np.float(latitude))) dist_grid = distance_2d(longitude, latitude, xx, yy) minval =",
"# Rescale the data array = offset + arr * scale # Return",
"to actual vapour pressure (hPa) \"\"\" return (0.6108 * np.exp((17.27 * d2m) /",
"= y # Select all of the temporal instances of the pixel arr",
"'07', '08', '09', '10', '11', '12', ], 'day': [ '01', '02', '03', '04',",
"'22:00', '23:00', ], 'format': 'netcdf', }, out_dir + '/ERA5_' + prefix + '_'",
"the time array from NETCDF file and convert to Python datetime ncfile =",
"== \"v10\"): ylab = 'windspeed v component (m s-1)' elif (layer.strip() == \"t2m\"):",
"' + ylab) ax.grid() # fig.savefig(\"test.png\") plt.show() def d2m2eact(d2m): \"\"\" Converts dew point",
"to extract the time component of a netCDF file \"\"\" # Get the",
"scale # Return the array return array def plotLayer(layer, time_convert, array): \"\"\" Function",
"'03', '04', '05', '06', '07', '08', '09', '10', '11', '12', ], 'day': [",
"= ncfile.variables['time'] # do not cast to numpy array yet time_convert = netCDF4.num2date(tim[:],",
"\"t2m\"): ylab = 'T2m (K)' elif (layer.strip() == \"d2m\"): ylab = 'Dewpoint T2m",
"dew point temperature to actual vapour pressure (hPa) \"\"\" return (0.6108 * np.exp((17.27",
"+ '_' + str(i_year) + '.nc') def getTimeNetcdf(netcdffile): \"\"\" Function to extract the",
"'snow_density', 'snow_depth' # '10m_u_component_of_wind', '10m_v_component_of_wind', '2m_dewpoint_temperature', # '2m_temperature', 'angle_of_sub_gridscale_orography', # 'anisotropy_of_sub_gridscale_orography', # 'evaporation',",
"Extract NoData Value from layer nodata = int(dict_nc['missing_value']) fillva = int(dict_nc['_FillValue']) # print(offset,",
"], 'area': [ north, west, south, east, ], # North, West, South, East.",
"'18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30',",
"fillva = int(dict_nc['_FillValue']) # print(offset, scale, nodata, fillva) lat, lon = nc.variables['latitude'], nc.variables['longitude']",
"'31', ], 'time': [ '00:00', '01:00', '02:00', '03:00', '04:00', '05:00', '06:00', '07:00', '08:00',",
"== 'ssrd': return arr # Rescale the data array = offset + arr",
"Converts dew point temperature to actual vapour pressure (hPa) \"\"\" return (0.6108 *",
"prefix + '_' + str(i_year) + '.nc') def getTimeNetcdf(netcdffile): \"\"\" Function to extract",
"'ssrd': arr[arr == 0] = np.nan # Replace nodata (often -32767) with NAN",
"= cdsapi.Client() c.retrieve( 'reanalysis-era5-single-levels', { 'product_type': 'reanalysis', 'variable': [ 'surface_solar_radiation_downwards', '10m_u_component_of_wind', '10m_v_component_of_wind', '2m_temperature',",
"'snow_density', 'snow_depth', 'soil_temperature_level_1', # 'soil_temperature_level_2', 'soil_temperature_level_3', 'soil_temperature_level_4', # 'soil_type', 'surface_pressure', 'surface_solar_radiation_downwards', # 'total_column_snow_water',",
"'04:00', '05:00', '06:00', '07:00', '08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00',",
"the offset and scale from netcdf file offset = float(dict_nc['add_offset']) scale = float(dict_nc['scale_factor'])",
"Function to plot the array data with time \"\"\" fig, ax = plt.subplots()",
"v component (m s-1)' elif (layer.strip() == \"t2m\"): ylab = 'T2m (K)' elif",
"'snow_depth' # '10m_u_component_of_wind', '10m_v_component_of_wind', '2m_dewpoint_temperature', # '2m_temperature', 'angle_of_sub_gridscale_orography', # 'anisotropy_of_sub_gridscale_orography', # 'evaporation', 'land_sea_mask',",
"(m s-1)' elif (layer.strip() == \"v10\"): ylab = 'windspeed v component (m s-1)'",
"'soil_temperature_level_1', # 'soil_temperature_level_2', 'soil_temperature_level_3', 'soil_temperature_level_4', # 'soil_type', 'surface_pressure', 'surface_solar_radiation_downwards', # 'total_column_snow_water', 'total_precipitation', 'volumetric_soil_water_layer_1',",
"return arr # Rescale the data array = offset + arr * scale",
"latvals = lat[:] lonvals = lon[:] #print(lonvals.shape) #print(latvals.shape) xl = np.linspace(lonvals.min(), lonvals.max(), lonvals.shape[0])",
"Fill values to NAN arr[arr == fillva] = np.nan arr[arr == -fillva] =",
"else: ylab = 'undefined product' ax.set(xlabel='time', ylabel=ylab, title='ERA5 ' + ylab) ax.grid() #",
"= lat[:] lonvals = lon[:] #print(lonvals.shape) #print(latvals.shape) xl = np.linspace(lonvals.min(), lonvals.max(), lonvals.shape[0]) yl",
"arr * scale # Return the array return array def plotLayer(layer, time_convert, array):",
"nc.variables['longitude'] # extract lat/lon values (in degrees) to numpy arrays latvals = lat[:]",
"north, west, south, east): c = cdsapi.Client() c.retrieve( 'reanalysis-era5-single-levels', { 'product_type': 'reanalysis', 'variable':",
"ylab = 'windspeed v component (m s-1)' elif (layer.strip() == \"t2m\"): ylab =",
"#print(longitude, latitude) #print(xgrid, xgrid.dtype) #print(ygrid, ygrid.dtype) return np.hypot(np.subtract(xgrid,np.float(longitude)), np.subtract(ygrid,np.float(latitude))) dist_grid = distance_2d(longitude, latitude,",
"= nc.variables[layer][:, 0, iy_min, ix_min] if layer == 'ssrd': arr[arr == 0] =",
"'total_precipitation', '2m_dewpoint_temperature' # 'evaporation', 'potential_evaporation', # 'snow_density', 'snow_depth' # '10m_u_component_of_wind', '10m_v_component_of_wind', '2m_dewpoint_temperature', #",
"'_' + str(i_year) + '.nc') def getTimeNetcdf(netcdffile): \"\"\" Function to extract the time",
"= 'Surface air pressure (Pa)' elif (layer.strip() == \"tp\"): ylab = 'Total precipitation",
"Python datetime ncfile = netCDF4.Dataset(netcdffile, 'r') tim = ncfile.variables['time'] # do not cast",
"arr = nc.variables[layer][:, 0, iy_min, ix_min] if layer == 'ssrd': arr[arr == 0]",
"-nodata] = np.nan # Fill in value is sometimes -32766, but not documented...",
"latvals.shape[0]) xx, yy = np.meshgrid(xl, yl, sparse=True) def distance_2d(longitude, latitude, xgrid, ygrid): #print(longitude,",
"the data array = offset + arr * scale # Return the array",
"'17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29',",
"sometimes -32766, but not documented... arr[arr == 32766] = np.nan # Fill values",
"def plotLayer(layer, time_convert, array): \"\"\" Function to plot the array data with time",
"latitude, xgrid, ygrid): #print(longitude, latitude) #print(xgrid, xgrid.dtype) #print(ygrid, ygrid.dtype) return np.hypot(np.subtract(xgrid,np.float(longitude)), np.subtract(ygrid,np.float(latitude))) dist_grid",
"{ 'product_type': 'reanalysis', 'variable': [ 'surface_solar_radiation_downwards', '10m_u_component_of_wind', '10m_v_component_of_wind', '2m_temperature', 'surface_pressure', 'total_precipitation', '2m_dewpoint_temperature' #",
"'day': [ '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11',",
"np.nan arr[arr == -fillva] = np.nan if layer == 'ssrd': return arr #",
"time component of a netCDF file \"\"\" # Get the time array from",
"ax = plt.subplots() ax.plot_date(time_convert, array, 'g-') if (layer.strip() == \"ssrd\"): ylab = 'surface",
"of a netCDF file \"\"\" # Get the time array from NETCDF file",
"'time': [ '00:00', '01:00', '02:00', '03:00', '04:00', '05:00', '06:00', '07:00', '08:00', '09:00', '10:00',",
"minval: ix_min = x iy_min = y # Select all of the temporal",
"== nodata] = np.nan arr[arr == -nodata] = np.nan # Fill in value",
"and convert to Python datetime ncfile = netCDF4.Dataset(netcdffile, 'r') tim = ncfile.variables['time'] #",
"downwelling shortwave flux in air (J m-2)' elif (layer.strip() == \"u10\"): ylab =",
"'undefined product' ax.set(xlabel='time', ylabel=ylab, title='ERA5 ' + ylab) ax.grid() # fig.savefig(\"test.png\") plt.show() def",
"to Python datetime ncfile = netCDF4.Dataset(netcdffile, 'r') tim = ncfile.variables['time'] # do not",
"# Return the array return array def plotLayer(layer, time_convert, array): \"\"\" Function to",
"m-2)' elif (layer.strip() == \"u10\"): ylab = 'windspeed u component (m s-1)' elif",
"= nc[layer].__dict__ # Extract the offset and scale from netcdf file offset =",
"array = offset + arr * scale # Return the array return array",
"], # North, West, South, East. Default: global 'year': str(i_year), 'month': [ '01',",
"# '10m_u_component_of_wind', '10m_v_component_of_wind', '2m_dewpoint_temperature', # '2m_temperature', 'angle_of_sub_gridscale_orography', # 'anisotropy_of_sub_gridscale_orography', # 'evaporation', 'land_sea_mask', #",
"= np.nan # Replace nodata (often -32767) with NAN arr[arr == nodata] =",
"], 'day': [ '01', '02', '03', '04', '05', '06', '07', '08', '09', '10',",
"# 'volumetric_soil_water_layer_4', ], 'area': [ north, west, south, east, ], # North, West,",
"array): \"\"\" Function to plot the array data with time \"\"\" fig, ax",
"(layer.strip() == \"ssrd\"): ylab = 'surface downwelling shortwave flux in air (J m-2)'",
"T2m (K)' #elif (layer.strip() == \"sp\"): # ylab = 'Surface air pressure (Pa)'",
"'Total precipitation (m)' else: ylab = 'undefined product' ax.set(xlabel='time', ylabel=ylab, title='ERA5 ' +",
"xgrid.dtype) #print(ygrid, ygrid.dtype) return np.hypot(np.subtract(xgrid,np.float(longitude)), np.subtract(ygrid,np.float(latitude))) dist_grid = distance_2d(longitude, latitude, xx, yy) minval",
"'2m_dewpoint_temperature', # '2m_temperature', 'angle_of_sub_gridscale_orography', # 'anisotropy_of_sub_gridscale_orography', # 'evaporation', 'land_sea_mask', # 'maximum_total_precipitation_rate_since_previous_post_processing', # 'mean_evaporation_rate',",
"longitude, latitude): \"\"\" Function to query pixels values for a given layer at",
"], 'time': [ '00:00', '01:00', '02:00', '03:00', '04:00', '05:00', '06:00', '07:00', '08:00', '09:00',",
"'potential_evaporation', # 'snow_density', 'snow_depth' # '10m_u_component_of_wind', '10m_v_component_of_wind', '2m_dewpoint_temperature', # '2m_temperature', 'angle_of_sub_gridscale_orography', # 'anisotropy_of_sub_gridscale_orography',",
"file and convert to Python datetime ncfile = netCDF4.Dataset(netcdffile, 'r') tim = ncfile.variables['time']",
"(layer.strip() == \"v10\"): ylab = 'windspeed v component (m s-1)' elif (layer.strip() ==",
"'23:00', ], 'format': 'netcdf', }, out_dir + '/ERA5_' + prefix + '_' +",
"c.retrieve( 'reanalysis-era5-single-levels', { 'product_type': 'reanalysis', 'variable': [ 'surface_solar_radiation_downwards', '10m_u_component_of_wind', '10m_v_component_of_wind', '2m_temperature', 'surface_pressure', 'total_precipitation',",
"float(dict_nc['add_offset']) scale = float(dict_nc['scale_factor']) # Extract NoData Value from layer nodata = int(dict_nc['missing_value'])",
"'orography', 'potential_evaporation', 'precipitation_type', # 'snow_density', 'snow_depth', 'soil_temperature_level_1', # 'soil_temperature_level_2', 'soil_temperature_level_3', 'soil_temperature_level_4', # 'soil_type',",
"a given Lat/long \"\"\" nc = netCDF4.Dataset(netcdffile) dict_nc = nc[layer].__dict__ # Extract the",
"pixel arr = nc.variables[layer][:, 0, iy_min, ix_min] if layer == 'ssrd': arr[arr ==",
"to numpy arrays latvals = lat[:] lonvals = lon[:] #print(lonvals.shape) #print(latvals.shape) xl =",
"c = cdsapi.Client() c.retrieve( 'reanalysis-era5-single-levels', { 'product_type': 'reanalysis', 'variable': [ 'surface_solar_radiation_downwards', '10m_u_component_of_wind', '10m_v_component_of_wind',",
"range(dist_grid.shape[1]): for y in range(dist_grid.shape[0]): if dist_grid[y][x] == minval: ix_min = x iy_min",
"lat/lon values (in degrees) to numpy arrays latvals = lat[:] lonvals = lon[:]",
"the array return array def plotLayer(layer, time_convert, array): \"\"\" Function to plot the",
"time_convert def getPixelVals(netcdffile, layer, longitude, latitude): \"\"\" Function to query pixels values for",
"'22', '23', '24', '25', '26', '27', '28', '29', '30', '31', ], 'time': [",
"and scale from netcdf file offset = float(dict_nc['add_offset']) scale = float(dict_nc['scale_factor']) # Extract",
"East. Default: global 'year': str(i_year), 'month': [ '01', '02', '03', '04', '05', '06',",
"str(i_year) + '.nc') def getTimeNetcdf(netcdffile): \"\"\" Function to extract the time component of",
"'06', '07', '08', '09', '10', '11', '12', ], 'day': [ '01', '02', '03',",
"'area': [ north, west, south, east, ], # North, West, South, East. Default:",
"NAN arr[arr == nodata] = np.nan arr[arr == -nodata] = np.nan # Fill",
"'13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25',",
"'2m_temperature', 'angle_of_sub_gridscale_orography', # 'anisotropy_of_sub_gridscale_orography', # 'evaporation', 'land_sea_mask', # 'maximum_total_precipitation_rate_since_previous_post_processing', # 'mean_evaporation_rate', 'mean_potential_evaporation_rate', #",
"xx, yy = np.meshgrid(xl, yl, sparse=True) def distance_2d(longitude, latitude, xgrid, ygrid): #print(longitude, latitude)",
"= plt.subplots() ax.plot_date(time_convert, array, 'g-') if (layer.strip() == \"ssrd\"): ylab = 'surface downwelling",
"'netcdf', }, out_dir + '/ERA5_' + prefix + '_' + str(i_year) + '.nc')",
"as np import matplotlib.pyplot as plt def download_ERA5_bbox(i_year, out_dir, prefix, north, west, south,",
"# Get the time array from NETCDF file and convert to Python datetime",
"layer == 'ssrd': return arr # Rescale the data array = offset +",
"with time \"\"\" fig, ax = plt.subplots() ax.plot_date(time_convert, array, 'g-') if (layer.strip() ==",
"Value from layer nodata = int(dict_nc['missing_value']) fillva = int(dict_nc['_FillValue']) # print(offset, scale, nodata,",
"'10m_v_component_of_wind', '2m_temperature', 'surface_pressure', 'total_precipitation', '2m_dewpoint_temperature' # 'evaporation', 'potential_evaporation', # 'snow_density', 'snow_depth' # '10m_u_component_of_wind',",
"'soil_temperature_level_3', 'soil_temperature_level_4', # 'soil_type', 'surface_pressure', 'surface_solar_radiation_downwards', # 'total_column_snow_water', 'total_precipitation', 'volumetric_soil_water_layer_1', # 'volumetric_soil_water_layer_2', 'volumetric_soil_water_layer_3',",
"'03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15',",
"'16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28',",
"lonvals.max(), lonvals.shape[0]) yl = np.linspace(latvals.min(), latvals.max(), latvals.shape[0]) xx, yy = np.meshgrid(xl, yl, sparse=True)",
"'soil_temperature_level_4', # 'soil_type', 'surface_pressure', 'surface_solar_radiation_downwards', # 'total_column_snow_water', 'total_precipitation', 'volumetric_soil_water_layer_1', # 'volumetric_soil_water_layer_2', 'volumetric_soil_water_layer_3', #",
"'2m_dewpoint_temperature' # 'evaporation', 'potential_evaporation', # 'snow_density', 'snow_depth' # '10m_u_component_of_wind', '10m_v_component_of_wind', '2m_dewpoint_temperature', # '2m_temperature',",
"-32766, but not documented... arr[arr == 32766] = np.nan # Fill values to",
"ix_min] if layer == 'ssrd': arr[arr == 0] = np.nan # Replace nodata",
"'08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20',",
"'29', '30', '31', ], 'time': [ '00:00', '01:00', '02:00', '03:00', '04:00', '05:00', '06:00',",
"to numpy array yet time_convert = netCDF4.num2date(tim[:], tim.units, tim.calendar, only_use_cftime_datetimes=False) return time_convert def",
"in value is sometimes -32766, but not documented... arr[arr == 32766] = np.nan",
"+ prefix + '_' + str(i_year) + '.nc') def getTimeNetcdf(netcdffile): \"\"\" Function to",
"lonvals = lon[:] #print(lonvals.shape) #print(latvals.shape) xl = np.linspace(lonvals.min(), lonvals.max(), lonvals.shape[0]) yl = np.linspace(latvals.min(),",
"np.nan # Replace nodata (often -32767) with NAN arr[arr == nodata] = np.nan",
"air pressure (Pa)' elif (layer.strip() == \"tp\"): ylab = 'Total precipitation (m)' else:",
"'23', '24', '25', '26', '27', '28', '29', '30', '31', ], 'time': [ '00:00',",
"'volumetric_soil_water_layer_1', # 'volumetric_soil_water_layer_2', 'volumetric_soil_water_layer_3', # 'volumetric_soil_water_layer_4', ], 'area': [ north, west, south, east,",
"a netCDF file \"\"\" # Get the time array from NETCDF file and",
"scale from netcdf file offset = float(dict_nc['add_offset']) scale = float(dict_nc['scale_factor']) # Extract NoData",
"np import matplotlib.pyplot as plt def download_ERA5_bbox(i_year, out_dir, prefix, north, west, south, east):",
"NAN arr[arr == fillva] = np.nan arr[arr == -fillva] = np.nan if layer",
"dist_grid = distance_2d(longitude, latitude, xx, yy) minval = dist_grid.min() for x in range(dist_grid.shape[1]):",
"(layer.strip() == \"sp\"): # ylab = 'Surface air pressure (Pa)' elif (layer.strip() ==",
"'25', '26', '27', '28', '29', '30', '31', ], 'time': [ '00:00', '01:00', '02:00',",
"'20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', ],",
"nc = netCDF4.Dataset(netcdffile) dict_nc = nc[layer].__dict__ # Extract the offset and scale from",
"#print(latvals.shape) xl = np.linspace(lonvals.min(), lonvals.max(), lonvals.shape[0]) yl = np.linspace(latvals.min(), latvals.max(), latvals.shape[0]) xx, yy",
"data with time \"\"\" fig, ax = plt.subplots() ax.plot_date(time_convert, array, 'g-') if (layer.strip()",
"'28', '29', '30', '31', ], 'time': [ '00:00', '01:00', '02:00', '03:00', '04:00', '05:00',",
"ylab = 'windspeed u component (m s-1)' elif (layer.strip() == \"v10\"): ylab =",
"latvals.max(), latvals.shape[0]) xx, yy = np.meshgrid(xl, yl, sparse=True) def distance_2d(longitude, latitude, xgrid, ygrid):",
"offset + arr * scale # Return the array return array def plotLayer(layer,",
"(m s-1)' elif (layer.strip() == \"t2m\"): ylab = 'T2m (K)' elif (layer.strip() ==",
"Lat/long \"\"\" nc = netCDF4.Dataset(netcdffile) dict_nc = nc[layer].__dict__ # Extract the offset and",
"arr # Rescale the data array = offset + arr * scale #",
"'T2m (K)' elif (layer.strip() == \"d2m\"): ylab = 'Dewpoint T2m (K)' #elif (layer.strip()",
"'04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16',",
"south, east): c = cdsapi.Client() c.retrieve( 'reanalysis-era5-single-levels', { 'product_type': 'reanalysis', 'variable': [ 'surface_solar_radiation_downwards',",
"North, West, South, East. Default: global 'year': str(i_year), 'month': [ '01', '02', '03',",
"# 'soil_type', 'surface_pressure', 'surface_solar_radiation_downwards', # 'total_column_snow_water', 'total_precipitation', 'volumetric_soil_water_layer_1', # 'volumetric_soil_water_layer_2', 'volumetric_soil_water_layer_3', # 'volumetric_soil_water_layer_4',",
"(often -32767) with NAN arr[arr == nodata] = np.nan arr[arr == -nodata] =",
"ygrid.dtype) return np.hypot(np.subtract(xgrid,np.float(longitude)), np.subtract(ygrid,np.float(latitude))) dist_grid = distance_2d(longitude, latitude, xx, yy) minval = dist_grid.min()",
"in range(dist_grid.shape[1]): for y in range(dist_grid.shape[0]): if dist_grid[y][x] == minval: ix_min = x",
"def distance_2d(longitude, latitude, xgrid, ygrid): #print(longitude, latitude) #print(xgrid, xgrid.dtype) #print(ygrid, ygrid.dtype) return np.hypot(np.subtract(xgrid,np.float(longitude)),",
"numpy arrays latvals = lat[:] lonvals = lon[:] #print(lonvals.shape) #print(latvals.shape) xl = np.linspace(lonvals.min(),",
"the array data with time \"\"\" fig, ax = plt.subplots() ax.plot_date(time_convert, array, 'g-')",
"but not documented... arr[arr == 32766] = np.nan # Fill values to NAN",
"all of the temporal instances of the pixel arr = nc.variables[layer][:, 0, iy_min,",
"South, East. Default: global 'year': str(i_year), 'month': [ '01', '02', '03', '04', '05',",
"\"\"\" Function to plot the array data with time \"\"\" fig, ax =",
"numpy as np import matplotlib.pyplot as plt def download_ERA5_bbox(i_year, out_dir, prefix, north, west,",
"sparse=True) def distance_2d(longitude, latitude, xgrid, ygrid): #print(longitude, latitude) #print(xgrid, xgrid.dtype) #print(ygrid, ygrid.dtype) return",
"pixels values for a given layer at a given Lat/long \"\"\" nc =",
"Get the time array from NETCDF file and convert to Python datetime ncfile",
"Fill in value is sometimes -32766, but not documented... arr[arr == 32766] =",
"'volumetric_soil_water_layer_3', # 'volumetric_soil_water_layer_4', ], 'area': [ north, west, south, east, ], # North,",
"x iy_min = y # Select all of the temporal instances of the",
"= np.nan # Fill in value is sometimes -32766, but not documented... arr[arr",
"if layer == 'ssrd': arr[arr == 0] = np.nan # Replace nodata (often",
"xx, yy) minval = dist_grid.min() for x in range(dist_grid.shape[1]): for y in range(dist_grid.shape[0]):",
"== minval: ix_min = x iy_min = y # Select all of the",
"== 0] = np.nan # Replace nodata (often -32767) with NAN arr[arr ==",
"fillva] = np.nan arr[arr == -fillva] = np.nan if layer == 'ssrd': return",
"[ north, west, south, east, ], # North, West, South, East. Default: global",
"= float(dict_nc['scale_factor']) # Extract NoData Value from layer nodata = int(dict_nc['missing_value']) fillva =",
"'16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00', ], 'format': 'netcdf', }, out_dir",
"# print(offset, scale, nodata, fillva) lat, lon = nc.variables['latitude'], nc.variables['longitude'] # extract lat/lon",
"east): c = cdsapi.Client() c.retrieve( 'reanalysis-era5-single-levels', { 'product_type': 'reanalysis', 'variable': [ 'surface_solar_radiation_downwards', '10m_u_component_of_wind',",
"= 'Dewpoint T2m (K)' #elif (layer.strip() == \"sp\"): # ylab = 'Surface air",
"# 'snow_density', 'snow_depth' # '10m_u_component_of_wind', '10m_v_component_of_wind', '2m_dewpoint_temperature', # '2m_temperature', 'angle_of_sub_gridscale_orography', # 'anisotropy_of_sub_gridscale_orography', #",
"'surface_solar_radiation_downwards', '10m_u_component_of_wind', '10m_v_component_of_wind', '2m_temperature', 'surface_pressure', 'total_precipitation', '2m_dewpoint_temperature' # 'evaporation', 'potential_evaporation', # 'snow_density', 'snow_depth'",
"# 'evaporation', 'potential_evaporation', # 'snow_density', 'snow_depth' # '10m_u_component_of_wind', '10m_v_component_of_wind', '2m_dewpoint_temperature', # '2m_temperature', 'angle_of_sub_gridscale_orography',",
"'10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22',",
"numpy array yet time_convert = netCDF4.num2date(tim[:], tim.units, tim.calendar, only_use_cftime_datetimes=False) return time_convert def getPixelVals(netcdffile,",
"'.nc') def getTimeNetcdf(netcdffile): \"\"\" Function to extract the time component of a netCDF",
"from netcdf file offset = float(dict_nc['add_offset']) scale = float(dict_nc['scale_factor']) # Extract NoData Value",
"'20:00', '21:00', '22:00', '23:00', ], 'format': 'netcdf', }, out_dir + '/ERA5_' + prefix",
"== 'ssrd': arr[arr == 0] = np.nan # Replace nodata (often -32767) with",
"time \"\"\" fig, ax = plt.subplots() ax.plot_date(time_convert, array, 'g-') if (layer.strip() == \"ssrd\"):",
"# 'snow_density', 'snow_depth', 'soil_temperature_level_1', # 'soil_temperature_level_2', 'soil_temperature_level_3', 'soil_temperature_level_4', # 'soil_type', 'surface_pressure', 'surface_solar_radiation_downwards', #",
"download_ERA5_bbox(i_year, out_dir, prefix, north, west, south, east): c = cdsapi.Client() c.retrieve( 'reanalysis-era5-single-levels', {",
"'24', '25', '26', '27', '28', '29', '30', '31', ], 'time': [ '00:00', '01:00',",
"'/ERA5_' + prefix + '_' + str(i_year) + '.nc') def getTimeNetcdf(netcdffile): \"\"\" Function",
"'01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13',",
"elif (layer.strip() == \"v10\"): ylab = 'windspeed v component (m s-1)' elif (layer.strip()",
"'10m_v_component_of_wind', '2m_dewpoint_temperature', # '2m_temperature', 'angle_of_sub_gridscale_orography', # 'anisotropy_of_sub_gridscale_orography', # 'evaporation', 'land_sea_mask', # 'maximum_total_precipitation_rate_since_previous_post_processing', #",
"fig.savefig(\"test.png\") plt.show() def d2m2eact(d2m): \"\"\" Converts dew point temperature to actual vapour pressure",
"precipitation (m)' else: ylab = 'undefined product' ax.set(xlabel='time', ylabel=ylab, title='ERA5 ' + ylab)",
"actual vapour pressure (hPa) \"\"\" return (0.6108 * np.exp((17.27 * d2m) / (d2m",
"array yet time_convert = netCDF4.num2date(tim[:], tim.units, tim.calendar, only_use_cftime_datetimes=False) return time_convert def getPixelVals(netcdffile, layer,",
"(m)' else: ylab = 'undefined product' ax.set(xlabel='time', ylabel=ylab, title='ERA5 ' + ylab) ax.grid()",
"'land_sea_mask', # 'maximum_total_precipitation_rate_since_previous_post_processing', # 'mean_evaporation_rate', 'mean_potential_evaporation_rate', # 'minimum_total_precipitation_rate_since_previous_post_processing', # 'orography', 'potential_evaporation', 'precipitation_type', #",
"values (in degrees) to numpy arrays latvals = lat[:] lonvals = lon[:] #print(lonvals.shape)",
"'05', '06', '07', '08', '09', '10', '11', '12', ], 'day': [ '01', '02',",
"'volumetric_soil_water_layer_2', 'volumetric_soil_water_layer_3', # 'volumetric_soil_water_layer_4', ], 'area': [ north, west, south, east, ], #",
"'15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00', ], 'format': 'netcdf', },",
"of the pixel arr = nc.variables[layer][:, 0, iy_min, ix_min] if layer == 'ssrd':",
"-fillva] = np.nan if layer == 'ssrd': return arr # Rescale the data",
"latitude) #print(xgrid, xgrid.dtype) #print(ygrid, ygrid.dtype) return np.hypot(np.subtract(xgrid,np.float(longitude)), np.subtract(ygrid,np.float(latitude))) dist_grid = distance_2d(longitude, latitude, xx,",
"s-1)' elif (layer.strip() == \"t2m\"): ylab = 'T2m (K)' elif (layer.strip() == \"d2m\"):",
"ylab) ax.grid() # fig.savefig(\"test.png\") plt.show() def d2m2eact(d2m): \"\"\" Converts dew point temperature to",
"\"\"\" Converts dew point temperature to actual vapour pressure (hPa) \"\"\" return (0.6108",
"'angle_of_sub_gridscale_orography', # 'anisotropy_of_sub_gridscale_orography', # 'evaporation', 'land_sea_mask', # 'maximum_total_precipitation_rate_since_previous_post_processing', # 'mean_evaporation_rate', 'mean_potential_evaporation_rate', # 'minimum_total_precipitation_rate_since_previous_post_processing',",
"array data with time \"\"\" fig, ax = plt.subplots() ax.plot_date(time_convert, array, 'g-') if",
"dist_grid.min() for x in range(dist_grid.shape[1]): for y in range(dist_grid.shape[0]): if dist_grid[y][x] == minval:",
"values to NAN arr[arr == fillva] = np.nan arr[arr == -fillva] = np.nan",
"(layer.strip() == \"u10\"): ylab = 'windspeed u component (m s-1)' elif (layer.strip() ==",
"# Replace nodata (often -32767) with NAN arr[arr == nodata] = np.nan arr[arr",
"fillva) lat, lon = nc.variables['latitude'], nc.variables['longitude'] # extract lat/lon values (in degrees) to",
"'18:00', '19:00', '20:00', '21:00', '22:00', '23:00', ], 'format': 'netcdf', }, out_dir + '/ERA5_'",
"= dist_grid.min() for x in range(dist_grid.shape[1]): for y in range(dist_grid.shape[0]): if dist_grid[y][x] ==",
"ylab = 'Total precipitation (m)' else: ylab = 'undefined product' ax.set(xlabel='time', ylabel=ylab, title='ERA5",
"cdsapi.Client() c.retrieve( 'reanalysis-era5-single-levels', { 'product_type': 'reanalysis', 'variable': [ 'surface_solar_radiation_downwards', '10m_u_component_of_wind', '10m_v_component_of_wind', '2m_temperature', 'surface_pressure',",
"== \"ssrd\"): ylab = 'surface downwelling shortwave flux in air (J m-2)' elif",
"'14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00', ], 'format': 'netcdf',",
"'soil_temperature_level_2', 'soil_temperature_level_3', 'soil_temperature_level_4', # 'soil_type', 'surface_pressure', 'surface_solar_radiation_downwards', # 'total_column_snow_water', 'total_precipitation', 'volumetric_soil_water_layer_1', # 'volumetric_soil_water_layer_2',",
"netCDF4 import cdsapi import numpy as np import matplotlib.pyplot as plt def download_ERA5_bbox(i_year,",
"# 'orography', 'potential_evaporation', 'precipitation_type', # 'snow_density', 'snow_depth', 'soil_temperature_level_1', # 'soil_temperature_level_2', 'soil_temperature_level_3', 'soil_temperature_level_4', #",
"extract lat/lon values (in degrees) to numpy arrays latvals = lat[:] lonvals =",
"of the temporal instances of the pixel arr = nc.variables[layer][:, 0, iy_min, ix_min]",
"'surface_solar_radiation_downwards', # 'total_column_snow_water', 'total_precipitation', 'volumetric_soil_water_layer_1', # 'volumetric_soil_water_layer_2', 'volumetric_soil_water_layer_3', # 'volumetric_soil_water_layer_4', ], 'area': [",
"lonvals.shape[0]) yl = np.linspace(latvals.min(), latvals.max(), latvals.shape[0]) xx, yy = np.meshgrid(xl, yl, sparse=True) def",
"== -fillva] = np.nan if layer == 'ssrd': return arr # Rescale the",
"return array def plotLayer(layer, time_convert, array): \"\"\" Function to plot the array data",
"'Surface air pressure (Pa)' elif (layer.strip() == \"tp\"): ylab = 'Total precipitation (m)'",
"if dist_grid[y][x] == minval: ix_min = x iy_min = y # Select all",
"component (m s-1)' elif (layer.strip() == \"t2m\"): ylab = 'T2m (K)' elif (layer.strip()",
"+ '.nc') def getTimeNetcdf(netcdffile): \"\"\" Function to extract the time component of a",
"== -nodata] = np.nan # Fill in value is sometimes -32766, but not",
"offset = float(dict_nc['add_offset']) scale = float(dict_nc['scale_factor']) # Extract NoData Value from layer nodata",
"= distance_2d(longitude, latitude, xx, yy) minval = dist_grid.min() for x in range(dist_grid.shape[1]): for",
"# 'anisotropy_of_sub_gridscale_orography', # 'evaporation', 'land_sea_mask', # 'maximum_total_precipitation_rate_since_previous_post_processing', # 'mean_evaporation_rate', 'mean_potential_evaporation_rate', # 'minimum_total_precipitation_rate_since_previous_post_processing', #",
"a given layer at a given Lat/long \"\"\" nc = netCDF4.Dataset(netcdffile) dict_nc =",
"'mean_evaporation_rate', 'mean_potential_evaporation_rate', # 'minimum_total_precipitation_rate_since_previous_post_processing', # 'orography', 'potential_evaporation', 'precipitation_type', # 'snow_density', 'snow_depth', 'soil_temperature_level_1', #",
"cdsapi import numpy as np import matplotlib.pyplot as plt def download_ERA5_bbox(i_year, out_dir, prefix,",
"lon = nc.variables['latitude'], nc.variables['longitude'] # extract lat/lon values (in degrees) to numpy arrays",
"file offset = float(dict_nc['add_offset']) scale = float(dict_nc['scale_factor']) # Extract NoData Value from layer",
"Rescale the data array = offset + arr * scale # Return the",
"NoData Value from layer nodata = int(dict_nc['missing_value']) fillva = int(dict_nc['_FillValue']) # print(offset, scale,",
"layer at a given Lat/long \"\"\" nc = netCDF4.Dataset(netcdffile) dict_nc = nc[layer].__dict__ #",
"lat, lon = nc.variables['latitude'], nc.variables['longitude'] # extract lat/lon values (in degrees) to numpy",
"plt def download_ERA5_bbox(i_year, out_dir, prefix, north, west, south, east): c = cdsapi.Client() c.retrieve(",
"= np.meshgrid(xl, yl, sparse=True) def distance_2d(longitude, latitude, xgrid, ygrid): #print(longitude, latitude) #print(xgrid, xgrid.dtype)",
"(K)' elif (layer.strip() == \"d2m\"): ylab = 'Dewpoint T2m (K)' #elif (layer.strip() ==",
"ix_min = x iy_min = y # Select all of the temporal instances",
"'month': [ '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11',",
"'02:00', '03:00', '04:00', '05:00', '06:00', '07:00', '08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00',",
"= nc.variables['latitude'], nc.variables['longitude'] # extract lat/lon values (in degrees) to numpy arrays latvals",
"= np.nan # Fill values to NAN arr[arr == fillva] = np.nan arr[arr",
"u component (m s-1)' elif (layer.strip() == \"v10\"): ylab = 'windspeed v component",
"the temporal instances of the pixel arr = nc.variables[layer][:, 0, iy_min, ix_min] if",
"print(offset, scale, nodata, fillva) lat, lon = nc.variables['latitude'], nc.variables['longitude'] # extract lat/lon values",
"# 'total_column_snow_water', 'total_precipitation', 'volumetric_soil_water_layer_1', # 'volumetric_soil_water_layer_2', 'volumetric_soil_water_layer_3', # 'volumetric_soil_water_layer_4', ], 'area': [ north,",
"'12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00', ],",
"<gh_stars>0 import netCDF4 import cdsapi import numpy as np import matplotlib.pyplot as plt",
"+ arr * scale # Return the array return array def plotLayer(layer, time_convert,",
"distance_2d(longitude, latitude, xgrid, ygrid): #print(longitude, latitude) #print(xgrid, xgrid.dtype) #print(ygrid, ygrid.dtype) return np.hypot(np.subtract(xgrid,np.float(longitude)), np.subtract(ygrid,np.float(latitude)))",
"def download_ERA5_bbox(i_year, out_dir, prefix, north, west, south, east): c = cdsapi.Client() c.retrieve( 'reanalysis-era5-single-levels',",
"value is sometimes -32766, but not documented... arr[arr == 32766] = np.nan #",
"netCDF file \"\"\" # Get the time array from NETCDF file and convert",
"Replace nodata (often -32767) with NAN arr[arr == nodata] = np.nan arr[arr ==",
"plotLayer(layer, time_convert, array): \"\"\" Function to plot the array data with time \"\"\"",
"for x in range(dist_grid.shape[1]): for y in range(dist_grid.shape[0]): if dist_grid[y][x] == minval: ix_min",
"nc.variables[layer][:, 0, iy_min, ix_min] if layer == 'ssrd': arr[arr == 0] = np.nan",
"if layer == 'ssrd': return arr # Rescale the data array = offset",
"(layer.strip() == \"d2m\"): ylab = 'Dewpoint T2m (K)' #elif (layer.strip() == \"sp\"): #",
"'21:00', '22:00', '23:00', ], 'format': 'netcdf', }, out_dir + '/ERA5_' + prefix +",
"'year': str(i_year), 'month': [ '01', '02', '03', '04', '05', '06', '07', '08', '09',",
"def d2m2eact(d2m): \"\"\" Converts dew point temperature to actual vapour pressure (hPa) \"\"\"",
"time_convert, array): \"\"\" Function to plot the array data with time \"\"\" fig,",
"np.nan # Fill in value is sometimes -32766, but not documented... arr[arr ==",
"= x iy_min = y # Select all of the temporal instances of",
"yet time_convert = netCDF4.num2date(tim[:], tim.units, tim.calendar, only_use_cftime_datetimes=False) return time_convert def getPixelVals(netcdffile, layer, longitude,",
"(layer.strip() == \"t2m\"): ylab = 'T2m (K)' elif (layer.strip() == \"d2m\"): ylab =",
"import cdsapi import numpy as np import matplotlib.pyplot as plt def download_ERA5_bbox(i_year, out_dir,",
"Extract the offset and scale from netcdf file offset = float(dict_nc['add_offset']) scale =",
"array return array def plotLayer(layer, time_convert, array): \"\"\" Function to plot the array",
"'04', '05', '06', '07', '08', '09', '10', '11', '12', ], 'day': [ '01',",
"'09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00',",
"ncfile = netCDF4.Dataset(netcdffile, 'r') tim = ncfile.variables['time'] # do not cast to numpy",
"str(i_year), 'month': [ '01', '02', '03', '04', '05', '06', '07', '08', '09', '10',",
"= 'T2m (K)' elif (layer.strip() == \"d2m\"): ylab = 'Dewpoint T2m (K)' #elif",
"title='ERA5 ' + ylab) ax.grid() # fig.savefig(\"test.png\") plt.show() def d2m2eact(d2m): \"\"\" Converts dew",
"south, east, ], # North, West, South, East. Default: global 'year': str(i_year), 'month':",
"def getTimeNetcdf(netcdffile): \"\"\" Function to extract the time component of a netCDF file",
"'07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19',",
"+ '/ERA5_' + prefix + '_' + str(i_year) + '.nc') def getTimeNetcdf(netcdffile): \"\"\"",
"np.nan if layer == 'ssrd': return arr # Rescale the data array =",
"range(dist_grid.shape[0]): if dist_grid[y][x] == minval: ix_min = x iy_min = y # Select",
"'mean_potential_evaporation_rate', # 'minimum_total_precipitation_rate_since_previous_post_processing', # 'orography', 'potential_evaporation', 'precipitation_type', # 'snow_density', 'snow_depth', 'soil_temperature_level_1', # 'soil_temperature_level_2',",
"query pixels values for a given layer at a given Lat/long \"\"\" nc",
"nc.variables['latitude'], nc.variables['longitude'] # extract lat/lon values (in degrees) to numpy arrays latvals =",
"0] = np.nan # Replace nodata (often -32767) with NAN arr[arr == nodata]",
"\"v10\"): ylab = 'windspeed v component (m s-1)' elif (layer.strip() == \"t2m\"): ylab",
"vapour pressure (hPa) \"\"\" return (0.6108 * np.exp((17.27 * d2m) / (d2m +",
"import netCDF4 import cdsapi import numpy as np import matplotlib.pyplot as plt def",
"'06:00', '07:00', '08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00',",
"file \"\"\" # Get the time array from NETCDF file and convert to",
"fig, ax = plt.subplots() ax.plot_date(time_convert, array, 'g-') if (layer.strip() == \"ssrd\"): ylab =",
"== \"tp\"): ylab = 'Total precipitation (m)' else: ylab = 'undefined product' ax.set(xlabel='time',",
"'01:00', '02:00', '03:00', '04:00', '05:00', '06:00', '07:00', '08:00', '09:00', '10:00', '11:00', '12:00', '13:00',",
"'05:00', '06:00', '07:00', '08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00',",
"np.meshgrid(xl, yl, sparse=True) def distance_2d(longitude, latitude, xgrid, ygrid): #print(longitude, latitude) #print(xgrid, xgrid.dtype) #print(ygrid,",
"ylab = 'T2m (K)' elif (layer.strip() == \"d2m\"): ylab = 'Dewpoint T2m (K)'",
"# 'volumetric_soil_water_layer_2', 'volumetric_soil_water_layer_3', # 'volumetric_soil_water_layer_4', ], 'area': [ north, west, south, east, ],",
"netcdf file offset = float(dict_nc['add_offset']) scale = float(dict_nc['scale_factor']) # Extract NoData Value from",
"for y in range(dist_grid.shape[0]): if dist_grid[y][x] == minval: ix_min = x iy_min =",
"'21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', ], 'time':",
"'00:00', '01:00', '02:00', '03:00', '04:00', '05:00', '06:00', '07:00', '08:00', '09:00', '10:00', '11:00', '12:00',",
"ylab = 'surface downwelling shortwave flux in air (J m-2)' elif (layer.strip() ==",
"+ ylab) ax.grid() # fig.savefig(\"test.png\") plt.show() def d2m2eact(d2m): \"\"\" Converts dew point temperature",
"'11', '12', ], 'day': [ '01', '02', '03', '04', '05', '06', '07', '08',",
"'surface downwelling shortwave flux in air (J m-2)' elif (layer.strip() == \"u10\"): ylab",
"# 'mean_evaporation_rate', 'mean_potential_evaporation_rate', # 'minimum_total_precipitation_rate_since_previous_post_processing', # 'orography', 'potential_evaporation', 'precipitation_type', # 'snow_density', 'snow_depth', 'soil_temperature_level_1',",
"def getPixelVals(netcdffile, layer, longitude, latitude): \"\"\" Function to query pixels values for a",
"'g-') if (layer.strip() == \"ssrd\"): ylab = 'surface downwelling shortwave flux in air",
"instances of the pixel arr = nc.variables[layer][:, 0, iy_min, ix_min] if layer ==",
"(layer.strip() == \"tp\"): ylab = 'Total precipitation (m)' else: ylab = 'undefined product'",
"if (layer.strip() == \"ssrd\"): ylab = 'surface downwelling shortwave flux in air (J",
"# Fill values to NAN arr[arr == fillva] = np.nan arr[arr == -fillva]",
"cast to numpy array yet time_convert = netCDF4.num2date(tim[:], tim.units, tim.calendar, only_use_cftime_datetimes=False) return time_convert",
"ylab = 'Dewpoint T2m (K)' #elif (layer.strip() == \"sp\"): # ylab = 'Surface",
"\"\"\" nc = netCDF4.Dataset(netcdffile) dict_nc = nc[layer].__dict__ # Extract the offset and scale",
"only_use_cftime_datetimes=False) return time_convert def getPixelVals(netcdffile, layer, longitude, latitude): \"\"\" Function to query pixels",
"yy) minval = dist_grid.min() for x in range(dist_grid.shape[1]): for y in range(dist_grid.shape[0]): if",
"'product_type': 'reanalysis', 'variable': [ 'surface_solar_radiation_downwards', '10m_u_component_of_wind', '10m_v_component_of_wind', '2m_temperature', 'surface_pressure', 'total_precipitation', '2m_dewpoint_temperature' # 'evaporation',",
"= 'windspeed u component (m s-1)' elif (layer.strip() == \"v10\"): ylab = 'windspeed",
"'snow_depth', 'soil_temperature_level_1', # 'soil_temperature_level_2', 'soil_temperature_level_3', 'soil_temperature_level_4', # 'soil_type', 'surface_pressure', 'surface_solar_radiation_downwards', # 'total_column_snow_water', 'total_precipitation',",
"west, south, east): c = cdsapi.Client() c.retrieve( 'reanalysis-era5-single-levels', { 'product_type': 'reanalysis', 'variable': [",
"'2m_temperature', 'surface_pressure', 'total_precipitation', '2m_dewpoint_temperature' # 'evaporation', 'potential_evaporation', # 'snow_density', 'snow_depth' # '10m_u_component_of_wind', '10m_v_component_of_wind',",
"# '2m_temperature', 'angle_of_sub_gridscale_orography', # 'anisotropy_of_sub_gridscale_orography', # 'evaporation', 'land_sea_mask', # 'maximum_total_precipitation_rate_since_previous_post_processing', # 'mean_evaporation_rate', 'mean_potential_evaporation_rate',",
"'surface_pressure', 'surface_solar_radiation_downwards', # 'total_column_snow_water', 'total_precipitation', 'volumetric_soil_water_layer_1', # 'volumetric_soil_water_layer_2', 'volumetric_soil_water_layer_3', # 'volumetric_soil_water_layer_4', ], 'area':",
"do not cast to numpy array yet time_convert = netCDF4.num2date(tim[:], tim.units, tim.calendar, only_use_cftime_datetimes=False)",
"== fillva] = np.nan arr[arr == -fillva] = np.nan if layer == 'ssrd':",
"from NETCDF file and convert to Python datetime ncfile = netCDF4.Dataset(netcdffile, 'r') tim",
"flux in air (J m-2)' elif (layer.strip() == \"u10\"): ylab = 'windspeed u",
"ax.set(xlabel='time', ylabel=ylab, title='ERA5 ' + ylab) ax.grid() # fig.savefig(\"test.png\") plt.show() def d2m2eact(d2m): \"\"\"",
"tim = ncfile.variables['time'] # do not cast to numpy array yet time_convert =",
"latitude): \"\"\" Function to query pixels values for a given layer at a",
"layer == 'ssrd': arr[arr == 0] = np.nan # Replace nodata (often -32767)",
"int(dict_nc['_FillValue']) # print(offset, scale, nodata, fillva) lat, lon = nc.variables['latitude'], nc.variables['longitude'] # extract",
"'17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00', ], 'format': 'netcdf', }, out_dir +",
"from layer nodata = int(dict_nc['missing_value']) fillva = int(dict_nc['_FillValue']) # print(offset, scale, nodata, fillva)",
"netCDF4.num2date(tim[:], tim.units, tim.calendar, only_use_cftime_datetimes=False) return time_convert def getPixelVals(netcdffile, layer, longitude, latitude): \"\"\" Function",
"pressure (hPa) \"\"\" return (0.6108 * np.exp((17.27 * d2m) / (d2m + 237.3)))",
"= netCDF4.Dataset(netcdffile, 'r') tim = ncfile.variables['time'] # do not cast to numpy array",
"'potential_evaporation', 'precipitation_type', # 'snow_density', 'snow_depth', 'soil_temperature_level_1', # 'soil_temperature_level_2', 'soil_temperature_level_3', 'soil_temperature_level_4', # 'soil_type', 'surface_pressure',",
"\"sp\"): # ylab = 'Surface air pressure (Pa)' elif (layer.strip() == \"tp\"): ylab",
"given Lat/long \"\"\" nc = netCDF4.Dataset(netcdffile) dict_nc = nc[layer].__dict__ # Extract the offset",
"int(dict_nc['missing_value']) fillva = int(dict_nc['_FillValue']) # print(offset, scale, nodata, fillva) lat, lon = nc.variables['latitude'],",
"'reanalysis', 'variable': [ 'surface_solar_radiation_downwards', '10m_u_component_of_wind', '10m_v_component_of_wind', '2m_temperature', 'surface_pressure', 'total_precipitation', '2m_dewpoint_temperature' # 'evaporation', 'potential_evaporation',",
"# North, West, South, East. Default: global 'year': str(i_year), 'month': [ '01', '02',",
"yy = np.meshgrid(xl, yl, sparse=True) def distance_2d(longitude, latitude, xgrid, ygrid): #print(longitude, latitude) #print(xgrid,",
"= int(dict_nc['_FillValue']) # print(offset, scale, nodata, fillva) lat, lon = nc.variables['latitude'], nc.variables['longitude'] #",
"'10m_u_component_of_wind', '10m_v_component_of_wind', '2m_temperature', 'surface_pressure', 'total_precipitation', '2m_dewpoint_temperature' # 'evaporation', 'potential_evaporation', # 'snow_density', 'snow_depth' #",
"'08', '09', '10', '11', '12', ], 'day': [ '01', '02', '03', '04', '05',",
"'soil_type', 'surface_pressure', 'surface_solar_radiation_downwards', # 'total_column_snow_water', 'total_precipitation', 'volumetric_soil_water_layer_1', # 'volumetric_soil_water_layer_2', 'volumetric_soil_water_layer_3', # 'volumetric_soil_water_layer_4', ],",
"'ssrd': return arr # Rescale the data array = offset + arr *",
"= 'undefined product' ax.set(xlabel='time', ylabel=ylab, title='ERA5 ' + ylab) ax.grid() # fig.savefig(\"test.png\") plt.show()",
"'12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24',",
"}, out_dir + '/ERA5_' + prefix + '_' + str(i_year) + '.nc') def",
"ax.plot_date(time_convert, array, 'g-') if (layer.strip() == \"ssrd\"): ylab = 'surface downwelling shortwave flux",
"# extract lat/lon values (in degrees) to numpy arrays latvals = lat[:] lonvals",
"\"\"\" # Get the time array from NETCDF file and convert to Python",
"return time_convert def getPixelVals(netcdffile, layer, longitude, latitude): \"\"\" Function to query pixels values",
"ncfile.variables['time'] # do not cast to numpy array yet time_convert = netCDF4.num2date(tim[:], tim.units,",
"lon[:] #print(lonvals.shape) #print(latvals.shape) xl = np.linspace(lonvals.min(), lonvals.max(), lonvals.shape[0]) yl = np.linspace(latvals.min(), latvals.max(), latvals.shape[0])",
"'19:00', '20:00', '21:00', '22:00', '23:00', ], 'format': 'netcdf', }, out_dir + '/ERA5_' +",
"ylab = 'Surface air pressure (Pa)' elif (layer.strip() == \"tp\"): ylab = 'Total",
"# 'maximum_total_precipitation_rate_since_previous_post_processing', # 'mean_evaporation_rate', 'mean_potential_evaporation_rate', # 'minimum_total_precipitation_rate_since_previous_post_processing', # 'orography', 'potential_evaporation', 'precipitation_type', # 'snow_density',",
"x in range(dist_grid.shape[1]): for y in range(dist_grid.shape[0]): if dist_grid[y][x] == minval: ix_min =",
"32766] = np.nan # Fill values to NAN arr[arr == fillva] = np.nan",
"global 'year': str(i_year), 'month': [ '01', '02', '03', '04', '05', '06', '07', '08',",
"return np.hypot(np.subtract(xgrid,np.float(longitude)), np.subtract(ygrid,np.float(latitude))) dist_grid = distance_2d(longitude, latitude, xx, yy) minval = dist_grid.min() for",
"= np.nan arr[arr == -fillva] = np.nan if layer == 'ssrd': return arr",
"scale, nodata, fillva) lat, lon = nc.variables['latitude'], nc.variables['longitude'] # extract lat/lon values (in",
"time array from NETCDF file and convert to Python datetime ncfile = netCDF4.Dataset(netcdffile,",
"'total_precipitation', 'volumetric_soil_water_layer_1', # 'volumetric_soil_water_layer_2', 'volumetric_soil_water_layer_3', # 'volumetric_soil_water_layer_4', ], 'area': [ north, west, south,",
"to query pixels values for a given layer at a given Lat/long \"\"\"",
"convert to Python datetime ncfile = netCDF4.Dataset(netcdffile, 'r') tim = ncfile.variables['time'] # do",
"'r') tim = ncfile.variables['time'] # do not cast to numpy array yet time_convert",
"'09', '10', '11', '12', ], 'day': [ '01', '02', '03', '04', '05', '06',",
"'evaporation', 'land_sea_mask', # 'maximum_total_precipitation_rate_since_previous_post_processing', # 'mean_evaporation_rate', 'mean_potential_evaporation_rate', # 'minimum_total_precipitation_rate_since_previous_post_processing', # 'orography', 'potential_evaporation', 'precipitation_type',",
"'10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00',",
"\"tp\"): ylab = 'Total precipitation (m)' else: ylab = 'undefined product' ax.set(xlabel='time', ylabel=ylab,",
"#print(lonvals.shape) #print(latvals.shape) xl = np.linspace(lonvals.min(), lonvals.max(), lonvals.shape[0]) yl = np.linspace(latvals.min(), latvals.max(), latvals.shape[0]) xx,",
"= offset + arr * scale # Return the array return array def",
"to plot the array data with time \"\"\" fig, ax = plt.subplots() ax.plot_date(time_convert,",
"'format': 'netcdf', }, out_dir + '/ERA5_' + prefix + '_' + str(i_year) +",
"#elif (layer.strip() == \"sp\"): # ylab = 'Surface air pressure (Pa)' elif (layer.strip()",
"out_dir + '/ERA5_' + prefix + '_' + str(i_year) + '.nc') def getTimeNetcdf(netcdffile):",
"Default: global 'year': str(i_year), 'month': [ '01', '02', '03', '04', '05', '06', '07',",
"xl = np.linspace(lonvals.min(), lonvals.max(), lonvals.shape[0]) yl = np.linspace(latvals.min(), latvals.max(), latvals.shape[0]) xx, yy =",
"time_convert = netCDF4.num2date(tim[:], tim.units, tim.calendar, only_use_cftime_datetimes=False) return time_convert def getPixelVals(netcdffile, layer, longitude, latitude):",
"'06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18',",
"nodata] = np.nan arr[arr == -nodata] = np.nan # Fill in value is",
"= int(dict_nc['missing_value']) fillva = int(dict_nc['_FillValue']) # print(offset, scale, nodata, fillva) lat, lon =",
"to NAN arr[arr == fillva] = np.nan arr[arr == -fillva] = np.nan if",
"iy_min = y # Select all of the temporal instances of the pixel",
"shortwave flux in air (J m-2)' elif (layer.strip() == \"u10\"): ylab = 'windspeed",
"not cast to numpy array yet time_convert = netCDF4.num2date(tim[:], tim.units, tim.calendar, only_use_cftime_datetimes=False) return",
"'09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21',",
"'10m_u_component_of_wind', '10m_v_component_of_wind', '2m_dewpoint_temperature', # '2m_temperature', 'angle_of_sub_gridscale_orography', # 'anisotropy_of_sub_gridscale_orography', # 'evaporation', 'land_sea_mask', # 'maximum_total_precipitation_rate_since_previous_post_processing',",
"arr[arr == nodata] = np.nan arr[arr == -nodata] = np.nan # Fill in",
"documented... arr[arr == 32766] = np.nan # Fill values to NAN arr[arr ==",
"'02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', ], 'day':",
"array from NETCDF file and convert to Python datetime ncfile = netCDF4.Dataset(netcdffile, 'r')",
"in range(dist_grid.shape[0]): if dist_grid[y][x] == minval: ix_min = x iy_min = y #",
"ax.grid() # fig.savefig(\"test.png\") plt.show() def d2m2eact(d2m): \"\"\" Converts dew point temperature to actual",
"values for a given layer at a given Lat/long \"\"\" nc = netCDF4.Dataset(netcdffile)",
"Select all of the temporal instances of the pixel arr = nc.variables[layer][:, 0,",
"np.linspace(latvals.min(), latvals.max(), latvals.shape[0]) xx, yy = np.meshgrid(xl, yl, sparse=True) def distance_2d(longitude, latitude, xgrid,",
"Function to extract the time component of a netCDF file \"\"\" # Get",
"= np.nan if layer == 'ssrd': return arr # Rescale the data array",
"'total_column_snow_water', 'total_precipitation', 'volumetric_soil_water_layer_1', # 'volumetric_soil_water_layer_2', 'volumetric_soil_water_layer_3', # 'volumetric_soil_water_layer_4', ], 'area': [ north, west,",
"'12', ], 'day': [ '01', '02', '03', '04', '05', '06', '07', '08', '09',",
"# Fill in value is sometimes -32766, but not documented... arr[arr == 32766]",
"\"\"\" Function to extract the time component of a netCDF file \"\"\" #",
"arr[arr == 32766] = np.nan # Fill values to NAN arr[arr == fillva]",
"product' ax.set(xlabel='time', ylabel=ylab, title='ERA5 ' + ylab) ax.grid() # fig.savefig(\"test.png\") plt.show() def d2m2eact(d2m):",
"'11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00',",
"'surface_pressure', 'total_precipitation', '2m_dewpoint_temperature' # 'evaporation', 'potential_evaporation', # 'snow_density', 'snow_depth' # '10m_u_component_of_wind', '10m_v_component_of_wind', '2m_dewpoint_temperature',",
"Return the array return array def plotLayer(layer, time_convert, array): \"\"\" Function to plot",
"# do not cast to numpy array yet time_convert = netCDF4.num2date(tim[:], tim.units, tim.calendar,",
"dist_grid[y][x] == minval: ix_min = x iy_min = y # Select all of",
"'Dewpoint T2m (K)' #elif (layer.strip() == \"sp\"): # ylab = 'Surface air pressure",
"= 'Total precipitation (m)' else: ylab = 'undefined product' ax.set(xlabel='time', ylabel=ylab, title='ERA5 '",
"# Extract the offset and scale from netcdf file offset = float(dict_nc['add_offset']) scale",
"np.linspace(lonvals.min(), lonvals.max(), lonvals.shape[0]) yl = np.linspace(latvals.min(), latvals.max(), latvals.shape[0]) xx, yy = np.meshgrid(xl, yl,",
"np.nan arr[arr == -nodata] = np.nan # Fill in value is sometimes -32766,",
"* scale # Return the array return array def plotLayer(layer, time_convert, array): \"\"\"",
"yl = np.linspace(latvals.min(), latvals.max(), latvals.shape[0]) xx, yy = np.meshgrid(xl, yl, sparse=True) def distance_2d(longitude,",
"= netCDF4.Dataset(netcdffile) dict_nc = nc[layer].__dict__ # Extract the offset and scale from netcdf",
"component (m s-1)' elif (layer.strip() == \"v10\"): ylab = 'windspeed v component (m",
"dict_nc = nc[layer].__dict__ # Extract the offset and scale from netcdf file offset",
"the pixel arr = nc.variables[layer][:, 0, iy_min, ix_min] if layer == 'ssrd': arr[arr",
"'variable': [ 'surface_solar_radiation_downwards', '10m_u_component_of_wind', '10m_v_component_of_wind', '2m_temperature', 'surface_pressure', 'total_precipitation', '2m_dewpoint_temperature' # 'evaporation', 'potential_evaporation', #",
"'30', '31', ], 'time': [ '00:00', '01:00', '02:00', '03:00', '04:00', '05:00', '06:00', '07:00',",
"import numpy as np import matplotlib.pyplot as plt def download_ERA5_bbox(i_year, out_dir, prefix, north,",
"= float(dict_nc['add_offset']) scale = float(dict_nc['scale_factor']) # Extract NoData Value from layer nodata =",
"= 'windspeed v component (m s-1)' elif (layer.strip() == \"t2m\"): ylab = 'T2m",
"lat[:] lonvals = lon[:] #print(lonvals.shape) #print(latvals.shape) xl = np.linspace(lonvals.min(), lonvals.max(), lonvals.shape[0]) yl =",
"elif (layer.strip() == \"tp\"): ylab = 'Total precipitation (m)' else: ylab = 'undefined",
"plt.subplots() ax.plot_date(time_convert, array, 'g-') if (layer.strip() == \"ssrd\"): ylab = 'surface downwelling shortwave",
"np.hypot(np.subtract(xgrid,np.float(longitude)), np.subtract(ygrid,np.float(latitude))) dist_grid = distance_2d(longitude, latitude, xx, yy) minval = dist_grid.min() for x",
"== \"u10\"): ylab = 'windspeed u component (m s-1)' elif (layer.strip() == \"v10\"):",
"nodata (often -32767) with NAN arr[arr == nodata] = np.nan arr[arr == -nodata]",
"arr[arr == 0] = np.nan # Replace nodata (often -32767) with NAN arr[arr",
"ylab = 'undefined product' ax.set(xlabel='time', ylabel=ylab, title='ERA5 ' + ylab) ax.grid() # fig.savefig(\"test.png\")",
"y # Select all of the temporal instances of the pixel arr =",
"netCDF4.Dataset(netcdffile, 'r') tim = ncfile.variables['time'] # do not cast to numpy array yet",
"d2m2eact(d2m): \"\"\" Converts dew point temperature to actual vapour pressure (hPa) \"\"\" return",
"out_dir, prefix, north, west, south, east): c = cdsapi.Client() c.retrieve( 'reanalysis-era5-single-levels', { 'product_type':",
"float(dict_nc['scale_factor']) # Extract NoData Value from layer nodata = int(dict_nc['missing_value']) fillva = int(dict_nc['_FillValue'])",
"'03:00', '04:00', '05:00', '06:00', '07:00', '08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00',",
"'reanalysis-era5-single-levels', { 'product_type': 'reanalysis', 'variable': [ 'surface_solar_radiation_downwards', '10m_u_component_of_wind', '10m_v_component_of_wind', '2m_temperature', 'surface_pressure', 'total_precipitation', '2m_dewpoint_temperature'",
"# 'minimum_total_precipitation_rate_since_previous_post_processing', # 'orography', 'potential_evaporation', 'precipitation_type', # 'snow_density', 'snow_depth', 'soil_temperature_level_1', # 'soil_temperature_level_2', 'soil_temperature_level_3',",
"'02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14',",
"the time component of a netCDF file \"\"\" # Get the time array",
"\"ssrd\"): ylab = 'surface downwelling shortwave flux in air (J m-2)' elif (layer.strip()",
"np.nan # Fill values to NAN arr[arr == fillva] = np.nan arr[arr ==",
"== 32766] = np.nan # Fill values to NAN arr[arr == fillva] =",
"(J m-2)' elif (layer.strip() == \"u10\"): ylab = 'windspeed u component (m s-1)'",
"point temperature to actual vapour pressure (hPa) \"\"\" return (0.6108 * np.exp((17.27 *",
"(K)' #elif (layer.strip() == \"sp\"): # ylab = 'Surface air pressure (Pa)' elif",
"temporal instances of the pixel arr = nc.variables[layer][:, 0, iy_min, ix_min] if layer",
"matplotlib.pyplot as plt def download_ERA5_bbox(i_year, out_dir, prefix, north, west, south, east): c =",
"'windspeed v component (m s-1)' elif (layer.strip() == \"t2m\"): ylab = 'T2m (K)'",
"array def plotLayer(layer, time_convert, array): \"\"\" Function to plot the array data with",
"plt.show() def d2m2eact(d2m): \"\"\" Converts dew point temperature to actual vapour pressure (hPa)",
"# 'soil_temperature_level_2', 'soil_temperature_level_3', 'soil_temperature_level_4', # 'soil_type', 'surface_pressure', 'surface_solar_radiation_downwards', # 'total_column_snow_water', 'total_precipitation', 'volumetric_soil_water_layer_1', #",
"minval = dist_grid.min() for x in range(dist_grid.shape[1]): for y in range(dist_grid.shape[0]): if dist_grid[y][x]",
"at a given Lat/long \"\"\" nc = netCDF4.Dataset(netcdffile) dict_nc = nc[layer].__dict__ # Extract",
"nc[layer].__dict__ # Extract the offset and scale from netcdf file offset = float(dict_nc['add_offset'])",
"'05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17',",
"'19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31',",
"'27', '28', '29', '30', '31', ], 'time': [ '00:00', '01:00', '02:00', '03:00', '04:00',",
"air (J m-2)' elif (layer.strip() == \"u10\"): ylab = 'windspeed u component (m",
"'13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00', ], 'format':",
"'windspeed u component (m s-1)' elif (layer.strip() == \"v10\"): ylab = 'windspeed v",
"arrays latvals = lat[:] lonvals = lon[:] #print(lonvals.shape) #print(latvals.shape) xl = np.linspace(lonvals.min(), lonvals.max(),",
"arr[arr == -fillva] = np.nan if layer == 'ssrd': return arr # Rescale",
"elif (layer.strip() == \"d2m\"): ylab = 'Dewpoint T2m (K)' #elif (layer.strip() == \"sp\"):",
"as plt def download_ERA5_bbox(i_year, out_dir, prefix, north, west, south, east): c = cdsapi.Client()",
"= 'surface downwelling shortwave flux in air (J m-2)' elif (layer.strip() == \"u10\"):",
"layer nodata = int(dict_nc['missing_value']) fillva = int(dict_nc['_FillValue']) # print(offset, scale, nodata, fillva) lat,",
"tim.calendar, only_use_cftime_datetimes=False) return time_convert def getPixelVals(netcdffile, layer, longitude, latitude): \"\"\" Function to query",
"east, ], # North, West, South, East. Default: global 'year': str(i_year), 'month': [",
"'11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23',",
"extract the time component of a netCDF file \"\"\" # Get the time",
"tim.units, tim.calendar, only_use_cftime_datetimes=False) return time_convert def getPixelVals(netcdffile, layer, longitude, latitude): \"\"\" Function to",
"datetime ncfile = netCDF4.Dataset(netcdffile, 'r') tim = ncfile.variables['time'] # do not cast to",
"\"\"\" Function to query pixels values for a given layer at a given",
"# Extract NoData Value from layer nodata = int(dict_nc['missing_value']) fillva = int(dict_nc['_FillValue']) #",
"degrees) to numpy arrays latvals = lat[:] lonvals = lon[:] #print(lonvals.shape) #print(latvals.shape) xl",
"'10', '11', '12', ], 'day': [ '01', '02', '03', '04', '05', '06', '07',",
"arr[arr == -nodata] = np.nan # Fill in value is sometimes -32766, but",
"-32767) with NAN arr[arr == nodata] = np.nan arr[arr == -nodata] = np.nan",
"'15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27',",
"offset and scale from netcdf file offset = float(dict_nc['add_offset']) scale = float(dict_nc['scale_factor']) #",
"'evaporation', 'potential_evaporation', # 'snow_density', 'snow_depth' # '10m_u_component_of_wind', '10m_v_component_of_wind', '2m_dewpoint_temperature', # '2m_temperature', 'angle_of_sub_gridscale_orography', #",
"given layer at a given Lat/long \"\"\" nc = netCDF4.Dataset(netcdffile) dict_nc = nc[layer].__dict__",
"not documented... arr[arr == 32766] = np.nan # Fill values to NAN arr[arr",
"np.subtract(ygrid,np.float(latitude))) dist_grid = distance_2d(longitude, latitude, xx, yy) minval = dist_grid.min() for x in",
"[ '00:00', '01:00', '02:00', '03:00', '04:00', '05:00', '06:00', '07:00', '08:00', '09:00', '10:00', '11:00',",
"is sometimes -32766, but not documented... arr[arr == 32766] = np.nan # Fill",
"pressure (Pa)' elif (layer.strip() == \"tp\"): ylab = 'Total precipitation (m)' else: ylab",
"netCDF4.Dataset(netcdffile) dict_nc = nc[layer].__dict__ # Extract the offset and scale from netcdf file",
"getTimeNetcdf(netcdffile): \"\"\" Function to extract the time component of a netCDF file \"\"\"",
"component of a netCDF file \"\"\" # Get the time array from NETCDF",
"0, iy_min, ix_min] if layer == 'ssrd': arr[arr == 0] = np.nan #",
"ygrid): #print(longitude, latitude) #print(xgrid, xgrid.dtype) #print(ygrid, ygrid.dtype) return np.hypot(np.subtract(xgrid,np.float(longitude)), np.subtract(ygrid,np.float(latitude))) dist_grid = distance_2d(longitude,",
"= np.linspace(lonvals.min(), lonvals.max(), lonvals.shape[0]) yl = np.linspace(latvals.min(), latvals.max(), latvals.shape[0]) xx, yy = np.meshgrid(xl,",
"west, south, east, ], # North, West, South, East. Default: global 'year': str(i_year),",
"'07:00', '08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00',",
"# 'evaporation', 'land_sea_mask', # 'maximum_total_precipitation_rate_since_previous_post_processing', # 'mean_evaporation_rate', 'mean_potential_evaporation_rate', # 'minimum_total_precipitation_rate_since_previous_post_processing', # 'orography', 'potential_evaporation',",
"'precipitation_type', # 'snow_density', 'snow_depth', 'soil_temperature_level_1', # 'soil_temperature_level_2', 'soil_temperature_level_3', 'soil_temperature_level_4', # 'soil_type', 'surface_pressure', 'surface_solar_radiation_downwards',",
"= np.linspace(latvals.min(), latvals.max(), latvals.shape[0]) xx, yy = np.meshgrid(xl, yl, sparse=True) def distance_2d(longitude, latitude,",
"data array = offset + arr * scale # Return the array return",
"latitude, xx, yy) minval = dist_grid.min() for x in range(dist_grid.shape[1]): for y in",
"'14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26',",
"'maximum_total_precipitation_rate_since_previous_post_processing', # 'mean_evaporation_rate', 'mean_potential_evaporation_rate', # 'minimum_total_precipitation_rate_since_previous_post_processing', # 'orography', 'potential_evaporation', 'precipitation_type', # 'snow_density', 'snow_depth',",
"ylabel=ylab, title='ERA5 ' + ylab) ax.grid() # fig.savefig(\"test.png\") plt.show() def d2m2eact(d2m): \"\"\" Converts",
"== \"d2m\"): ylab = 'Dewpoint T2m (K)' #elif (layer.strip() == \"sp\"): # ylab",
"import matplotlib.pyplot as plt def download_ERA5_bbox(i_year, out_dir, prefix, north, west, south, east): c",
"prefix, north, west, south, east): c = cdsapi.Client() c.retrieve( 'reanalysis-era5-single-levels', { 'product_type': 'reanalysis',",
"\"d2m\"): ylab = 'Dewpoint T2m (K)' #elif (layer.strip() == \"sp\"): # ylab =",
"scale = float(dict_nc['scale_factor']) # Extract NoData Value from layer nodata = int(dict_nc['missing_value']) fillva",
"== \"sp\"): # ylab = 'Surface air pressure (Pa)' elif (layer.strip() == \"tp\"):",
"+ str(i_year) + '.nc') def getTimeNetcdf(netcdffile): \"\"\" Function to extract the time component",
"'anisotropy_of_sub_gridscale_orography', # 'evaporation', 'land_sea_mask', # 'maximum_total_precipitation_rate_since_previous_post_processing', # 'mean_evaporation_rate', 'mean_potential_evaporation_rate', # 'minimum_total_precipitation_rate_since_previous_post_processing', # 'orography',",
"'volumetric_soil_water_layer_4', ], 'area': [ north, west, south, east, ], # North, West, South,"
] |
[] |
[
"from tqdm import tqdm from torch.nn.utils import clip_grad_norm_ from torch.optim.lr_scheduler import ReduceLROnPlateau from",
"torch.nn as nn import torch.optim as optim from pathlib import Path from tqdm",
"torch.optim as optim from pathlib import Path from tqdm import tqdm from torch.nn.utils",
"clip_grad_norm_ from torch.optim.lr_scheduler import ReduceLROnPlateau from torch.utils.tensorboard import SummaryWriter from data_loader import DataLoader",
"from torch.nn.utils import clip_grad_norm_ from torch.optim.lr_scheduler import ReduceLROnPlateau from torch.utils.tensorboard import SummaryWriter from",
"torch.nn.utils import clip_grad_norm_ from torch.optim.lr_scheduler import ReduceLROnPlateau from torch.utils.tensorboard import SummaryWriter from data_loader",
"import torch import torch.nn as nn import torch.optim as optim from pathlib import",
"import torch.nn as nn import torch.optim as optim from pathlib import Path from",
"import argparse import torch import torch.nn as nn import torch.optim as optim from",
"as nn import torch.optim as optim from pathlib import Path from tqdm import",
"torch.optim.lr_scheduler import ReduceLROnPlateau from torch.utils.tensorboard import SummaryWriter from data_loader import DataLoader from model.ops",
"argparse import torch import torch.nn as nn import torch.optim as optim from pathlib",
"import tqdm from torch.nn.utils import clip_grad_norm_ from torch.optim.lr_scheduler import ReduceLROnPlateau from torch.utils.tensorboard import",
"torch import torch.nn as nn import torch.optim as optim from pathlib import Path",
"as optim from pathlib import Path from tqdm import tqdm from torch.nn.utils import",
"ReduceLROnPlateau from torch.utils.tensorboard import SummaryWriter from data_loader import DataLoader from model.ops import RNNClassifier",
"optim from pathlib import Path from tqdm import tqdm from torch.nn.utils import clip_grad_norm_",
"import ReduceLROnPlateau from torch.utils.tensorboard import SummaryWriter from data_loader import DataLoader from model.ops import",
"nn import torch.optim as optim from pathlib import Path from tqdm import tqdm",
"tqdm import tqdm from torch.nn.utils import clip_grad_norm_ from torch.optim.lr_scheduler import ReduceLROnPlateau from torch.utils.tensorboard",
"pathlib import Path from tqdm import tqdm from torch.nn.utils import clip_grad_norm_ from torch.optim.lr_scheduler",
"<reponame>Ronalmoo/nlp_with_torch import argparse import torch import torch.nn as nn import torch.optim as optim",
"import clip_grad_norm_ from torch.optim.lr_scheduler import ReduceLROnPlateau from torch.utils.tensorboard import SummaryWriter from data_loader import",
"from torch.optim.lr_scheduler import ReduceLROnPlateau from torch.utils.tensorboard import SummaryWriter from data_loader import DataLoader from",
"import Path from tqdm import tqdm from torch.nn.utils import clip_grad_norm_ from torch.optim.lr_scheduler import",
"import torch.optim as optim from pathlib import Path from tqdm import tqdm from",
"tqdm from torch.nn.utils import clip_grad_norm_ from torch.optim.lr_scheduler import ReduceLROnPlateau from torch.utils.tensorboard import SummaryWriter",
"Path from tqdm import tqdm from torch.nn.utils import clip_grad_norm_ from torch.optim.lr_scheduler import ReduceLROnPlateau",
"from pathlib import Path from tqdm import tqdm from torch.nn.utils import clip_grad_norm_ from"
] |
[
"(f.read()) f.close() rules = whole_text.split('\\n') # Start of each group is indicated by",
"this tree. total_inside = 0 for each_inside, num_inside in rule_dict[root]: total_inside += num_inside",
"pairs, one pair per rule. # k = bag that the rule is",
"muted yellow bags.\" # {'light red': [('bright white', 1), ('muted yellow', 2)} #",
"+= num_inside + num_inside * search_inside(each_inside) return total_inside f = open(filename) whole_text =",
"7 of AOC 2020, <NAME>. # https://adventofcode.com/2020/day/7 import sys VERBOSE = ('-v' in",
"0 # ... there are no shiny gold bags in this tree. shiny_gold_inside",
"of those bags. # # For example, \"light red bags contain 1 bright",
"VERBOSE: print('each_rule, words, k:', each_rule, words, k) v = [] if each_rule[-22:] !=",
"1), ('muted yellow', 2)} # # Another example, # \"dotted black bags contain",
"num_inside in rule_dict[root]: total_inside += num_inside + num_inside * search_inside(each_inside) return total_inside f",
"list... return 0 # ... there are no bags this tree. total_inside =",
"each_inside == 'shiny gold': shiny_gold_inside = num_inside else: shiny_gold_inside += search_for_shiny_gold(each_inside) return shiny_gold_inside",
"of shiny gold bags it contains.\"\"\" if VERBOSE: print('root, rule_dict[root]:', root, rule_dict[root]) if",
"white bag, 2 muted yellow bags.\" # {'light red': [('bright white', 1), ('muted",
"VERBOSE: # print('each_rule, i, four_words:', each_rule, i, four_words) if len(four_words) == 4: v.append((four_words[1]",
"of bags it contains.\"\"\" if VERBOSE: print('root, rule_dict[root]:', root, rule_dict[root]) if len(rule_dict[root]) ==",
"indicated by a blank line. if VERBOSE: print('rules:', rules) # Dictionary contains k:",
"pair per rule. # k = bag that the rule is about, eg.",
"= bag that the rule is about, eg. \"light red\". # v =",
"value is empty list... return 0 # ... there are no bags this",
"rule_dict[root]) if len(rule_dict[root]) == 0: # If value is empty list... return 0",
"bag that the rule is about, eg. \"light red\". # v = Empty",
"in sys.argv) filename = sys.argv[1] def search_for_shiny_gold(root: str) -> int: \"\"\"Search a tree",
"total_inside f = open(filename) whole_text = (f.read()) f.close() rules = whole_text.split('\\n') # Start",
"# bag, and v is number of those bags. # # For example,",
"int(four_words[0]))) four_words = [] rule_dict[k] = v if VERBOSE: print('rule_dict, len(rule_dict)', rule_dict, len(rule_dict))",
"' + words[1] if VERBOSE: print('each_rule, words, k:', each_rule, words, k) v =",
"rule is about, eg. \"light red\". # v = Empty list if bag",
"shiny_gold_inside def search_inside(root: str) -> int: \"\"\"Search a tree of bags. Return the",
"red bags contain 1 bright white bag, 2 muted yellow bags.\" # {'light",
"words, k:', each_rule, words, k) v = [] if each_rule[-22:] != 'contain no",
"total_inside = 0 for each_inside, num_inside in rule_dict[root]: total_inside += num_inside + num_inside",
"each_inside, num_inside in rule_dict[root]: total_inside += num_inside + num_inside * search_inside(each_inside) return total_inside",
"empty list... return 0 # ... there are no shiny gold bags in",
"!= 'contain no other bags.': four_words = [] for i in words[4:]: four_words.append(i)",
"# Solution to day 7 of AOC 2020, <NAME>. # https://adventofcode.com/2020/day/7 import sys",
"list... return 0 # ... there are no shiny gold bags in this",
"int: \"\"\"Search a tree of bags. Return the total number of bags it",
"rule. # k = bag that the rule is about, eg. \"light red\".",
"len(rule_dict)) shiny_gold = 0 for k in rule_dict: if search_for_shiny_gold(k) > 0: shiny_gold",
"contain 1 bright white bag, 2 muted yellow bags.\" # {'light red': [('bright",
"shiny_gold = 0 for k in rule_dict: if search_for_shiny_gold(k) > 0: shiny_gold +=",
"v = [] if each_rule[-22:] != 'contain no other bags.': four_words = []",
"0: # If value is empty list... return 0 # ... there are",
"# Another example, # \"dotted black bags contain no other bags.\" # {'dotted",
"of tuples (b, n), where b is bag inside key # bag, and",
"else: shiny_gold_inside += search_for_shiny_gold(each_inside) return shiny_gold_inside def search_inside(root: str) -> int: \"\"\"Search a",
"black bags contain no other bags.\" # {'dotted black': []} rule_dict = {}",
"<NAME>. # https://adventofcode.com/2020/day/7 import sys VERBOSE = ('-v' in sys.argv) filename = sys.argv[1]",
"bag that the rules is about. k = words[0] + ' ' +",
"that the rule is about, eg. \"light red\". # v = Empty list",
"Dictionary contains k: v pairs, one pair per rule. # k = bag",
"' ' + four_words[2], int(four_words[0]))) four_words = [] rule_dict[k] = v if VERBOSE:",
"in rules: words = each_rule.split() # First 2 words are the name of",
"for each_inside, num_inside in rule_dict[root]: total_inside += num_inside + num_inside * search_inside(each_inside) return",
"VERBOSE: print('rules:', rules) # Dictionary contains k: v pairs, one pair per rule.",
"key # bag, and v is number of those bags. # # For",
"bags contain 1 bright white bag, 2 muted yellow bags.\" # {'light red':",
"in words[4:]: four_words.append(i) # if VERBOSE: # print('each_rule, i, four_words:', each_rule, i, four_words)",
"other bags.': four_words = [] for i in words[4:]: four_words.append(i) # if VERBOSE:",
"* search_inside(each_inside) return total_inside f = open(filename) whole_text = (f.read()) f.close() rules =",
"no other bags. Otherwise, contains list of tuples (b, n), where b is",
"sys.argv[1] def search_for_shiny_gold(root: str) -> int: \"\"\"Search a tree of bags. Return the",
"contain no other bags.\" # {'dotted black': []} rule_dict = {} for each_rule",
"white', 1), ('muted yellow', 2)} # # Another example, # \"dotted black bags",
"VERBOSE = ('-v' in sys.argv) filename = sys.argv[1] def search_for_shiny_gold(root: str) -> int:",
"num_inside in rule_dict[root]: if each_inside == 'shiny gold': shiny_gold_inside = num_inside else: shiny_gold_inside",
"a blank line. if VERBOSE: print('rules:', rules) # Dictionary contains k: v pairs,",
"# ... there are no bags this tree. total_inside = 0 for each_inside,",
"of each group is indicated by a blank line. if VERBOSE: print('rules:', rules)",
"search_inside(root: str) -> int: \"\"\"Search a tree of bags. Return the total number",
"tuples (b, n), where b is bag inside key # bag, and v",
"about, eg. \"light red\". # v = Empty list if bag contains no",
"are no bags this tree. total_inside = 0 for each_inside, num_inside in rule_dict[root]:",
"import sys VERBOSE = ('-v' in sys.argv) filename = sys.argv[1] def search_for_shiny_gold(root: str)",
"k = bag that the rule is about, eg. \"light red\". # v",
"# if VERBOSE: # print('each_rule, i, four_words:', each_rule, i, four_words) if len(four_words) ==",
"those bags. # # For example, \"light red bags contain 1 bright white",
"+= search_for_shiny_gold(each_inside) return shiny_gold_inside def search_inside(root: str) -> int: \"\"\"Search a tree of",
"[] rule_dict[k] = v if VERBOSE: print('rule_dict, len(rule_dict)', rule_dict, len(rule_dict)) shiny_gold = 0",
"that the rules is about. k = words[0] + ' ' + words[1]",
"red\". # v = Empty list if bag contains no other bags. Otherwise,",
"bag inside key # bag, and v is number of those bags. #",
"per rule. # k = bag that the rule is about, eg. \"light",
"search_for_shiny_gold(each_inside) return shiny_gold_inside def search_inside(root: str) -> int: \"\"\"Search a tree of bags.",
"filename = sys.argv[1] def search_for_shiny_gold(root: str) -> int: \"\"\"Search a tree of bags.",
"+ words[1] if VERBOSE: print('each_rule, words, k:', each_rule, words, k) v = []",
"shiny_gold_inside = num_inside else: shiny_gold_inside += search_for_shiny_gold(each_inside) return shiny_gold_inside def search_inside(root: str) ->",
"for each_rule in rules: words = each_rule.split() # First 2 words are the",
"bags. # # For example, \"light red bags contain 1 bright white bag,",
"num_inside + num_inside * search_inside(each_inside) return total_inside f = open(filename) whole_text = (f.read())",
"there are no shiny gold bags in this tree. shiny_gold_inside = 0 for",
"print('rules:', rules) # Dictionary contains k: v pairs, one pair per rule. #",
"= [] for i in words[4:]: four_words.append(i) # if VERBOSE: # print('each_rule, i,",
"' + four_words[2], int(four_words[0]))) four_words = [] rule_dict[k] = v if VERBOSE: print('rule_dict,",
"each_inside, num_inside in rule_dict[root]: if each_inside == 'shiny gold': shiny_gold_inside = num_inside else:",
"= Empty list if bag contains no other bags. Otherwise, contains list of",
"is bag inside key # bag, and v is number of those bags.",
"# Start of each group is indicated by a blank line. if VERBOSE:",
"= [] rule_dict[k] = v if VERBOSE: print('rule_dict, len(rule_dict)', rule_dict, len(rule_dict)) shiny_gold =",
"are no shiny gold bags in this tree. shiny_gold_inside = 0 for each_inside,",
"print('each_rule, i, four_words:', each_rule, i, four_words) if len(four_words) == 4: v.append((four_words[1] + '",
"tree. total_inside = 0 for each_inside, num_inside in rule_dict[root]: total_inside += num_inside +",
"= open(filename) whole_text = (f.read()) f.close() rules = whole_text.split('\\n') # Start of each",
"for each_inside, num_inside in rule_dict[root]: if each_inside == 'shiny gold': shiny_gold_inside = num_inside",
"each_rule[-22:] != 'contain no other bags.': four_words = [] for i in words[4:]:",
"no other bags.\" # {'dotted black': []} rule_dict = {} for each_rule in",
"to day 7 of AOC 2020, <NAME>. # https://adventofcode.com/2020/day/7 import sys VERBOSE =",
"k: v pairs, one pair per rule. # k = bag that the",
"# # Another example, # \"dotted black bags contain no other bags.\" #",
"\"\"\"Search a tree of bags. Return the number of shiny gold bags it",
"is about, eg. \"light red\". # v = Empty list if bag contains",
"inside key # bag, and v is number of those bags. # #",
"2)} # # Another example, # \"dotted black bags contain no other bags.\"",
"rules: words = each_rule.split() # First 2 words are the name of the",
"the rule is about, eg. \"light red\". # v = Empty list if",
"[('bright white', 1), ('muted yellow', 2)} # # Another example, # \"dotted black",
"Return the number of shiny gold bags it contains.\"\"\" if VERBOSE: print('root, rule_dict[root]:',",
"n), where b is bag inside key # bag, and v is number",
"\"dotted black bags contain no other bags.\" # {'dotted black': []} rule_dict =",
"in rule_dict[root]: total_inside += num_inside + num_inside * search_inside(each_inside) return total_inside f =",
"Otherwise, contains list of tuples (b, n), where b is bag inside key",
"# For example, \"light red bags contain 1 bright white bag, 2 muted",
"no bags this tree. total_inside = 0 for each_inside, num_inside in rule_dict[root]: total_inside",
"== 4: v.append((four_words[1] + ' ' + four_words[2], int(four_words[0]))) four_words = [] rule_dict[k]",
"in rule_dict: if search_for_shiny_gold(k) > 0: shiny_gold += 1 print('Part 1:', shiny_gold) print('Part",
"'shiny gold': shiny_gold_inside = num_inside else: shiny_gold_inside += search_for_shiny_gold(each_inside) return shiny_gold_inside def search_inside(root:",
"return 0 # ... there are no shiny gold bags in this tree.",
"bag contains no other bags. Otherwise, contains list of tuples (b, n), where",
"i in words[4:]: four_words.append(i) # if VERBOSE: # print('each_rule, i, four_words:', each_rule, i,",
"i, four_words) if len(four_words) == 4: v.append((four_words[1] + ' ' + four_words[2], int(four_words[0])))",
"of bags. Return the number of shiny gold bags it contains.\"\"\" if VERBOSE:",
"group is indicated by a blank line. if VERBOSE: print('rules:', rules) # Dictionary",
"f.close() rules = whole_text.split('\\n') # Start of each group is indicated by a",
"k in rule_dict: if search_for_shiny_gold(k) > 0: shiny_gold += 1 print('Part 1:', shiny_gold)",
"example, # \"dotted black bags contain no other bags.\" # {'dotted black': []}",
"each_rule in rules: words = each_rule.split() # First 2 words are the name",
"rule_dict[root]:', root, rule_dict[root]) if len(rule_dict[root]) == 0: # If value is empty list...",
"and v is number of those bags. # # For example, \"light red",
"the number of shiny gold bags it contains.\"\"\" if VERBOSE: print('root, rule_dict[root]:', root,",
"bag, and v is number of those bags. # # For example, \"light",
"the bag that the rules is about. k = words[0] + ' '",
"search_for_shiny_gold(k) > 0: shiny_gold += 1 print('Part 1:', shiny_gold) print('Part 2:', search_inside(root='shiny gold'))",
"tree of bags. Return the total number of bags it contains.\"\"\" if VERBOSE:",
"# print('each_rule, i, four_words:', each_rule, i, four_words) if len(four_words) == 4: v.append((four_words[1] +",
"no shiny gold bags in this tree. shiny_gold_inside = 0 for each_inside, num_inside",
"= [] if each_rule[-22:] != 'contain no other bags.': four_words = [] for",
"v is number of those bags. # # For example, \"light red bags",
"-> int: \"\"\"Search a tree of bags. Return the number of shiny gold",
"# {'dotted black': []} rule_dict = {} for each_rule in rules: words =",
"len(rule_dict)', rule_dict, len(rule_dict)) shiny_gold = 0 for k in rule_dict: if search_for_shiny_gold(k) >",
"... there are no bags this tree. total_inside = 0 for each_inside, num_inside",
"each group is indicated by a blank line. if VERBOSE: print('rules:', rules) #",
"each_rule, i, four_words) if len(four_words) == 4: v.append((four_words[1] + ' ' + four_words[2],",
"rule_dict[k] = v if VERBOSE: print('rule_dict, len(rule_dict)', rule_dict, len(rule_dict)) shiny_gold = 0 for",
"for i in words[4:]: four_words.append(i) # if VERBOSE: # print('each_rule, i, four_words:', each_rule,",
"contains k: v pairs, one pair per rule. # k = bag that",
"one pair per rule. # k = bag that the rule is about,",
"if VERBOSE: print('rule_dict, len(rule_dict)', rule_dict, len(rule_dict)) shiny_gold = 0 for k in rule_dict:",
"{} for each_rule in rules: words = each_rule.split() # First 2 words are",
"bags. Return the number of shiny gold bags it contains.\"\"\" if VERBOSE: print('root,",
"k) v = [] if each_rule[-22:] != 'contain no other bags.': four_words =",
"= {} for each_rule in rules: words = each_rule.split() # First 2 words",
"0 for each_inside, num_inside in rule_dict[root]: if each_inside == 'shiny gold': shiny_gold_inside =",
"four_words:', each_rule, i, four_words) if len(four_words) == 4: v.append((four_words[1] + ' ' +",
"in this tree. shiny_gold_inside = 0 for each_inside, num_inside in rule_dict[root]: if each_inside",
"VERBOSE: print('rule_dict, len(rule_dict)', rule_dict, len(rule_dict)) shiny_gold = 0 for k in rule_dict: if",
"# # For example, \"light red bags contain 1 bright white bag, 2",
"if VERBOSE: print('each_rule, words, k:', each_rule, words, k) v = [] if each_rule[-22:]",
"bags.\" # {'light red': [('bright white', 1), ('muted yellow', 2)} # # Another",
"if each_inside == 'shiny gold': shiny_gold_inside = num_inside else: shiny_gold_inside += search_for_shiny_gold(each_inside) return",
"if VERBOSE: print('rules:', rules) # Dictionary contains k: v pairs, one pair per",
"yellow', 2)} # # Another example, # \"dotted black bags contain no other",
"search_for_shiny_gold(root: str) -> int: \"\"\"Search a tree of bags. Return the number of",
"Empty list if bag contains no other bags. Otherwise, contains list of tuples",
"rule_dict, len(rule_dict)) shiny_gold = 0 for k in rule_dict: if search_for_shiny_gold(k) > 0:",
"= v if VERBOSE: print('rule_dict, len(rule_dict)', rule_dict, len(rule_dict)) shiny_gold = 0 for k",
"Start of each group is indicated by a blank line. if VERBOSE: print('rules:',",
"open(filename) whole_text = (f.read()) f.close() rules = whole_text.split('\\n') # Start of each group",
"other bags. Otherwise, contains list of tuples (b, n), where b is bag",
"# Dictionary contains k: v pairs, one pair per rule. # k =",
"whole_text = (f.read()) f.close() rules = whole_text.split('\\n') # Start of each group is",
"bright white bag, 2 muted yellow bags.\" # {'light red': [('bright white', 1),",
"[] for i in words[4:]: four_words.append(i) # if VERBOSE: # print('each_rule, i, four_words:',",
"bags in this tree. shiny_gold_inside = 0 for each_inside, num_inside in rule_dict[root]: if",
"shiny_gold_inside += search_for_shiny_gold(each_inside) return shiny_gold_inside def search_inside(root: str) -> int: \"\"\"Search a tree",
"tree. shiny_gold_inside = 0 for each_inside, num_inside in rule_dict[root]: if each_inside == 'shiny",
"example, \"light red bags contain 1 bright white bag, 2 muted yellow bags.\"",
"k = words[0] + ' ' + words[1] if VERBOSE: print('each_rule, words, k:',",
"str) -> int: \"\"\"Search a tree of bags. Return the number of shiny",
"# ... there are no shiny gold bags in this tree. shiny_gold_inside =",
"v pairs, one pair per rule. # k = bag that the rule",
"by a blank line. if VERBOSE: print('rules:', rules) # Dictionary contains k: v",
"for k in rule_dict: if search_for_shiny_gold(k) > 0: shiny_gold += 1 print('Part 1:',",
"print('root, rule_dict[root]:', root, rule_dict[root]) if len(rule_dict[root]) == 0: # If value is empty",
"whole_text.split('\\n') # Start of each group is indicated by a blank line. if",
"2020, <NAME>. # https://adventofcode.com/2020/day/7 import sys VERBOSE = ('-v' in sys.argv) filename =",
"https://adventofcode.com/2020/day/7 import sys VERBOSE = ('-v' in sys.argv) filename = sys.argv[1] def search_for_shiny_gold(root:",
"four_words = [] for i in words[4:]: four_words.append(i) # if VERBOSE: # print('each_rule,",
"2 muted yellow bags.\" # {'light red': [('bright white', 1), ('muted yellow', 2)}",
"[]} rule_dict = {} for each_rule in rules: words = each_rule.split() # First",
"other bags.\" # {'dotted black': []} rule_dict = {} for each_rule in rules:",
"bags it contains.\"\"\" if VERBOSE: print('root, rule_dict[root]:', root, rule_dict[root]) if len(rule_dict[root]) == 0:",
"-> int: \"\"\"Search a tree of bags. Return the total number of bags",
"i, four_words:', each_rule, i, four_words) if len(four_words) == 4: v.append((four_words[1] + ' '",
"in rule_dict[root]: if each_inside == 'shiny gold': shiny_gold_inside = num_inside else: shiny_gold_inside +=",
"First 2 words are the name of the bag that the rules is",
"b is bag inside key # bag, and v is number of those",
"is about. k = words[0] + ' ' + words[1] if VERBOSE: print('each_rule,",
"'contain no other bags.': four_words = [] for i in words[4:]: four_words.append(i) #",
"v.append((four_words[1] + ' ' + four_words[2], int(four_words[0]))) four_words = [] rule_dict[k] = v",
"if VERBOSE: # print('each_rule, i, four_words:', each_rule, i, four_words) if len(four_words) == 4:",
"black': []} rule_dict = {} for each_rule in rules: words = each_rule.split() #",
"f = open(filename) whole_text = (f.read()) f.close() rules = whole_text.split('\\n') # Start of",
"rules = whole_text.split('\\n') # Start of each group is indicated by a blank",
"bags. Otherwise, contains list of tuples (b, n), where b is bag inside",
"root, rule_dict[root]) if len(rule_dict[root]) == 0: # If value is empty list... return",
"words, k) v = [] if each_rule[-22:] != 'contain no other bags.': four_words",
"# k = bag that the rule is about, eg. \"light red\". #",
"bags.': four_words = [] for i in words[4:]: four_words.append(i) # if VERBOSE: #",
"are the name of the bag that the rules is about. k =",
"search_inside(each_inside) return total_inside f = open(filename) whole_text = (f.read()) f.close() rules = whole_text.split('\\n')",
"bags this tree. total_inside = 0 for each_inside, num_inside in rule_dict[root]: total_inside +=",
"Another example, # \"dotted black bags contain no other bags.\" # {'dotted black':",
"if VERBOSE: print('root, rule_dict[root]:', root, rule_dict[root]) if len(rule_dict[root]) == 0: # If value",
"AOC 2020, <NAME>. # https://adventofcode.com/2020/day/7 import sys VERBOSE = ('-v' in sys.argv) filename",
"len(four_words) == 4: v.append((four_words[1] + ' ' + four_words[2], int(four_words[0]))) four_words = []",
"print('rule_dict, len(rule_dict)', rule_dict, len(rule_dict)) shiny_gold = 0 for k in rule_dict: if search_for_shiny_gold(k)",
"if each_rule[-22:] != 'contain no other bags.': four_words = [] for i in",
"if bag contains no other bags. Otherwise, contains list of tuples (b, n),",
"0 for each_inside, num_inside in rule_dict[root]: total_inside += num_inside + num_inside * search_inside(each_inside)",
"= 0 for each_inside, num_inside in rule_dict[root]: total_inside += num_inside + num_inside *",
"= num_inside else: shiny_gold_inside += search_for_shiny_gold(each_inside) return shiny_gold_inside def search_inside(root: str) -> int:",
"contains no other bags. Otherwise, contains list of tuples (b, n), where b",
"len(rule_dict[root]) == 0: # If value is empty list... return 0 # ...",
"words = each_rule.split() # First 2 words are the name of the bag",
"(b, n), where b is bag inside key # bag, and v is",
"' ' + words[1] if VERBOSE: print('each_rule, words, k:', each_rule, words, k) v",
"str) -> int: \"\"\"Search a tree of bags. Return the total number of",
"bags. Return the total number of bags it contains.\"\"\" if VERBOSE: print('root, rule_dict[root]:',",
"For example, \"light red bags contain 1 bright white bag, 2 muted yellow",
"no other bags.': four_words = [] for i in words[4:]: four_words.append(i) # if",
"print('each_rule, words, k:', each_rule, words, k) v = [] if each_rule[-22:] != 'contain",
"+ four_words[2], int(four_words[0]))) four_words = [] rule_dict[k] = v if VERBOSE: print('rule_dict, len(rule_dict)',",
"there are no bags this tree. total_inside = 0 for each_inside, num_inside in",
"<filename>07-handy-haversacks/solution.py # Solution to day 7 of AOC 2020, <NAME>. # https://adventofcode.com/2020/day/7 import",
"{'dotted black': []} rule_dict = {} for each_rule in rules: words = each_rule.split()",
"\"\"\"Search a tree of bags. Return the total number of bags it contains.\"\"\"",
"value is empty list... return 0 # ... there are no shiny gold",
"+ ' ' + four_words[2], int(four_words[0]))) four_words = [] rule_dict[k] = v if",
"total number of bags it contains.\"\"\" if VERBOSE: print('root, rule_dict[root]:', root, rule_dict[root]) if",
"is empty list... return 0 # ... there are no shiny gold bags",
"four_words[2], int(four_words[0]))) four_words = [] rule_dict[k] = v if VERBOSE: print('rule_dict, len(rule_dict)', rule_dict,",
"# \"dotted black bags contain no other bags.\" # {'dotted black': []} rule_dict",
"the total number of bags it contains.\"\"\" if VERBOSE: print('root, rule_dict[root]:', root, rule_dict[root])",
"def search_for_shiny_gold(root: str) -> int: \"\"\"Search a tree of bags. Return the number",
"words[1] if VERBOSE: print('each_rule, words, k:', each_rule, words, k) v = [] if",
"rule_dict[root]: total_inside += num_inside + num_inside * search_inside(each_inside) return total_inside f = open(filename)",
"shiny_gold_inside = 0 for each_inside, num_inside in rule_dict[root]: if each_inside == 'shiny gold':",
"+ ' ' + words[1] if VERBOSE: print('each_rule, words, k:', each_rule, words, k)",
"of AOC 2020, <NAME>. # https://adventofcode.com/2020/day/7 import sys VERBOSE = ('-v' in sys.argv)",
"four_words = [] rule_dict[k] = v if VERBOSE: print('rule_dict, len(rule_dict)', rule_dict, len(rule_dict)) shiny_gold",
"where b is bag inside key # bag, and v is number of",
"# v = Empty list if bag contains no other bags. Otherwise, contains",
"tree of bags. Return the number of shiny gold bags it contains.\"\"\" if",
"sys.argv) filename = sys.argv[1] def search_for_shiny_gold(root: str) -> int: \"\"\"Search a tree of",
"rule_dict = {} for each_rule in rules: words = each_rule.split() # First 2",
"= (f.read()) f.close() rules = whole_text.split('\\n') # Start of each group is indicated",
"def search_inside(root: str) -> int: \"\"\"Search a tree of bags. Return the total",
"four_words) if len(four_words) == 4: v.append((four_words[1] + ' ' + four_words[2], int(four_words[0]))) four_words",
"number of bags it contains.\"\"\" if VERBOSE: print('root, rule_dict[root]:', root, rule_dict[root]) if len(rule_dict[root])",
"words are the name of the bag that the rules is about. k",
"name of the bag that the rules is about. k = words[0] +",
"four_words.append(i) # if VERBOSE: # print('each_rule, i, four_words:', each_rule, i, four_words) if len(four_words)",
"empty list... return 0 # ... there are no bags this tree. total_inside",
"a tree of bags. Return the number of shiny gold bags it contains.\"\"\"",
"if search_for_shiny_gold(k) > 0: shiny_gold += 1 print('Part 1:', shiny_gold) print('Part 2:', search_inside(root='shiny",
"# https://adventofcode.com/2020/day/7 import sys VERBOSE = ('-v' in sys.argv) filename = sys.argv[1] def",
"num_inside * search_inside(each_inside) return total_inside f = open(filename) whole_text = (f.read()) f.close() rules",
"# If value is empty list... return 0 # ... there are no",
"shiny gold bags in this tree. shiny_gold_inside = 0 for each_inside, num_inside in",
"Return the total number of bags it contains.\"\"\" if VERBOSE: print('root, rule_dict[root]:', root,",
"gold': shiny_gold_inside = num_inside else: shiny_gold_inside += search_for_shiny_gold(each_inside) return shiny_gold_inside def search_inside(root: str)",
"\"light red\". # v = Empty list if bag contains no other bags.",
"VERBOSE: print('root, rule_dict[root]:', root, rule_dict[root]) if len(rule_dict[root]) == 0: # If value is",
"is number of those bags. # # For example, \"light red bags contain",
"int: \"\"\"Search a tree of bags. Return the number of shiny gold bags",
"bags.\" # {'dotted black': []} rule_dict = {} for each_rule in rules: words",
"# {'light red': [('bright white', 1), ('muted yellow', 2)} # # Another example,",
"rules) # Dictionary contains k: v pairs, one pair per rule. # k",
"list if bag contains no other bags. Otherwise, contains list of tuples (b,",
"of the bag that the rules is about. k = words[0] + '",
"number of those bags. # # For example, \"light red bags contain 1",
"each_rule.split() # First 2 words are the name of the bag that the",
"line. if VERBOSE: print('rules:', rules) # Dictionary contains k: v pairs, one pair",
"If value is empty list... return 0 # ... there are no shiny",
"if len(four_words) == 4: v.append((four_words[1] + ' ' + four_words[2], int(four_words[0]))) four_words =",
"return total_inside f = open(filename) whole_text = (f.read()) f.close() rules = whole_text.split('\\n') #",
"2 words are the name of the bag that the rules is about.",
"0 # ... there are no bags this tree. total_inside = 0 for",
"If value is empty list... return 0 # ... there are no bags",
"v if VERBOSE: print('rule_dict, len(rule_dict)', rule_dict, len(rule_dict)) shiny_gold = 0 for k in",
"number of shiny gold bags it contains.\"\"\" if VERBOSE: print('root, rule_dict[root]:', root, rule_dict[root])",
"eg. \"light red\". # v = Empty list if bag contains no other",
"this tree. shiny_gold_inside = 0 for each_inside, num_inside in rule_dict[root]: if each_inside ==",
"return shiny_gold_inside def search_inside(root: str) -> int: \"\"\"Search a tree of bags. Return",
"\"light red bags contain 1 bright white bag, 2 muted yellow bags.\" #",
"1 bright white bag, 2 muted yellow bags.\" # {'light red': [('bright white',",
"sys VERBOSE = ('-v' in sys.argv) filename = sys.argv[1] def search_for_shiny_gold(root: str) ->",
"gold bags it contains.\"\"\" if VERBOSE: print('root, rule_dict[root]:', root, rule_dict[root]) if len(rule_dict[root]) ==",
"day 7 of AOC 2020, <NAME>. # https://adventofcode.com/2020/day/7 import sys VERBOSE = ('-v'",
"total_inside += num_inside + num_inside * search_inside(each_inside) return total_inside f = open(filename) whole_text",
"= whole_text.split('\\n') # Start of each group is indicated by a blank line.",
"bag, 2 muted yellow bags.\" # {'light red': [('bright white', 1), ('muted yellow',",
"words[0] + ' ' + words[1] if VERBOSE: print('each_rule, words, k:', each_rule, words,",
"+ num_inside * search_inside(each_inside) return total_inside f = open(filename) whole_text = (f.read()) f.close()",
"= ('-v' in sys.argv) filename = sys.argv[1] def search_for_shiny_gold(root: str) -> int: \"\"\"Search",
"== 'shiny gold': shiny_gold_inside = num_inside else: shiny_gold_inside += search_for_shiny_gold(each_inside) return shiny_gold_inside def",
"blank line. if VERBOSE: print('rules:', rules) # Dictionary contains k: v pairs, one",
"Solution to day 7 of AOC 2020, <NAME>. # https://adventofcode.com/2020/day/7 import sys VERBOSE",
"('-v' in sys.argv) filename = sys.argv[1] def search_for_shiny_gold(root: str) -> int: \"\"\"Search a",
"red': [('bright white', 1), ('muted yellow', 2)} # # Another example, # \"dotted",
"if len(rule_dict[root]) == 0: # If value is empty list... return 0 #",
"rule_dict[root]: if each_inside == 'shiny gold': shiny_gold_inside = num_inside else: shiny_gold_inside += search_for_shiny_gold(each_inside)",
"bags contain no other bags.\" # {'dotted black': []} rule_dict = {} for",
"('muted yellow', 2)} # # Another example, # \"dotted black bags contain no",
"num_inside else: shiny_gold_inside += search_for_shiny_gold(each_inside) return shiny_gold_inside def search_inside(root: str) -> int: \"\"\"Search",
"0 for k in rule_dict: if search_for_shiny_gold(k) > 0: shiny_gold += 1 print('Part",
"contains.\"\"\" if VERBOSE: print('root, rule_dict[root]:', root, rule_dict[root]) if len(rule_dict[root]) == 0: # If",
"is empty list... return 0 # ... there are no bags this tree.",
"rules is about. k = words[0] + ' ' + words[1] if VERBOSE:",
"= each_rule.split() # First 2 words are the name of the bag that",
"contains list of tuples (b, n), where b is bag inside key #",
"rule_dict: if search_for_shiny_gold(k) > 0: shiny_gold += 1 print('Part 1:', shiny_gold) print('Part 2:',",
"== 0: # If value is empty list... return 0 # ... there",
"words[4:]: four_words.append(i) # if VERBOSE: # print('each_rule, i, four_words:', each_rule, i, four_words) if",
"the name of the bag that the rules is about. k = words[0]",
"k:', each_rule, words, k) v = [] if each_rule[-22:] != 'contain no other",
"4: v.append((four_words[1] + ' ' + four_words[2], int(four_words[0]))) four_words = [] rule_dict[k] =",
"the rules is about. k = words[0] + ' ' + words[1] if",
"about. k = words[0] + ' ' + words[1] if VERBOSE: print('each_rule, words,",
"= 0 for k in rule_dict: if search_for_shiny_gold(k) > 0: shiny_gold += 1",
"of bags. Return the total number of bags it contains.\"\"\" if VERBOSE: print('root,",
"return 0 # ... there are no bags this tree. total_inside = 0",
"a tree of bags. Return the total number of bags it contains.\"\"\" if",
"= words[0] + ' ' + words[1] if VERBOSE: print('each_rule, words, k:', each_rule,",
"... there are no shiny gold bags in this tree. shiny_gold_inside = 0",
"shiny gold bags it contains.\"\"\" if VERBOSE: print('root, rule_dict[root]:', root, rule_dict[root]) if len(rule_dict[root])",
"list of tuples (b, n), where b is bag inside key # bag,",
"[] if each_rule[-22:] != 'contain no other bags.': four_words = [] for i",
"= 0 for each_inside, num_inside in rule_dict[root]: if each_inside == 'shiny gold': shiny_gold_inside",
"yellow bags.\" # {'light red': [('bright white', 1), ('muted yellow', 2)} # #",
"gold bags in this tree. shiny_gold_inside = 0 for each_inside, num_inside in rule_dict[root]:",
"# First 2 words are the name of the bag that the rules",
"{'light red': [('bright white', 1), ('muted yellow', 2)} # # Another example, #",
"= sys.argv[1] def search_for_shiny_gold(root: str) -> int: \"\"\"Search a tree of bags. Return",
"each_rule, words, k) v = [] if each_rule[-22:] != 'contain no other bags.':",
"v = Empty list if bag contains no other bags. Otherwise, contains list",
"is indicated by a blank line. if VERBOSE: print('rules:', rules) # Dictionary contains",
"it contains.\"\"\" if VERBOSE: print('root, rule_dict[root]:', root, rule_dict[root]) if len(rule_dict[root]) == 0: #"
] |
[] |
[
"document_root=None): messages.error(request, \"접근 불가\") return redirect('/') urlpatterns = [ path('', views.AllListView.as_view(), name='all_list'), path('free/',",
"views.free_detail_view, name='free_detail'), path('<int:pk>/edit/', views.free_edit_view, name='free_edit'), path('<int:pk>/delete/', views.free_delete_view, name='free_delete'), path('download/<int:pk>', views.free_download_view, name=\"free_download\"), path('<int:pk>/comment/write/', views.comment_write_view,",
"django.urls import path from . import views from django.contrib import messages from django.shortcuts",
". import views from django.contrib import messages from django.shortcuts import redirect app_name =",
"from django.shortcuts import redirect app_name = 'free' def protected_file(request, path, document_root=None): messages.error(request, \"접근",
"path('information/', views.InformationListView.as_view(), name='information_list'), path('write/', views.free_write_view, name='free_write'), path('<int:pk>/', views.free_detail_view, name='free_detail'), path('<int:pk>/edit/', views.free_edit_view, name='free_edit'), path('<int:pk>/delete/',",
"django.conf import settings from django.conf.urls.static import static from django.urls import path from .",
"import static from django.urls import path from . import views from django.contrib import",
"[ path('', views.AllListView.as_view(), name='all_list'), path('free/', views.FreeListView.as_view(), name='free_list'), path('question/', views.QuestionListView.as_view(), name='question_list'), path('information/', views.InformationListView.as_view(), name='information_list'),",
"\"접근 불가\") return redirect('/') urlpatterns = [ path('', views.AllListView.as_view(), name='all_list'), path('free/', views.FreeListView.as_view(), name='free_list'),",
"redirect app_name = 'free' def protected_file(request, path, document_root=None): messages.error(request, \"접근 불가\") return redirect('/')",
"messages from django.shortcuts import redirect app_name = 'free' def protected_file(request, path, document_root=None): messages.error(request,",
"name='free_list'), path('question/', views.QuestionListView.as_view(), name='question_list'), path('information/', views.InformationListView.as_view(), name='information_list'), path('write/', views.free_write_view, name='free_write'), path('<int:pk>/', views.free_detail_view, name='free_detail'),",
"static from django.urls import path from . import views from django.contrib import messages",
"views.free_download_view, name=\"free_download\"), path('<int:pk>/comment/write/', views.comment_write_view, name='comment_write'), path('<int:pk>/comment/delete/', views.comment_delete_view, name='comment_delete'), ] urlpatterns += static(settings.MEDIA_URL, protected_file,",
"path('<int:pk>/edit/', views.free_edit_view, name='free_edit'), path('<int:pk>/delete/', views.free_delete_view, name='free_delete'), path('download/<int:pk>', views.free_download_view, name=\"free_download\"), path('<int:pk>/comment/write/', views.comment_write_view, name='comment_write'), path('<int:pk>/comment/delete/',",
"from django.conf.urls.static import static from django.urls import path from . import views from",
"views.free_write_view, name='free_write'), path('<int:pk>/', views.free_detail_view, name='free_detail'), path('<int:pk>/edit/', views.free_edit_view, name='free_edit'), path('<int:pk>/delete/', views.free_delete_view, name='free_delete'), path('download/<int:pk>', views.free_download_view,",
"path('question/', views.QuestionListView.as_view(), name='question_list'), path('information/', views.InformationListView.as_view(), name='information_list'), path('write/', views.free_write_view, name='free_write'), path('<int:pk>/', views.free_detail_view, name='free_detail'), path('<int:pk>/edit/',",
"views from django.contrib import messages from django.shortcuts import redirect app_name = 'free' def",
"path('download/<int:pk>', views.free_download_view, name=\"free_download\"), path('<int:pk>/comment/write/', views.comment_write_view, name='comment_write'), path('<int:pk>/comment/delete/', views.comment_delete_view, name='comment_delete'), ] urlpatterns += static(settings.MEDIA_URL,",
"return redirect('/') urlpatterns = [ path('', views.AllListView.as_view(), name='all_list'), path('free/', views.FreeListView.as_view(), name='free_list'), path('question/', views.QuestionListView.as_view(),",
"app_name = 'free' def protected_file(request, path, document_root=None): messages.error(request, \"접근 불가\") return redirect('/') urlpatterns",
"= [ path('', views.AllListView.as_view(), name='all_list'), path('free/', views.FreeListView.as_view(), name='free_list'), path('question/', views.QuestionListView.as_view(), name='question_list'), path('information/', views.InformationListView.as_view(),",
"name='question_list'), path('information/', views.InformationListView.as_view(), name='information_list'), path('write/', views.free_write_view, name='free_write'), path('<int:pk>/', views.free_detail_view, name='free_detail'), path('<int:pk>/edit/', views.free_edit_view, name='free_edit'),",
"import messages from django.shortcuts import redirect app_name = 'free' def protected_file(request, path, document_root=None):",
"path('write/', views.free_write_view, name='free_write'), path('<int:pk>/', views.free_detail_view, name='free_detail'), path('<int:pk>/edit/', views.free_edit_view, name='free_edit'), path('<int:pk>/delete/', views.free_delete_view, name='free_delete'), path('download/<int:pk>',",
"import redirect app_name = 'free' def protected_file(request, path, document_root=None): messages.error(request, \"접근 불가\") return",
"protected_file(request, path, document_root=None): messages.error(request, \"접근 불가\") return redirect('/') urlpatterns = [ path('', views.AllListView.as_view(),",
"from django.urls import path from . import views from django.contrib import messages from",
"views.free_edit_view, name='free_edit'), path('<int:pk>/delete/', views.free_delete_view, name='free_delete'), path('download/<int:pk>', views.free_download_view, name=\"free_download\"), path('<int:pk>/comment/write/', views.comment_write_view, name='comment_write'), path('<int:pk>/comment/delete/', views.comment_delete_view,",
"import views from django.contrib import messages from django.shortcuts import redirect app_name = 'free'",
"def protected_file(request, path, document_root=None): messages.error(request, \"접근 불가\") return redirect('/') urlpatterns = [ path('',",
"'free' def protected_file(request, path, document_root=None): messages.error(request, \"접근 불가\") return redirect('/') urlpatterns = [",
"import settings from django.conf.urls.static import static from django.urls import path from . import",
"views.AllListView.as_view(), name='all_list'), path('free/', views.FreeListView.as_view(), name='free_list'), path('question/', views.QuestionListView.as_view(), name='question_list'), path('information/', views.InformationListView.as_view(), name='information_list'), path('write/', views.free_write_view,",
"path, document_root=None): messages.error(request, \"접근 불가\") return redirect('/') urlpatterns = [ path('', views.AllListView.as_view(), name='all_list'),",
"redirect('/') urlpatterns = [ path('', views.AllListView.as_view(), name='all_list'), path('free/', views.FreeListView.as_view(), name='free_list'), path('question/', views.QuestionListView.as_view(), name='question_list'),",
"name='free_edit'), path('<int:pk>/delete/', views.free_delete_view, name='free_delete'), path('download/<int:pk>', views.free_download_view, name=\"free_download\"), path('<int:pk>/comment/write/', views.comment_write_view, name='comment_write'), path('<int:pk>/comment/delete/', views.comment_delete_view, name='comment_delete'),",
"django.shortcuts import redirect app_name = 'free' def protected_file(request, path, document_root=None): messages.error(request, \"접근 불가\")",
"name='information_list'), path('write/', views.free_write_view, name='free_write'), path('<int:pk>/', views.free_detail_view, name='free_detail'), path('<int:pk>/edit/', views.free_edit_view, name='free_edit'), path('<int:pk>/delete/', views.free_delete_view, name='free_delete'),",
"urlpatterns = [ path('', views.AllListView.as_view(), name='all_list'), path('free/', views.FreeListView.as_view(), name='free_list'), path('question/', views.QuestionListView.as_view(), name='question_list'), path('information/',",
"views.FreeListView.as_view(), name='free_list'), path('question/', views.QuestionListView.as_view(), name='question_list'), path('information/', views.InformationListView.as_view(), name='information_list'), path('write/', views.free_write_view, name='free_write'), path('<int:pk>/', views.free_detail_view,",
"from django.contrib import messages from django.shortcuts import redirect app_name = 'free' def protected_file(request,",
"= 'free' def protected_file(request, path, document_root=None): messages.error(request, \"접근 불가\") return redirect('/') urlpatterns =",
"path('<int:pk>/delete/', views.free_delete_view, name='free_delete'), path('download/<int:pk>', views.free_download_view, name=\"free_download\"), path('<int:pk>/comment/write/', views.comment_write_view, name='comment_write'), path('<int:pk>/comment/delete/', views.comment_delete_view, name='comment_delete'), ]",
"from . import views from django.contrib import messages from django.shortcuts import redirect app_name",
"from django.conf import settings from django.conf.urls.static import static from django.urls import path from",
"불가\") return redirect('/') urlpatterns = [ path('', views.AllListView.as_view(), name='all_list'), path('free/', views.FreeListView.as_view(), name='free_list'), path('question/',",
"messages.error(request, \"접근 불가\") return redirect('/') urlpatterns = [ path('', views.AllListView.as_view(), name='all_list'), path('free/', views.FreeListView.as_view(),",
"django.contrib import messages from django.shortcuts import redirect app_name = 'free' def protected_file(request, path,",
"path('<int:pk>/', views.free_detail_view, name='free_detail'), path('<int:pk>/edit/', views.free_edit_view, name='free_edit'), path('<int:pk>/delete/', views.free_delete_view, name='free_delete'), path('download/<int:pk>', views.free_download_view, name=\"free_download\"), path('<int:pk>/comment/write/',",
"name='free_delete'), path('download/<int:pk>', views.free_download_view, name=\"free_download\"), path('<int:pk>/comment/write/', views.comment_write_view, name='comment_write'), path('<int:pk>/comment/delete/', views.comment_delete_view, name='comment_delete'), ] urlpatterns +=",
"path('free/', views.FreeListView.as_view(), name='free_list'), path('question/', views.QuestionListView.as_view(), name='question_list'), path('information/', views.InformationListView.as_view(), name='information_list'), path('write/', views.free_write_view, name='free_write'), path('<int:pk>/',",
"name='free_write'), path('<int:pk>/', views.free_detail_view, name='free_detail'), path('<int:pk>/edit/', views.free_edit_view, name='free_edit'), path('<int:pk>/delete/', views.free_delete_view, name='free_delete'), path('download/<int:pk>', views.free_download_view, name=\"free_download\"),",
"views.free_delete_view, name='free_delete'), path('download/<int:pk>', views.free_download_view, name=\"free_download\"), path('<int:pk>/comment/write/', views.comment_write_view, name='comment_write'), path('<int:pk>/comment/delete/', views.comment_delete_view, name='comment_delete'), ] urlpatterns",
"views.QuestionListView.as_view(), name='question_list'), path('information/', views.InformationListView.as_view(), name='information_list'), path('write/', views.free_write_view, name='free_write'), path('<int:pk>/', views.free_detail_view, name='free_detail'), path('<int:pk>/edit/', views.free_edit_view,",
"path from . import views from django.contrib import messages from django.shortcuts import redirect",
"name='free_detail'), path('<int:pk>/edit/', views.free_edit_view, name='free_edit'), path('<int:pk>/delete/', views.free_delete_view, name='free_delete'), path('download/<int:pk>', views.free_download_view, name=\"free_download\"), path('<int:pk>/comment/write/', views.comment_write_view, name='comment_write'),",
"name='all_list'), path('free/', views.FreeListView.as_view(), name='free_list'), path('question/', views.QuestionListView.as_view(), name='question_list'), path('information/', views.InformationListView.as_view(), name='information_list'), path('write/', views.free_write_view, name='free_write'),",
"import path from . import views from django.contrib import messages from django.shortcuts import",
"settings from django.conf.urls.static import static from django.urls import path from . import views",
"name=\"free_download\"), path('<int:pk>/comment/write/', views.comment_write_view, name='comment_write'), path('<int:pk>/comment/delete/', views.comment_delete_view, name='comment_delete'), ] urlpatterns += static(settings.MEDIA_URL, protected_file, document_root=settings.MEDIA_ROOT)",
"django.conf.urls.static import static from django.urls import path from . import views from django.contrib",
"path('', views.AllListView.as_view(), name='all_list'), path('free/', views.FreeListView.as_view(), name='free_list'), path('question/', views.QuestionListView.as_view(), name='question_list'), path('information/', views.InformationListView.as_view(), name='information_list'), path('write/',",
"views.InformationListView.as_view(), name='information_list'), path('write/', views.free_write_view, name='free_write'), path('<int:pk>/', views.free_detail_view, name='free_detail'), path('<int:pk>/edit/', views.free_edit_view, name='free_edit'), path('<int:pk>/delete/', views.free_delete_view,"
] |
[
"dt.fit(X_train, y_train) preds = dt.predict(X_test) accuracies.append((preds == y_test).mean()) f, ax = plt.subplots(figsize=(7, 5))",
"21:04:18 2017 @author: pd \"\"\" #from IPython import get_ipython #get_ipython().magic('reset -sf') import numpy",
"-sf') import numpy as np from sklearn import datasets from sklearn.tree import DecisionTreeClassifier",
"as np from sklearn import datasets from sklearn.tree import DecisionTreeClassifier import matplotlib.pyplot as",
"-*- coding: utf-8 -*- \"\"\" Created on Sun Feb 19 21:04:18 2017 @author:",
"sklearn import datasets from sklearn.tree import DecisionTreeClassifier import matplotlib.pyplot as plt from sklearn.cross_validation",
"= train_test_split(X,y, test_size=0.25, random_state=0) accuracies = [] for x in np.arange(1, n_features+1,5): dt",
"import get_ipython #get_ipython().magic('reset -sf') import numpy as np from sklearn import datasets from",
"#get_ipython().magic('reset -sf') import numpy as np from sklearn import datasets from sklearn.tree import",
"pd \"\"\" #from IPython import get_ipython #get_ipython().magic('reset -sf') import numpy as np from",
"import numpy as np from sklearn import datasets from sklearn.tree import DecisionTreeClassifier import",
"19 21:04:18 2017 @author: pd \"\"\" #from IPython import get_ipython #get_ipython().magic('reset -sf') import",
"n_features+1,5): dt = DecisionTreeClassifier(max_depth=x) dt.fit(X_train, y_train) preds = dt.predict(X_test) accuracies.append((preds == y_test).mean()) f,",
"y_train, y_test = train_test_split(X,y, test_size=0.25, random_state=0) accuracies = [] for x in np.arange(1,",
"= datasets.make_classification(750, n_features=n_features, n_informative=5, random_state=29) X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.25, random_state=0)",
"n_features=200 X, y = datasets.make_classification(750, n_features=n_features, n_informative=5, random_state=29) X_train, X_test, y_train, y_test =",
"-*- \"\"\" Created on Sun Feb 19 21:04:18 2017 @author: pd \"\"\" #from",
"n_features=n_features, n_informative=5, random_state=29) X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.25, random_state=0) accuracies =",
"x in np.arange(1, n_features+1,5): dt = DecisionTreeClassifier(max_depth=x) dt.fit(X_train, y_train) preds = dt.predict(X_test) accuracies.append((preds",
"preds = dt.predict(X_test) accuracies.append((preds == y_test).mean()) f, ax = plt.subplots(figsize=(7, 5)) ax.plot(range(1, n_features+1,5),",
"5)) ax.plot(range(1, n_features+1,5), accuracies, 'ko') #ax.plot(range(1, n_features+1)[:12], accuracies[:12], color='k') ax.set_title(\"Decision Tree Accuracy\") ax.set_ylabel(\"%",
"sklearn.cross_validation import train_test_split n_features=200 X, y = datasets.make_classification(750, n_features=n_features, n_informative=5, random_state=29) X_train, X_test,",
"= plt.subplots(figsize=(7, 5)) ax.plot(range(1, n_features+1,5), accuracies, 'ko') #ax.plot(range(1, n_features+1)[:12], accuracies[:12], color='k') ax.set_title(\"Decision Tree",
"import DecisionTreeClassifier import matplotlib.pyplot as plt from sklearn.cross_validation import train_test_split n_features=200 X, y",
"from sklearn import datasets from sklearn.tree import DecisionTreeClassifier import matplotlib.pyplot as plt from",
"f, ax = plt.subplots(figsize=(7, 5)) ax.plot(range(1, n_features+1,5), accuracies, 'ko') #ax.plot(range(1, n_features+1)[:12], accuracies[:12], color='k')",
"[] for x in np.arange(1, n_features+1,5): dt = DecisionTreeClassifier(max_depth=x) dt.fit(X_train, y_train) preds =",
"= [] for x in np.arange(1, n_features+1,5): dt = DecisionTreeClassifier(max_depth=x) dt.fit(X_train, y_train) preds",
"datasets.make_classification(750, n_features=n_features, n_informative=5, random_state=29) X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.25, random_state=0) accuracies",
"= DecisionTreeClassifier(max_depth=x) dt.fit(X_train, y_train) preds = dt.predict(X_test) accuracies.append((preds == y_test).mean()) f, ax =",
"X_test, y_train, y_test = train_test_split(X,y, test_size=0.25, random_state=0) accuracies = [] for x in",
"# -*- coding: utf-8 -*- \"\"\" Created on Sun Feb 19 21:04:18 2017",
"accuracies = [] for x in np.arange(1, n_features+1,5): dt = DecisionTreeClassifier(max_depth=x) dt.fit(X_train, y_train)",
"2017 @author: pd \"\"\" #from IPython import get_ipython #get_ipython().magic('reset -sf') import numpy as",
"n_informative=5, random_state=29) X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.25, random_state=0) accuracies = []",
"on Sun Feb 19 21:04:18 2017 @author: pd \"\"\" #from IPython import get_ipython",
"train_test_split n_features=200 X, y = datasets.make_classification(750, n_features=n_features, n_informative=5, random_state=29) X_train, X_test, y_train, y_test",
"test_size=0.25, random_state=0) accuracies = [] for x in np.arange(1, n_features+1,5): dt = DecisionTreeClassifier(max_depth=x)",
"accuracies.append((preds == y_test).mean()) f, ax = plt.subplots(figsize=(7, 5)) ax.plot(range(1, n_features+1,5), accuracies, 'ko') #ax.plot(range(1,",
"y_test = train_test_split(X,y, test_size=0.25, random_state=0) accuracies = [] for x in np.arange(1, n_features+1,5):",
"train_test_split(X,y, test_size=0.25, random_state=0) accuracies = [] for x in np.arange(1, n_features+1,5): dt =",
"= dt.predict(X_test) accuracies.append((preds == y_test).mean()) f, ax = plt.subplots(figsize=(7, 5)) ax.plot(range(1, n_features+1,5), accuracies,",
"from sklearn.cross_validation import train_test_split n_features=200 X, y = datasets.make_classification(750, n_features=n_features, n_informative=5, random_state=29) X_train,",
"import train_test_split n_features=200 X, y = datasets.make_classification(750, n_features=n_features, n_informative=5, random_state=29) X_train, X_test, y_train,",
"'ko') #ax.plot(range(1, n_features+1)[:12], accuracies[:12], color='k') ax.set_title(\"Decision Tree Accuracy\") ax.set_ylabel(\"% Correct\") ax.set_xlabel(\"Max Depth\") plt.show()",
"ax = plt.subplots(figsize=(7, 5)) ax.plot(range(1, n_features+1,5), accuracies, 'ko') #ax.plot(range(1, n_features+1)[:12], accuracies[:12], color='k') ax.set_title(\"Decision",
"X, y = datasets.make_classification(750, n_features=n_features, n_informative=5, random_state=29) X_train, X_test, y_train, y_test = train_test_split(X,y,",
"python2 # -*- coding: utf-8 -*- \"\"\" Created on Sun Feb 19 21:04:18",
"X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.25, random_state=0) accuracies = [] for x",
"numpy as np from sklearn import datasets from sklearn.tree import DecisionTreeClassifier import matplotlib.pyplot",
"import datasets from sklearn.tree import DecisionTreeClassifier import matplotlib.pyplot as plt from sklearn.cross_validation import",
"IPython import get_ipython #get_ipython().magic('reset -sf') import numpy as np from sklearn import datasets",
"random_state=0) accuracies = [] for x in np.arange(1, n_features+1,5): dt = DecisionTreeClassifier(max_depth=x) dt.fit(X_train,",
"@author: pd \"\"\" #from IPython import get_ipython #get_ipython().magic('reset -sf') import numpy as np",
"get_ipython #get_ipython().magic('reset -sf') import numpy as np from sklearn import datasets from sklearn.tree",
"\"\"\" Created on Sun Feb 19 21:04:18 2017 @author: pd \"\"\" #from IPython",
"datasets from sklearn.tree import DecisionTreeClassifier import matplotlib.pyplot as plt from sklearn.cross_validation import train_test_split",
"plt from sklearn.cross_validation import train_test_split n_features=200 X, y = datasets.make_classification(750, n_features=n_features, n_informative=5, random_state=29)",
"from sklearn.tree import DecisionTreeClassifier import matplotlib.pyplot as plt from sklearn.cross_validation import train_test_split n_features=200",
"ax.plot(range(1, n_features+1,5), accuracies, 'ko') #ax.plot(range(1, n_features+1)[:12], accuracies[:12], color='k') ax.set_title(\"Decision Tree Accuracy\") ax.set_ylabel(\"% Correct\")",
"#!/usr/bin/env python2 # -*- coding: utf-8 -*- \"\"\" Created on Sun Feb 19",
"y_test).mean()) f, ax = plt.subplots(figsize=(7, 5)) ax.plot(range(1, n_features+1,5), accuracies, 'ko') #ax.plot(range(1, n_features+1)[:12], accuracies[:12],",
"plt.subplots(figsize=(7, 5)) ax.plot(range(1, n_features+1,5), accuracies, 'ko') #ax.plot(range(1, n_features+1)[:12], accuracies[:12], color='k') ax.set_title(\"Decision Tree Accuracy\")",
"dt.predict(X_test) accuracies.append((preds == y_test).mean()) f, ax = plt.subplots(figsize=(7, 5)) ax.plot(range(1, n_features+1,5), accuracies, 'ko')",
"matplotlib.pyplot as plt from sklearn.cross_validation import train_test_split n_features=200 X, y = datasets.make_classification(750, n_features=n_features,",
"sklearn.tree import DecisionTreeClassifier import matplotlib.pyplot as plt from sklearn.cross_validation import train_test_split n_features=200 X,",
"== y_test).mean()) f, ax = plt.subplots(figsize=(7, 5)) ax.plot(range(1, n_features+1,5), accuracies, 'ko') #ax.plot(range(1, n_features+1)[:12],",
"random_state=29) X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.25, random_state=0) accuracies = [] for",
"DecisionTreeClassifier(max_depth=x) dt.fit(X_train, y_train) preds = dt.predict(X_test) accuracies.append((preds == y_test).mean()) f, ax = plt.subplots(figsize=(7,",
"Feb 19 21:04:18 2017 @author: pd \"\"\" #from IPython import get_ipython #get_ipython().magic('reset -sf')",
"DecisionTreeClassifier import matplotlib.pyplot as plt from sklearn.cross_validation import train_test_split n_features=200 X, y =",
"Sun Feb 19 21:04:18 2017 @author: pd \"\"\" #from IPython import get_ipython #get_ipython().magic('reset",
"for x in np.arange(1, n_features+1,5): dt = DecisionTreeClassifier(max_depth=x) dt.fit(X_train, y_train) preds = dt.predict(X_test)",
"\"\"\" #from IPython import get_ipython #get_ipython().magic('reset -sf') import numpy as np from sklearn",
"np from sklearn import datasets from sklearn.tree import DecisionTreeClassifier import matplotlib.pyplot as plt",
"utf-8 -*- \"\"\" Created on Sun Feb 19 21:04:18 2017 @author: pd \"\"\"",
"y = datasets.make_classification(750, n_features=n_features, n_informative=5, random_state=29) X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.25,",
"dt = DecisionTreeClassifier(max_depth=x) dt.fit(X_train, y_train) preds = dt.predict(X_test) accuracies.append((preds == y_test).mean()) f, ax",
"np.arange(1, n_features+1,5): dt = DecisionTreeClassifier(max_depth=x) dt.fit(X_train, y_train) preds = dt.predict(X_test) accuracies.append((preds == y_test).mean())",
"y_train) preds = dt.predict(X_test) accuracies.append((preds == y_test).mean()) f, ax = plt.subplots(figsize=(7, 5)) ax.plot(range(1,",
"coding: utf-8 -*- \"\"\" Created on Sun Feb 19 21:04:18 2017 @author: pd",
"in np.arange(1, n_features+1,5): dt = DecisionTreeClassifier(max_depth=x) dt.fit(X_train, y_train) preds = dt.predict(X_test) accuracies.append((preds ==",
"n_features+1,5), accuracies, 'ko') #ax.plot(range(1, n_features+1)[:12], accuracies[:12], color='k') ax.set_title(\"Decision Tree Accuracy\") ax.set_ylabel(\"% Correct\") ax.set_xlabel(\"Max",
"accuracies, 'ko') #ax.plot(range(1, n_features+1)[:12], accuracies[:12], color='k') ax.set_title(\"Decision Tree Accuracy\") ax.set_ylabel(\"% Correct\") ax.set_xlabel(\"Max Depth\")",
"as plt from sklearn.cross_validation import train_test_split n_features=200 X, y = datasets.make_classification(750, n_features=n_features, n_informative=5,",
"import matplotlib.pyplot as plt from sklearn.cross_validation import train_test_split n_features=200 X, y = datasets.make_classification(750,",
"Created on Sun Feb 19 21:04:18 2017 @author: pd \"\"\" #from IPython import",
"#from IPython import get_ipython #get_ipython().magic('reset -sf') import numpy as np from sklearn import"
] |
[
"!= y: value = Levenshtein.distance(lines[x], lines[y]) distances[x,y] = value if value < 5:",
"# coding: utf-8 import sys import Levenshtein import numpy as np assert len(sys.argv)",
"if value < 5: message = \"lines {} and {} look similar\\n{}{}\\n\".format(x, y,",
"np assert len(sys.argv) > 1 with open(sys.argv[1], 'r', encoding='utf-8') as file: lines =",
"= Levenshtein.distance(lines[x], lines[y]) distances[x,y] = value if value < 5: message = \"lines",
"= value if value < 5: message = \"lines {} and {} look",
"range(x + 1, n_lines): if x != y: value = Levenshtein.distance(lines[x], lines[y]) distances[x,y]",
"y: value = Levenshtein.distance(lines[x], lines[y]) distances[x,y] = value if value < 5: message",
"assert len(sys.argv) > 1 with open(sys.argv[1], 'r', encoding='utf-8') as file: lines = file.readlines()",
"in range(n_lines): for y in range(x + 1, n_lines): if x != y:",
"and {} look similar\\n{}{}\\n\".format(x, y, lines[x], lines[y]) messages.append(message) for message in messages: print(message)",
"1, n_lines): if x != y: value = Levenshtein.distance(lines[x], lines[y]) distances[x,y] = value",
"value < 5: message = \"lines {} and {} look similar\\n{}{}\\n\".format(x, y, lines[x],",
"< 5: message = \"lines {} and {} look similar\\n{}{}\\n\".format(x, y, lines[x], lines[y])",
"messages = [] for x in range(n_lines): for y in range(x + 1,",
"as np assert len(sys.argv) > 1 with open(sys.argv[1], 'r', encoding='utf-8') as file: lines",
"distances[x,y] = value if value < 5: message = \"lines {} and {}",
"5: message = \"lines {} and {} look similar\\n{}{}\\n\".format(x, y, lines[x], lines[y]) messages.append(message)",
"#!/usr/bin/python # coding: utf-8 import sys import Levenshtein import numpy as np assert",
"encoding='utf-8') as file: lines = file.readlines() n_lines = len(lines) distances = np.zeros((n_lines, n_lines),",
"for y in range(x + 1, n_lines): if x != y: value =",
"= \"lines {} and {} look similar\\n{}{}\\n\".format(x, y, lines[x], lines[y]) messages.append(message) for message",
"len(sys.argv) > 1 with open(sys.argv[1], 'r', encoding='utf-8') as file: lines = file.readlines() n_lines",
"x in range(n_lines): for y in range(x + 1, n_lines): if x !=",
"= [] for x in range(n_lines): for y in range(x + 1, n_lines):",
"Levenshtein.distance(lines[x], lines[y]) distances[x,y] = value if value < 5: message = \"lines {}",
"\"lines {} and {} look similar\\n{}{}\\n\".format(x, y, lines[x], lines[y]) messages.append(message) for message in",
"= file.readlines() n_lines = len(lines) distances = np.zeros((n_lines, n_lines), dtype=int) messages = []",
"open(sys.argv[1], 'r', encoding='utf-8') as file: lines = file.readlines() n_lines = len(lines) distances =",
"import Levenshtein import numpy as np assert len(sys.argv) > 1 with open(sys.argv[1], 'r',",
"y in range(x + 1, n_lines): if x != y: value = Levenshtein.distance(lines[x],",
"sys import Levenshtein import numpy as np assert len(sys.argv) > 1 with open(sys.argv[1],",
"file: lines = file.readlines() n_lines = len(lines) distances = np.zeros((n_lines, n_lines), dtype=int) messages",
"= np.zeros((n_lines, n_lines), dtype=int) messages = [] for x in range(n_lines): for y",
"range(n_lines): for y in range(x + 1, n_lines): if x != y: value",
"if x != y: value = Levenshtein.distance(lines[x], lines[y]) distances[x,y] = value if value",
"value = Levenshtein.distance(lines[x], lines[y]) distances[x,y] = value if value < 5: message =",
"n_lines): if x != y: value = Levenshtein.distance(lines[x], lines[y]) distances[x,y] = value if",
"as file: lines = file.readlines() n_lines = len(lines) distances = np.zeros((n_lines, n_lines), dtype=int)",
"[] for x in range(n_lines): for y in range(x + 1, n_lines): if",
"lines = file.readlines() n_lines = len(lines) distances = np.zeros((n_lines, n_lines), dtype=int) messages =",
"= len(lines) distances = np.zeros((n_lines, n_lines), dtype=int) messages = [] for x in",
"import sys import Levenshtein import numpy as np assert len(sys.argv) > 1 with",
"'r', encoding='utf-8') as file: lines = file.readlines() n_lines = len(lines) distances = np.zeros((n_lines,",
"file.readlines() n_lines = len(lines) distances = np.zeros((n_lines, n_lines), dtype=int) messages = [] for",
"for x in range(n_lines): for y in range(x + 1, n_lines): if x",
"> 1 with open(sys.argv[1], 'r', encoding='utf-8') as file: lines = file.readlines() n_lines =",
"with open(sys.argv[1], 'r', encoding='utf-8') as file: lines = file.readlines() n_lines = len(lines) distances",
"numpy as np assert len(sys.argv) > 1 with open(sys.argv[1], 'r', encoding='utf-8') as file:",
"Levenshtein import numpy as np assert len(sys.argv) > 1 with open(sys.argv[1], 'r', encoding='utf-8')",
"+ 1, n_lines): if x != y: value = Levenshtein.distance(lines[x], lines[y]) distances[x,y] =",
"{} and {} look similar\\n{}{}\\n\".format(x, y, lines[x], lines[y]) messages.append(message) for message in messages:",
"1 with open(sys.argv[1], 'r', encoding='utf-8') as file: lines = file.readlines() n_lines = len(lines)",
"dtype=int) messages = [] for x in range(n_lines): for y in range(x +",
"lines[y]) distances[x,y] = value if value < 5: message = \"lines {} and",
"message = \"lines {} and {} look similar\\n{}{}\\n\".format(x, y, lines[x], lines[y]) messages.append(message) for",
"np.zeros((n_lines, n_lines), dtype=int) messages = [] for x in range(n_lines): for y in",
"n_lines), dtype=int) messages = [] for x in range(n_lines): for y in range(x",
"n_lines = len(lines) distances = np.zeros((n_lines, n_lines), dtype=int) messages = [] for x",
"distances = np.zeros((n_lines, n_lines), dtype=int) messages = [] for x in range(n_lines): for",
"import numpy as np assert len(sys.argv) > 1 with open(sys.argv[1], 'r', encoding='utf-8') as",
"len(lines) distances = np.zeros((n_lines, n_lines), dtype=int) messages = [] for x in range(n_lines):",
"in range(x + 1, n_lines): if x != y: value = Levenshtein.distance(lines[x], lines[y])",
"value if value < 5: message = \"lines {} and {} look similar\\n{}{}\\n\".format(x,",
"utf-8 import sys import Levenshtein import numpy as np assert len(sys.argv) > 1",
"x != y: value = Levenshtein.distance(lines[x], lines[y]) distances[x,y] = value if value <",
"coding: utf-8 import sys import Levenshtein import numpy as np assert len(sys.argv) >"
] |
[
"import List import uvicorn from fastapi import FastAPI, HTTPException, status from pydantic import",
"-c 5M </dev/urandom > archive1` return FileResponse(\"archive1\") if __name__ == \"__main__\": uvicorn.run(\"mock_gh_api:app\", host=\"0.0.0.0\",",
"deepcopy(test_data[\"status\"][id]) # Add some delay to the export (not the failed ones) if",
"migration_status(id: str): status = deepcopy(test_data[\"status\"][id]) # Add some delay to the export (not",
"\"Repo4\": raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY) print(repos.repositories[0]) return test_data[\"startedMigration\"][repos.repositories[0]] @app.get(\"/orgs/{org}/migrations/{id}\") def migration_status(id: str): status = deepcopy(test_data[\"status\"][id])",
"class Repos(BaseModel): repositories: List[str] with open(\"mock_data.json\") as file: test_data = json.load(file) @app.get(\"/orgs/{org}/repos\") def",
"json from copy import deepcopy from random import randrange from typing import List",
"print(repos.repositories[0]) return test_data[\"startedMigration\"][repos.repositories[0]] @app.get(\"/orgs/{org}/migrations/{id}\") def migration_status(id: str): status = deepcopy(test_data[\"status\"][id]) # Add some",
"import deepcopy from random import randrange from typing import List import uvicorn from",
"random import randrange from typing import List import uvicorn from fastapi import FastAPI,",
"status = deepcopy(test_data[\"status\"][id]) # Add some delay to the export (not the failed",
"Add some delay to the export (not the failed ones) if status[\"state\"] !=",
"start_migration(repos: Repos): if repos.repositories[0] == \"Repo4\": raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY) print(repos.repositories[0]) return test_data[\"startedMigration\"][repos.repositories[0]] @app.get(\"/orgs/{org}/migrations/{id}\") def",
"pydantic import BaseModel from starlette.responses import FileResponse app = FastAPI() class Repos(BaseModel): repositories:",
"download_archive(id: str): # Can be created with `head -c 5M </dev/urandom > archive1`",
"randrange from typing import List import uvicorn from fastapi import FastAPI, HTTPException, status",
"BaseModel from starlette.responses import FileResponse app = FastAPI() class Repos(BaseModel): repositories: List[str] with",
"= json.load(file) @app.get(\"/orgs/{org}/repos\") def repos(): return test_data[\"repos\"] @app.get(\"/orgs/{org}/migrations\") def list_migrations(): return test_data[\"migrations\"] @app.post(\"/orgs/{org}/migrations\")",
"import FileResponse app = FastAPI() class Repos(BaseModel): repositories: List[str] with open(\"mock_data.json\") as file:",
"raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY) print(repos.repositories[0]) return test_data[\"startedMigration\"][repos.repositories[0]] @app.get(\"/orgs/{org}/migrations/{id}\") def migration_status(id: str): status = deepcopy(test_data[\"status\"][id]) #",
"= FastAPI() class Repos(BaseModel): repositories: List[str] with open(\"mock_data.json\") as file: test_data = json.load(file)",
"fastapi import FastAPI, HTTPException, status from pydantic import BaseModel from starlette.responses import FileResponse",
"as file: test_data = json.load(file) @app.get(\"/orgs/{org}/repos\") def repos(): return test_data[\"repos\"] @app.get(\"/orgs/{org}/migrations\") def list_migrations():",
"delay to the export (not the failed ones) if status[\"state\"] != \"failed\" and",
"List[str] with open(\"mock_data.json\") as file: test_data = json.load(file) @app.get(\"/orgs/{org}/repos\") def repos(): return test_data[\"repos\"]",
"def repos(): return test_data[\"repos\"] @app.get(\"/orgs/{org}/migrations\") def list_migrations(): return test_data[\"migrations\"] @app.post(\"/orgs/{org}/migrations\") def start_migration(repos: Repos):",
"if repos.repositories[0] == \"Repo4\": raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY) print(repos.repositories[0]) return test_data[\"startedMigration\"][repos.repositories[0]] @app.get(\"/orgs/{org}/migrations/{id}\") def migration_status(id: str):",
"def migration_status(id: str): status = deepcopy(test_data[\"status\"][id]) # Add some delay to the export",
"import json from copy import deepcopy from random import randrange from typing import",
"app = FastAPI() class Repos(BaseModel): repositories: List[str] with open(\"mock_data.json\") as file: test_data =",
"import BaseModel from starlette.responses import FileResponse app = FastAPI() class Repos(BaseModel): repositories: List[str]",
"</dev/urandom > archive1` return FileResponse(\"archive1\") if __name__ == \"__main__\": uvicorn.run(\"mock_gh_api:app\", host=\"0.0.0.0\", port=5000, reload=True)",
"status from pydantic import BaseModel from starlette.responses import FileResponse app = FastAPI() class",
"\"exported\" print(status) return status @app.get(\"/orgs/{org}/migrations/{id}/archive\") async def download_archive(id: str): # Can be created",
"def list_migrations(): return test_data[\"migrations\"] @app.post(\"/orgs/{org}/migrations\") def start_migration(repos: Repos): if repos.repositories[0] == \"Repo4\": raise",
"def download_archive(id: str): # Can be created with `head -c 5M </dev/urandom >",
"test_data[\"startedMigration\"][repos.repositories[0]] @app.get(\"/orgs/{org}/migrations/{id}\") def migration_status(id: str): status = deepcopy(test_data[\"status\"][id]) # Add some delay to",
"FastAPI() class Repos(BaseModel): repositories: List[str] with open(\"mock_data.json\") as file: test_data = json.load(file) @app.get(\"/orgs/{org}/repos\")",
"FastAPI, HTTPException, status from pydantic import BaseModel from starlette.responses import FileResponse app =",
"import uvicorn from fastapi import FastAPI, HTTPException, status from pydantic import BaseModel from",
"!= \"failed\" and randrange(10) > 6: status[\"state\"] = \"exported\" print(status) return status @app.get(\"/orgs/{org}/migrations/{id}/archive\")",
"to the export (not the failed ones) if status[\"state\"] != \"failed\" and randrange(10)",
"be created with `head -c 5M </dev/urandom > archive1` return FileResponse(\"archive1\") if __name__",
"return status @app.get(\"/orgs/{org}/migrations/{id}/archive\") async def download_archive(id: str): # Can be created with `head",
"the failed ones) if status[\"state\"] != \"failed\" and randrange(10) > 6: status[\"state\"] =",
"return test_data[\"repos\"] @app.get(\"/orgs/{org}/migrations\") def list_migrations(): return test_data[\"migrations\"] @app.post(\"/orgs/{org}/migrations\") def start_migration(repos: Repos): if repos.repositories[0]",
"@app.get(\"/orgs/{org}/migrations/{id}/archive\") async def download_archive(id: str): # Can be created with `head -c 5M",
"status[\"state\"] != \"failed\" and randrange(10) > 6: status[\"state\"] = \"exported\" print(status) return status",
"randrange(10) > 6: status[\"state\"] = \"exported\" print(status) return status @app.get(\"/orgs/{org}/migrations/{id}/archive\") async def download_archive(id:",
"return test_data[\"startedMigration\"][repos.repositories[0]] @app.get(\"/orgs/{org}/migrations/{id}\") def migration_status(id: str): status = deepcopy(test_data[\"status\"][id]) # Add some delay",
"with `head -c 5M </dev/urandom > archive1` return FileResponse(\"archive1\") if __name__ == \"__main__\":",
"6: status[\"state\"] = \"exported\" print(status) return status @app.get(\"/orgs/{org}/migrations/{id}/archive\") async def download_archive(id: str): #",
"Repos): if repos.repositories[0] == \"Repo4\": raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY) print(repos.repositories[0]) return test_data[\"startedMigration\"][repos.repositories[0]] @app.get(\"/orgs/{org}/migrations/{id}\") def migration_status(id:",
"Repos(BaseModel): repositories: List[str] with open(\"mock_data.json\") as file: test_data = json.load(file) @app.get(\"/orgs/{org}/repos\") def repos():",
"@app.get(\"/orgs/{org}/repos\") def repos(): return test_data[\"repos\"] @app.get(\"/orgs/{org}/migrations\") def list_migrations(): return test_data[\"migrations\"] @app.post(\"/orgs/{org}/migrations\") def start_migration(repos:",
"if status[\"state\"] != \"failed\" and randrange(10) > 6: status[\"state\"] = \"exported\" print(status) return",
"from typing import List import uvicorn from fastapi import FastAPI, HTTPException, status from",
"status @app.get(\"/orgs/{org}/migrations/{id}/archive\") async def download_archive(id: str): # Can be created with `head -c",
"test_data = json.load(file) @app.get(\"/orgs/{org}/repos\") def repos(): return test_data[\"repos\"] @app.get(\"/orgs/{org}/migrations\") def list_migrations(): return test_data[\"migrations\"]",
"export (not the failed ones) if status[\"state\"] != \"failed\" and randrange(10) > 6:",
"test_data[\"repos\"] @app.get(\"/orgs/{org}/migrations\") def list_migrations(): return test_data[\"migrations\"] @app.post(\"/orgs/{org}/migrations\") def start_migration(repos: Repos): if repos.repositories[0] ==",
"\"failed\" and randrange(10) > 6: status[\"state\"] = \"exported\" print(status) return status @app.get(\"/orgs/{org}/migrations/{id}/archive\") async",
"str): # Can be created with `head -c 5M </dev/urandom > archive1` return",
"file: test_data = json.load(file) @app.get(\"/orgs/{org}/repos\") def repos(): return test_data[\"repos\"] @app.get(\"/orgs/{org}/migrations\") def list_migrations(): return",
"starlette.responses import FileResponse app = FastAPI() class Repos(BaseModel): repositories: List[str] with open(\"mock_data.json\") as",
"the export (not the failed ones) if status[\"state\"] != \"failed\" and randrange(10) >",
"List import uvicorn from fastapi import FastAPI, HTTPException, status from pydantic import BaseModel",
"HTTPException, status from pydantic import BaseModel from starlette.responses import FileResponse app = FastAPI()",
"from pydantic import BaseModel from starlette.responses import FileResponse app = FastAPI() class Repos(BaseModel):",
"ones) if status[\"state\"] != \"failed\" and randrange(10) > 6: status[\"state\"] = \"exported\" print(status)",
"Can be created with `head -c 5M </dev/urandom > archive1` return FileResponse(\"archive1\") if",
"import FastAPI, HTTPException, status from pydantic import BaseModel from starlette.responses import FileResponse app",
"FileResponse app = FastAPI() class Repos(BaseModel): repositories: List[str] with open(\"mock_data.json\") as file: test_data",
"async def download_archive(id: str): # Can be created with `head -c 5M </dev/urandom",
"= \"exported\" print(status) return status @app.get(\"/orgs/{org}/migrations/{id}/archive\") async def download_archive(id: str): # Can be",
"import randrange from typing import List import uvicorn from fastapi import FastAPI, HTTPException,",
"HTTPException(status_code=status.HTTP_502_BAD_GATEWAY) print(repos.repositories[0]) return test_data[\"startedMigration\"][repos.repositories[0]] @app.get(\"/orgs/{org}/migrations/{id}\") def migration_status(id: str): status = deepcopy(test_data[\"status\"][id]) # Add",
"failed ones) if status[\"state\"] != \"failed\" and randrange(10) > 6: status[\"state\"] = \"exported\"",
"(not the failed ones) if status[\"state\"] != \"failed\" and randrange(10) > 6: status[\"state\"]",
"uvicorn from fastapi import FastAPI, HTTPException, status from pydantic import BaseModel from starlette.responses",
"# Can be created with `head -c 5M </dev/urandom > archive1` return FileResponse(\"archive1\")",
"print(status) return status @app.get(\"/orgs/{org}/migrations/{id}/archive\") async def download_archive(id: str): # Can be created with",
"repos(): return test_data[\"repos\"] @app.get(\"/orgs/{org}/migrations\") def list_migrations(): return test_data[\"migrations\"] @app.post(\"/orgs/{org}/migrations\") def start_migration(repos: Repos): if",
"5M </dev/urandom > archive1` return FileResponse(\"archive1\") if __name__ == \"__main__\": uvicorn.run(\"mock_gh_api:app\", host=\"0.0.0.0\", port=5000,",
"typing import List import uvicorn from fastapi import FastAPI, HTTPException, status from pydantic",
"repos.repositories[0] == \"Repo4\": raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY) print(repos.repositories[0]) return test_data[\"startedMigration\"][repos.repositories[0]] @app.get(\"/orgs/{org}/migrations/{id}\") def migration_status(id: str): status",
"def start_migration(repos: Repos): if repos.repositories[0] == \"Repo4\": raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY) print(repos.repositories[0]) return test_data[\"startedMigration\"][repos.repositories[0]] @app.get(\"/orgs/{org}/migrations/{id}\")",
"return test_data[\"migrations\"] @app.post(\"/orgs/{org}/migrations\") def start_migration(repos: Repos): if repos.repositories[0] == \"Repo4\": raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY) print(repos.repositories[0])",
"copy import deepcopy from random import randrange from typing import List import uvicorn",
"created with `head -c 5M </dev/urandom > archive1` return FileResponse(\"archive1\") if __name__ ==",
"@app.get(\"/orgs/{org}/migrations/{id}\") def migration_status(id: str): status = deepcopy(test_data[\"status\"][id]) # Add some delay to the",
"some delay to the export (not the failed ones) if status[\"state\"] != \"failed\"",
"deepcopy from random import randrange from typing import List import uvicorn from fastapi",
"from fastapi import FastAPI, HTTPException, status from pydantic import BaseModel from starlette.responses import",
"from random import randrange from typing import List import uvicorn from fastapi import",
"from starlette.responses import FileResponse app = FastAPI() class Repos(BaseModel): repositories: List[str] with open(\"mock_data.json\")",
"`head -c 5M </dev/urandom > archive1` return FileResponse(\"archive1\") if __name__ == \"__main__\": uvicorn.run(\"mock_gh_api:app\",",
"and randrange(10) > 6: status[\"state\"] = \"exported\" print(status) return status @app.get(\"/orgs/{org}/migrations/{id}/archive\") async def",
"# Add some delay to the export (not the failed ones) if status[\"state\"]",
"= deepcopy(test_data[\"status\"][id]) # Add some delay to the export (not the failed ones)",
"> 6: status[\"state\"] = \"exported\" print(status) return status @app.get(\"/orgs/{org}/migrations/{id}/archive\") async def download_archive(id: str):",
"with open(\"mock_data.json\") as file: test_data = json.load(file) @app.get(\"/orgs/{org}/repos\") def repos(): return test_data[\"repos\"] @app.get(\"/orgs/{org}/migrations\")",
"== \"Repo4\": raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY) print(repos.repositories[0]) return test_data[\"startedMigration\"][repos.repositories[0]] @app.get(\"/orgs/{org}/migrations/{id}\") def migration_status(id: str): status =",
"repositories: List[str] with open(\"mock_data.json\") as file: test_data = json.load(file) @app.get(\"/orgs/{org}/repos\") def repos(): return",
"from copy import deepcopy from random import randrange from typing import List import",
"list_migrations(): return test_data[\"migrations\"] @app.post(\"/orgs/{org}/migrations\") def start_migration(repos: Repos): if repos.repositories[0] == \"Repo4\": raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY)",
"@app.get(\"/orgs/{org}/migrations\") def list_migrations(): return test_data[\"migrations\"] @app.post(\"/orgs/{org}/migrations\") def start_migration(repos: Repos): if repos.repositories[0] == \"Repo4\":",
"json.load(file) @app.get(\"/orgs/{org}/repos\") def repos(): return test_data[\"repos\"] @app.get(\"/orgs/{org}/migrations\") def list_migrations(): return test_data[\"migrations\"] @app.post(\"/orgs/{org}/migrations\") def",
"status[\"state\"] = \"exported\" print(status) return status @app.get(\"/orgs/{org}/migrations/{id}/archive\") async def download_archive(id: str): # Can",
"test_data[\"migrations\"] @app.post(\"/orgs/{org}/migrations\") def start_migration(repos: Repos): if repos.repositories[0] == \"Repo4\": raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY) print(repos.repositories[0]) return",
"@app.post(\"/orgs/{org}/migrations\") def start_migration(repos: Repos): if repos.repositories[0] == \"Repo4\": raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY) print(repos.repositories[0]) return test_data[\"startedMigration\"][repos.repositories[0]]",
"str): status = deepcopy(test_data[\"status\"][id]) # Add some delay to the export (not the",
"open(\"mock_data.json\") as file: test_data = json.load(file) @app.get(\"/orgs/{org}/repos\") def repos(): return test_data[\"repos\"] @app.get(\"/orgs/{org}/migrations\") def"
] |
[
"null=True, verbose_name='Sales'), ), migrations.AlterField( model_name='mystrategyvalue', name='method', field=models.IntegerField(choices=[(1, 'daily return'), (2, 'overnight return'), (3,",
"(2, 'overnight return'), (3, 'night day consistency'), (4, 'two daily trend'), (5, 'night",
"new_name='ar', ), migrations.AlterField( model_name='incomestatement', name='total_revenue', field=models.FloatField(blank=True, default=0, null=True, verbose_name='Sales'), ), migrations.AlterField( model_name='mystrategyvalue', name='method',",
"'overnight return'), (3, 'night day consistency'), (4, 'two daily trend'), (5, 'night day",
"class Migration(migrations.Migration): dependencies = [ ('stock', '0023_auto_20210216_1552'), ] operations = [ migrations.RenameField( model_name='balancesheet',",
"Generated by Django 3.1.6 on 2021-02-18 23:47 from django.db import migrations, models class",
"model_name='mystrategyvalue', name='method', field=models.IntegerField(choices=[(1, 'daily return'), (2, 'overnight return'), (3, 'night day consistency'), (4,",
"Migration(migrations.Migration): dependencies = [ ('stock', '0023_auto_20210216_1552'), ] operations = [ migrations.RenameField( model_name='balancesheet', old_name='ac',",
"'night day consistency'), (4, 'two daily trend'), (5, 'night day compounded return')], default=1),",
"by Django 3.1.6 on 2021-02-18 23:47 from django.db import migrations, models class Migration(migrations.Migration):",
"3.1.6 on 2021-02-18 23:47 from django.db import migrations, models class Migration(migrations.Migration): dependencies =",
"models class Migration(migrations.Migration): dependencies = [ ('stock', '0023_auto_20210216_1552'), ] operations = [ migrations.RenameField(",
"migrations.AlterField( model_name='mystrategyvalue', name='method', field=models.IntegerField(choices=[(1, 'daily return'), (2, 'overnight return'), (3, 'night day consistency'),",
"] operations = [ migrations.RenameField( model_name='balancesheet', old_name='ac', new_name='ar', ), migrations.AlterField( model_name='incomestatement', name='total_revenue', field=models.FloatField(blank=True,",
"# Generated by Django 3.1.6 on 2021-02-18 23:47 from django.db import migrations, models",
"(3, 'night day consistency'), (4, 'two daily trend'), (5, 'night day compounded return')],",
"), migrations.AlterField( model_name='incomestatement', name='total_revenue', field=models.FloatField(blank=True, default=0, null=True, verbose_name='Sales'), ), migrations.AlterField( model_name='mystrategyvalue', name='method', field=models.IntegerField(choices=[(1,",
"name='method', field=models.IntegerField(choices=[(1, 'daily return'), (2, 'overnight return'), (3, 'night day consistency'), (4, 'two",
"field=models.FloatField(blank=True, default=0, null=True, verbose_name='Sales'), ), migrations.AlterField( model_name='mystrategyvalue', name='method', field=models.IntegerField(choices=[(1, 'daily return'), (2, 'overnight",
"return'), (2, 'overnight return'), (3, 'night day consistency'), (4, 'two daily trend'), (5,",
"field=models.IntegerField(choices=[(1, 'daily return'), (2, 'overnight return'), (3, 'night day consistency'), (4, 'two daily",
"model_name='balancesheet', old_name='ac', new_name='ar', ), migrations.AlterField( model_name='incomestatement', name='total_revenue', field=models.FloatField(blank=True, default=0, null=True, verbose_name='Sales'), ), migrations.AlterField(",
"migrations.RenameField( model_name='balancesheet', old_name='ac', new_name='ar', ), migrations.AlterField( model_name='incomestatement', name='total_revenue', field=models.FloatField(blank=True, default=0, null=True, verbose_name='Sales'), ),",
"operations = [ migrations.RenameField( model_name='balancesheet', old_name='ac', new_name='ar', ), migrations.AlterField( model_name='incomestatement', name='total_revenue', field=models.FloatField(blank=True, default=0,",
"2021-02-18 23:47 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('stock',",
"django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('stock', '0023_auto_20210216_1552'), ] operations",
"return'), (3, 'night day consistency'), (4, 'two daily trend'), (5, 'night day compounded",
"default=0, null=True, verbose_name='Sales'), ), migrations.AlterField( model_name='mystrategyvalue', name='method', field=models.IntegerField(choices=[(1, 'daily return'), (2, 'overnight return'),",
"model_name='incomestatement', name='total_revenue', field=models.FloatField(blank=True, default=0, null=True, verbose_name='Sales'), ), migrations.AlterField( model_name='mystrategyvalue', name='method', field=models.IntegerField(choices=[(1, 'daily return'),",
"import migrations, models class Migration(migrations.Migration): dependencies = [ ('stock', '0023_auto_20210216_1552'), ] operations =",
"name='total_revenue', field=models.FloatField(blank=True, default=0, null=True, verbose_name='Sales'), ), migrations.AlterField( model_name='mystrategyvalue', name='method', field=models.IntegerField(choices=[(1, 'daily return'), (2,",
"[ ('stock', '0023_auto_20210216_1552'), ] operations = [ migrations.RenameField( model_name='balancesheet', old_name='ac', new_name='ar', ), migrations.AlterField(",
"dependencies = [ ('stock', '0023_auto_20210216_1552'), ] operations = [ migrations.RenameField( model_name='balancesheet', old_name='ac', new_name='ar',",
"), migrations.AlterField( model_name='mystrategyvalue', name='method', field=models.IntegerField(choices=[(1, 'daily return'), (2, 'overnight return'), (3, 'night day",
"<reponame>fengxia41103/stock<filename>backend/stock/migrations/0024_auto_20210218_2347.py # Generated by Django 3.1.6 on 2021-02-18 23:47 from django.db import migrations,",
"on 2021-02-18 23:47 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [",
"= [ migrations.RenameField( model_name='balancesheet', old_name='ac', new_name='ar', ), migrations.AlterField( model_name='incomestatement', name='total_revenue', field=models.FloatField(blank=True, default=0, null=True,",
"('stock', '0023_auto_20210216_1552'), ] operations = [ migrations.RenameField( model_name='balancesheet', old_name='ac', new_name='ar', ), migrations.AlterField( model_name='incomestatement',",
"from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('stock', '0023_auto_20210216_1552'), ]",
"old_name='ac', new_name='ar', ), migrations.AlterField( model_name='incomestatement', name='total_revenue', field=models.FloatField(blank=True, default=0, null=True, verbose_name='Sales'), ), migrations.AlterField( model_name='mystrategyvalue',",
"[ migrations.RenameField( model_name='balancesheet', old_name='ac', new_name='ar', ), migrations.AlterField( model_name='incomestatement', name='total_revenue', field=models.FloatField(blank=True, default=0, null=True, verbose_name='Sales'),",
"= [ ('stock', '0023_auto_20210216_1552'), ] operations = [ migrations.RenameField( model_name='balancesheet', old_name='ac', new_name='ar', ),",
"consistency'), (4, 'two daily trend'), (5, 'night day compounded return')], default=1), ), ]",
"migrations, models class Migration(migrations.Migration): dependencies = [ ('stock', '0023_auto_20210216_1552'), ] operations = [",
"Django 3.1.6 on 2021-02-18 23:47 from django.db import migrations, models class Migration(migrations.Migration): dependencies",
"verbose_name='Sales'), ), migrations.AlterField( model_name='mystrategyvalue', name='method', field=models.IntegerField(choices=[(1, 'daily return'), (2, 'overnight return'), (3, 'night",
"'daily return'), (2, 'overnight return'), (3, 'night day consistency'), (4, 'two daily trend'),",
"23:47 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('stock', '0023_auto_20210216_1552'),",
"'0023_auto_20210216_1552'), ] operations = [ migrations.RenameField( model_name='balancesheet', old_name='ac', new_name='ar', ), migrations.AlterField( model_name='incomestatement', name='total_revenue',",
"migrations.AlterField( model_name='incomestatement', name='total_revenue', field=models.FloatField(blank=True, default=0, null=True, verbose_name='Sales'), ), migrations.AlterField( model_name='mystrategyvalue', name='method', field=models.IntegerField(choices=[(1, 'daily",
"day consistency'), (4, 'two daily trend'), (5, 'night day compounded return')], default=1), ),"
] |
[
"<filename>error_propagation/__init__.py from error_propagation.core import arrays_to_complex from error_propagation.core import Complex __all__ = [\"Complex\", \"arrays_to_complex\"]"
] |
[
"s = s.replace(k, v) for k in deletions: if k in s: s",
"while \"--\" in s: s = s.replace(\"--\", \"-\") for (ks, v) in substitutions.items():",
"for k in deletions: if k in s: s = s.replace(k, \"\") s",
"\", \"&\": \" <AND>\", } deletions = {\"¿\", \"¡\"} def normalize(s): s =",
"s = s.lower().replace(\".\", \"\").replace(\"\\n\", \"\") while \"--\" in s: s = s.replace(\"--\", \"-\")",
"s = s.replace(\"--\", \"-\") for (ks, v) in substitutions.items(): for k in ks:",
"s = \"<SOS> \" + s.strip() + \" <EOS>\" while \" \" in",
"\"!\": \" <EXCLAMATION> \", \",\": \" <COMMA> \", \":\": \" <COLON> \", \";\":",
"while \" \" in s: s = s.replace(\" \", \" \") return s",
"if k in s: s = s.replace(k, v) for k in deletions: if",
"= s.replace(v, ks[0]) return s def detokenize(tokens): tokens = [token for token in",
"detokenize(tokens): tokens = [token for token in tokens if token not in [\"<EOS>\",",
"s = s.replace(k, \"\") s = \"<SOS> \" + s.strip() + \" <EOS>\"",
"s: s = s.replace(\" \", \" \") return s def tokenize(s): s =",
"if k in s: s = s.replace(k, \"\") s = \"<SOS> \" +",
"\" <SINGLE-QUOTE> \", '\"«»': \" <DOUBLE-QUOTE> \", \"/\": \" <SLASH> \", \"\\\\\": \"",
"s.strip() + \" <EOS>\" while \" \" in s: s = s.replace(\" \",",
"return tokens def denormalize_string(s): for (ks, v) in substitutions.items(): if v in s:",
"if v in s: s = s.replace(v, ks[0]) return s def detokenize(tokens): tokens",
"word.isdigit(): tokens.append(\"<NUMBER>\") else: tokens.append(word) return tokens def denormalize_string(s): for (ks, v) in substitutions.items():",
"v in s: s = s.replace(v, ks[0]) return s def detokenize(tokens): tokens =",
"\"(\": \" <LEFT-PAREN> \", \")\": \" <RIGHT-PAREN> \", \"&\": \" <AND>\", } deletions",
"\"“\": \" <LEFT-QUOTE> \", \"-\": \" <HYPHEN> \", \"[\": \" <LEFT-BRACKET> \", \"]\":",
"for (ks, v) in substitutions.items(): if v in s: s = s.replace(v, ks[0])",
"\"\") s = \"<SOS> \" + s.strip() + \" <EOS>\" while \" \"",
"\"-\") for (ks, v) in substitutions.items(): for k in ks: if k in",
"s.split(\" \"): if len(word) == 0: continue elif word.isdigit(): tokens.append(\"<NUMBER>\") else: tokens.append(word) return",
"\", \"/\": \" <SLASH> \", \"\\\\\": \" <BACK-SLASH> \", \"”\": \" <RIGHT-QUOTE> \",",
"return s def detokenize(tokens): tokens = [token for token in tokens if token",
"+ s.strip() + \" <EOS>\" while \" \" in s: s = s.replace(\"",
"\", \"(\": \" <LEFT-PAREN> \", \")\": \" <RIGHT-PAREN> \", \"&\": \" <AND>\", }",
"in s: s = s.replace(v, ks[0]) return s def detokenize(tokens): tokens = [token",
"\", \",\": \" <COMMA> \", \":\": \" <COLON> \", \";\": \" <SEMI-COLON> \",",
"= s.replace(\"--\", \"-\") for (ks, v) in substitutions.items(): for k in ks: if",
"v) in substitutions.items(): if v in s: s = s.replace(v, ks[0]) return s",
"\"”\": \" <RIGHT-QUOTE> \", \"“\": \" <LEFT-QUOTE> \", \"-\": \" <HYPHEN> \", \"[\":",
"token in tokens if token not in [\"<EOS>\", \"<SOS>\"]] s = \" \".join(tokens)",
"\", \" \") return s def tokenize(s): s = normalize(s) tokens = []",
"\" <COMMA> \", \":\": \" <COLON> \", \";\": \" <SEMI-COLON> \", \"+\": \"<PLUS>",
"\", \":\": \" <COLON> \", \";\": \" <SEMI-COLON> \", \"+\": \"<PLUS> \", \"(\":",
"s.replace(k, \"\") s = \"<SOS> \" + s.strip() + \" <EOS>\" while \"",
"\"\") while \"--\" in s: s = s.replace(\"--\", \"-\") for (ks, v) in",
"<RIGHT-BRACKET> \", \"?\": \" <QUESTION> \", \"!\": \" <EXCLAMATION> \", \",\": \" <COMMA>",
"in s: s = s.replace(k, v) for k in deletions: if k in",
"= s.replace(k, v) for k in deletions: if k in s: s =",
"<DOUBLE-QUOTE> \", \"/\": \" <SLASH> \", \"\\\\\": \" <BACK-SLASH> \", \"”\": \" <RIGHT-QUOTE>",
"\", \"+\": \"<PLUS> \", \"(\": \" <LEFT-PAREN> \", \")\": \" <RIGHT-PAREN> \", \"&\":",
"<LEFT-BRACKET> \", \"]\": \" <RIGHT-BRACKET> \", \"?\": \" <QUESTION> \", \"!\": \" <EXCLAMATION>",
"= s.lower().replace(\".\", \"\").replace(\"\\n\", \"\") while \"--\" in s: s = s.replace(\"--\", \"-\") for",
"[token for token in tokens if token not in [\"<EOS>\", \"<SOS>\"]] s =",
"s.replace(v, ks[0]) return s def detokenize(tokens): tokens = [token for token in tokens",
"\" <LEFT-QUOTE> \", \"-\": \" <HYPHEN> \", \"[\": \" <LEFT-BRACKET> \", \"]\": \"",
"<EOS>\" while \" \" in s: s = s.replace(\" \", \" \") return",
"<SEMI-COLON> \", \"+\": \"<PLUS> \", \"(\": \" <LEFT-PAREN> \", \")\": \" <RIGHT-PAREN> \",",
"\") return s def tokenize(s): s = normalize(s) tokens = [] for word",
"k in s: s = s.replace(k, \"\") s = \"<SOS> \" + s.strip()",
"ks[0]) return s def detokenize(tokens): tokens = [token for token in tokens if",
"<LEFT-QUOTE> \", \"-\": \" <HYPHEN> \", \"[\": \" <LEFT-BRACKET> \", \"]\": \" <RIGHT-BRACKET>",
"} deletions = {\"¿\", \"¡\"} def normalize(s): s = s.lower().replace(\".\", \"\").replace(\"\\n\", \"\") while",
"<COMMA> \", \":\": \" <COLON> \", \";\": \" <SEMI-COLON> \", \"+\": \"<PLUS> \",",
"word in s.split(\" \"): if len(word) == 0: continue elif word.isdigit(): tokens.append(\"<NUMBER>\") else:",
"\" <LEFT-BRACKET> \", \"]\": \" <RIGHT-BRACKET> \", \"?\": \" <QUESTION> \", \"!\": \"",
"in s: s = s.replace(k, \"\") s = \"<SOS> \" + s.strip() +",
"len(word) == 0: continue elif word.isdigit(): tokens.append(\"<NUMBER>\") else: tokens.append(word) return tokens def denormalize_string(s):",
"<COLON> \", \";\": \" <SEMI-COLON> \", \"+\": \"<PLUS> \", \"(\": \" <LEFT-PAREN> \",",
"s: s = s.replace(\"--\", \"-\") for (ks, v) in substitutions.items(): for k in",
"s = s.replace(\" \", \" \") return s def tokenize(s): s = normalize(s)",
"\" <SEMI-COLON> \", \"+\": \"<PLUS> \", \"(\": \" <LEFT-PAREN> \", \")\": \" <RIGHT-PAREN>",
"= [token for token in tokens if token not in [\"<EOS>\", \"<SOS>\"]] s",
"<RIGHT-QUOTE> \", \"“\": \" <LEFT-QUOTE> \", \"-\": \" <HYPHEN> \", \"[\": \" <LEFT-BRACKET>",
"deletions = {\"¿\", \"¡\"} def normalize(s): s = s.lower().replace(\".\", \"\").replace(\"\\n\", \"\") while \"--\"",
"def detokenize(tokens): tokens = [token for token in tokens if token not in",
"<HYPHEN> \", \"[\": \" <LEFT-BRACKET> \", \"]\": \" <RIGHT-BRACKET> \", \"?\": \" <QUESTION>",
"\", \"]\": \" <RIGHT-BRACKET> \", \"?\": \" <QUESTION> \", \"!\": \" <EXCLAMATION> \",",
"\", \"”\": \" <RIGHT-QUOTE> \", \"“\": \" <LEFT-QUOTE> \", \"-\": \" <HYPHEN> \",",
"s: s = s.replace(k, v) for k in deletions: if k in s:",
"(ks, v) in substitutions.items(): if v in s: s = s.replace(v, ks[0]) return",
"== 0: continue elif word.isdigit(): tokens.append(\"<NUMBER>\") else: tokens.append(word) return tokens def denormalize_string(s): for",
"\";\": \" <SEMI-COLON> \", \"+\": \"<PLUS> \", \"(\": \" <LEFT-PAREN> \", \")\": \"",
"\"?\": \" <QUESTION> \", \"!\": \" <EXCLAMATION> \", \",\": \" <COMMA> \", \":\":",
"for token in tokens if token not in [\"<EOS>\", \"<SOS>\"]] s = \"",
"\"/\": \" <SLASH> \", \"\\\\\": \" <BACK-SLASH> \", \"”\": \" <RIGHT-QUOTE> \", \"“\":",
"\", \"“\": \" <LEFT-QUOTE> \", \"-\": \" <HYPHEN> \", \"[\": \" <LEFT-BRACKET> \",",
"\", \"[\": \" <LEFT-BRACKET> \", \"]\": \" <RIGHT-BRACKET> \", \"?\": \" <QUESTION> \",",
"= normalize(s) tokens = [] for word in s.split(\" \"): if len(word) ==",
"[] for word in s.split(\" \"): if len(word) == 0: continue elif word.isdigit():",
"\"'’‘\": \" <SINGLE-QUOTE> \", '\"«»': \" <DOUBLE-QUOTE> \", \"/\": \" <SLASH> \", \"\\\\\":",
"= { \"'’‘\": \" <SINGLE-QUOTE> \", '\"«»': \" <DOUBLE-QUOTE> \", \"/\": \" <SLASH>",
"substitutions.items(): if v in s: s = s.replace(v, ks[0]) return s def detokenize(tokens):",
"+ \" <EOS>\" while \" \" in s: s = s.replace(\" \", \"",
"\"\\\\\": \" <BACK-SLASH> \", \"”\": \" <RIGHT-QUOTE> \", \"“\": \" <LEFT-QUOTE> \", \"-\":",
"def denormalize_string(s): for (ks, v) in substitutions.items(): if v in s: s =",
"s: s = s.replace(k, \"\") s = \"<SOS> \" + s.strip() + \"",
"tokens.append(\"<NUMBER>\") else: tokens.append(word) return tokens def denormalize_string(s): for (ks, v) in substitutions.items(): if",
"\", \"-\": \" <HYPHEN> \", \"[\": \" <LEFT-BRACKET> \", \"]\": \" <RIGHT-BRACKET> \",",
"'\"«»': \" <DOUBLE-QUOTE> \", \"/\": \" <SLASH> \", \"\\\\\": \" <BACK-SLASH> \", \"”\":",
"\"\").replace(\"\\n\", \"\") while \"--\" in s: s = s.replace(\"--\", \"-\") for (ks, v)",
"\" <COLON> \", \";\": \" <SEMI-COLON> \", \"+\": \"<PLUS> \", \"(\": \" <LEFT-PAREN>",
"in substitutions.items(): if v in s: s = s.replace(v, ks[0]) return s def",
"s def tokenize(s): s = normalize(s) tokens = [] for word in s.split(\"",
"\" <BACK-SLASH> \", \"”\": \" <RIGHT-QUOTE> \", \"“\": \" <LEFT-QUOTE> \", \"-\": \"",
"in s: s = s.replace(\"--\", \"-\") for (ks, v) in substitutions.items(): for k",
"<SLASH> \", \"\\\\\": \" <BACK-SLASH> \", \"”\": \" <RIGHT-QUOTE> \", \"“\": \" <LEFT-QUOTE>",
"\", \"!\": \" <EXCLAMATION> \", \",\": \" <COMMA> \", \":\": \" <COLON> \",",
"\", \")\": \" <RIGHT-PAREN> \", \"&\": \" <AND>\", } deletions = {\"¿\", \"¡\"}",
"\"<PLUS> \", \"(\": \" <LEFT-PAREN> \", \")\": \" <RIGHT-PAREN> \", \"&\": \" <AND>\",",
"<RIGHT-PAREN> \", \"&\": \" <AND>\", } deletions = {\"¿\", \"¡\"} def normalize(s): s",
"\" <HYPHEN> \", \"[\": \" <LEFT-BRACKET> \", \"]\": \" <RIGHT-BRACKET> \", \"?\": \"",
"tokens = [token for token in tokens if token not in [\"<EOS>\", \"<SOS>\"]]",
"\" <AND>\", } deletions = {\"¿\", \"¡\"} def normalize(s): s = s.lower().replace(\".\", \"\").replace(\"\\n\",",
"for k in ks: if k in s: s = s.replace(k, v) for",
"deletions: if k in s: s = s.replace(k, \"\") s = \"<SOS> \"",
"\", \"?\": \" <QUESTION> \", \"!\": \" <EXCLAMATION> \", \",\": \" <COMMA> \",",
"k in deletions: if k in s: s = s.replace(k, \"\") s =",
"return s def tokenize(s): s = normalize(s) tokens = [] for word in",
"s.replace(\" \", \" \") return s def tokenize(s): s = normalize(s) tokens =",
"0: continue elif word.isdigit(): tokens.append(\"<NUMBER>\") else: tokens.append(word) return tokens def denormalize_string(s): for (ks,",
"\" <RIGHT-QUOTE> \", \"“\": \" <LEFT-QUOTE> \", \"-\": \" <HYPHEN> \", \"[\": \"",
"s = normalize(s) tokens = [] for word in s.split(\" \"): if len(word)",
"\" <RIGHT-BRACKET> \", \"?\": \" <QUESTION> \", \"!\": \" <EXCLAMATION> \", \",\": \"",
"\"): if len(word) == 0: continue elif word.isdigit(): tokens.append(\"<NUMBER>\") else: tokens.append(word) return tokens",
"s = s.replace(v, ks[0]) return s def detokenize(tokens): tokens = [token for token",
"if len(word) == 0: continue elif word.isdigit(): tokens.append(\"<NUMBER>\") else: tokens.append(word) return tokens def",
"\" <DOUBLE-QUOTE> \", \"/\": \" <SLASH> \", \"\\\\\": \" <BACK-SLASH> \", \"”\": \"",
"denormalize_string(s): for (ks, v) in substitutions.items(): if v in s: s = s.replace(v,",
"= {\"¿\", \"¡\"} def normalize(s): s = s.lower().replace(\".\", \"\").replace(\"\\n\", \"\") while \"--\" in",
"ks: if k in s: s = s.replace(k, v) for k in deletions:",
"\" <QUESTION> \", \"!\": \" <EXCLAMATION> \", \",\": \" <COMMA> \", \":\": \"",
"\" \" in s: s = s.replace(\" \", \" \") return s def",
"= s.replace(\" \", \" \") return s def tokenize(s): s = normalize(s) tokens",
"\"&\": \" <AND>\", } deletions = {\"¿\", \"¡\"} def normalize(s): s = s.lower().replace(\".\",",
"\" <SLASH> \", \"\\\\\": \" <BACK-SLASH> \", \"”\": \" <RIGHT-QUOTE> \", \"“\": \"",
"in tokens if token not in [\"<EOS>\", \"<SOS>\"]] s = \" \".join(tokens) return",
"\" <EXCLAMATION> \", \",\": \" <COMMA> \", \":\": \" <COLON> \", \";\": \"",
"\" \") return s def tokenize(s): s = normalize(s) tokens = [] for",
"= s.replace(k, \"\") s = \"<SOS> \" + s.strip() + \" <EOS>\" while",
"elif word.isdigit(): tokens.append(\"<NUMBER>\") else: tokens.append(word) return tokens def denormalize_string(s): for (ks, v) in",
"v) for k in deletions: if k in s: s = s.replace(k, \"\")",
"tokens.append(word) return tokens def denormalize_string(s): for (ks, v) in substitutions.items(): if v in",
"for word in s.split(\" \"): if len(word) == 0: continue elif word.isdigit(): tokens.append(\"<NUMBER>\")",
"tokenize(s): s = normalize(s) tokens = [] for word in s.split(\" \"): if",
"s: s = s.replace(v, ks[0]) return s def detokenize(tokens): tokens = [token for",
"\" <LEFT-PAREN> \", \")\": \" <RIGHT-PAREN> \", \"&\": \" <AND>\", } deletions =",
"<AND>\", } deletions = {\"¿\", \"¡\"} def normalize(s): s = s.lower().replace(\".\", \"\").replace(\"\\n\", \"\")",
"\"-\": \" <HYPHEN> \", \"[\": \" <LEFT-BRACKET> \", \"]\": \" <RIGHT-BRACKET> \", \"?\":",
"<LEFT-PAREN> \", \")\": \" <RIGHT-PAREN> \", \"&\": \" <AND>\", } deletions = {\"¿\",",
"tokens = [] for word in s.split(\" \"): if len(word) == 0: continue",
"in s: s = s.replace(\" \", \" \") return s def tokenize(s): s",
"<BACK-SLASH> \", \"”\": \" <RIGHT-QUOTE> \", \"“\": \" <LEFT-QUOTE> \", \"-\": \" <HYPHEN>",
"normalize(s) tokens = [] for word in s.split(\" \"): if len(word) == 0:",
"(ks, v) in substitutions.items(): for k in ks: if k in s: s",
"\")\": \" <RIGHT-PAREN> \", \"&\": \" <AND>\", } deletions = {\"¿\", \"¡\"} def",
"<SINGLE-QUOTE> \", '\"«»': \" <DOUBLE-QUOTE> \", \"/\": \" <SLASH> \", \"\\\\\": \" <BACK-SLASH>",
"in ks: if k in s: s = s.replace(k, v) for k in",
"substitutions = { \"'’‘\": \" <SINGLE-QUOTE> \", '\"«»': \" <DOUBLE-QUOTE> \", \"/\": \"",
"\" <EOS>\" while \" \" in s: s = s.replace(\" \", \" \")",
"in deletions: if k in s: s = s.replace(k, \"\") s = \"<SOS>",
"tokens if token not in [\"<EOS>\", \"<SOS>\"]] s = \" \".join(tokens) return denormalize_string(s)",
"\":\": \" <COLON> \", \";\": \" <SEMI-COLON> \", \"+\": \"<PLUS> \", \"(\": \"",
"\"]\": \" <RIGHT-BRACKET> \", \"?\": \" <QUESTION> \", \"!\": \" <EXCLAMATION> \", \",\":",
"s.replace(k, v) for k in deletions: if k in s: s = s.replace(k,",
"for (ks, v) in substitutions.items(): for k in ks: if k in s:",
"continue elif word.isdigit(): tokens.append(\"<NUMBER>\") else: tokens.append(word) return tokens def denormalize_string(s): for (ks, v)",
"{ \"'’‘\": \" <SINGLE-QUOTE> \", '\"«»': \" <DOUBLE-QUOTE> \", \"/\": \" <SLASH> \",",
"s.replace(\"--\", \"-\") for (ks, v) in substitutions.items(): for k in ks: if k",
"tokens def denormalize_string(s): for (ks, v) in substitutions.items(): if v in s: s",
"k in ks: if k in s: s = s.replace(k, v) for k",
"s.lower().replace(\".\", \"\").replace(\"\\n\", \"\") while \"--\" in s: s = s.replace(\"--\", \"-\") for (ks,",
"v) in substitutions.items(): for k in ks: if k in s: s =",
"def normalize(s): s = s.lower().replace(\".\", \"\").replace(\"\\n\", \"\") while \"--\" in s: s =",
"\" in s: s = s.replace(\" \", \" \") return s def tokenize(s):",
"\" + s.strip() + \" <EOS>\" while \" \" in s: s =",
"def tokenize(s): s = normalize(s) tokens = [] for word in s.split(\" \"):",
"\",\": \" <COMMA> \", \":\": \" <COLON> \", \";\": \" <SEMI-COLON> \", \"+\":",
"\", \"\\\\\": \" <BACK-SLASH> \", \"”\": \" <RIGHT-QUOTE> \", \"“\": \" <LEFT-QUOTE> \",",
"<QUESTION> \", \"!\": \" <EXCLAMATION> \", \",\": \" <COMMA> \", \":\": \" <COLON>",
"<EXCLAMATION> \", \",\": \" <COMMA> \", \":\": \" <COLON> \", \";\": \" <SEMI-COLON>",
"normalize(s): s = s.lower().replace(\".\", \"\").replace(\"\\n\", \"\") while \"--\" in s: s = s.replace(\"--\",",
"\"¡\"} def normalize(s): s = s.lower().replace(\".\", \"\").replace(\"\\n\", \"\") while \"--\" in s: s",
"substitutions.items(): for k in ks: if k in s: s = s.replace(k, v)",
"= [] for word in s.split(\" \"): if len(word) == 0: continue elif",
"\"+\": \"<PLUS> \", \"(\": \" <LEFT-PAREN> \", \")\": \" <RIGHT-PAREN> \", \"&\": \"",
"{\"¿\", \"¡\"} def normalize(s): s = s.lower().replace(\".\", \"\").replace(\"\\n\", \"\") while \"--\" in s:",
"\" <RIGHT-PAREN> \", \"&\": \" <AND>\", } deletions = {\"¿\", \"¡\"} def normalize(s):",
"= \"<SOS> \" + s.strip() + \" <EOS>\" while \" \" in s:",
"else: tokens.append(word) return tokens def denormalize_string(s): for (ks, v) in substitutions.items(): if v",
"in s.split(\" \"): if len(word) == 0: continue elif word.isdigit(): tokens.append(\"<NUMBER>\") else: tokens.append(word)",
"\"<SOS> \" + s.strip() + \" <EOS>\" while \" \" in s: s",
"k in s: s = s.replace(k, v) for k in deletions: if k",
"\", '\"«»': \" <DOUBLE-QUOTE> \", \"/\": \" <SLASH> \", \"\\\\\": \" <BACK-SLASH> \",",
"\", \";\": \" <SEMI-COLON> \", \"+\": \"<PLUS> \", \"(\": \" <LEFT-PAREN> \", \")\":",
"\"--\" in s: s = s.replace(\"--\", \"-\") for (ks, v) in substitutions.items(): for",
"in substitutions.items(): for k in ks: if k in s: s = s.replace(k,",
"s def detokenize(tokens): tokens = [token for token in tokens if token not",
"\"[\": \" <LEFT-BRACKET> \", \"]\": \" <RIGHT-BRACKET> \", \"?\": \" <QUESTION> \", \"!\":"
] |
[
"parser.add_argument(\"xsd\", help=\"XSD schema to validate against\") return parser.parse_args() def validate(xml, xsd): try: parseAndValidate(xml,",
"genxmlif import GenXmlIfError from minixsv.xsvalErrorHandler import XsvalError ValidationResult = namedtuple(\"Result\", \"passed message\") def",
"file against XSD schema using minixsd library. <NAME> (<EMAIL>) The Pennsylvania State University",
"schema to validate against\") return parser.parse_args() def validate(xml, xsd): try: parseAndValidate(xml, xsdFile=xsd) except",
"errstr) return ValidationResult(True, \"{0} complies to {1}\".format(xml, xsd)) def cli(): args = get_args()",
"except XsvalError, errstr: return ValidationResult(False, errstr) return ValidationResult(True, \"{0} complies to {1}\".format(xml, xsd))",
"= get_args() result = validate(args.xml, args.xsd) print result.message if __name__ == \"__main__\": cli()",
"return ValidationResult(False, errstr) except GenXmlIfError, errstr: return ValidationResult(False, errstr) except XsvalError, errstr: return",
"XSD schema using \"\\ \"the minixsd Python library.\" parser = argparse.ArgumentParser(description=description) parser.add_argument(\"xml\", help=\"XML",
"(<EMAIL>) The Pennsylvania State University Applied Research Laboratory 2012 \"\"\" import argparse from",
"using \"\\ \"the minixsd Python library.\" parser = argparse.ArgumentParser(description=description) parser.add_argument(\"xml\", help=\"XML file to",
"\"\\ \"the minixsd Python library.\" parser = argparse.ArgumentParser(description=description) parser.add_argument(\"xml\", help=\"XML file to validate\")",
"Pennsylvania State University Applied Research Laboratory 2012 \"\"\" import argparse from collections import",
"file against XSD schema using \"\\ \"the minixsd Python library.\" parser = argparse.ArgumentParser(description=description)",
"minixsd library. <NAME> (<EMAIL>) The Pennsylvania State University Applied Research Laboratory 2012 \"\"\"",
"xsd): try: parseAndValidate(xml, xsdFile=xsd) except IOError, errstr: return ValidationResult(False, errstr) except GenXmlIfError, errstr:",
"to validate against\") return parser.parse_args() def validate(xml, xsd): try: parseAndValidate(xml, xsdFile=xsd) except IOError,",
"validate against\") return parser.parse_args() def validate(xml, xsd): try: parseAndValidate(xml, xsdFile=xsd) except IOError, errstr:",
"def cli(): args = get_args() result = validate(args.xml, args.xsd) print result.message if __name__",
"Validate XML file against XSD schema using minixsd library. <NAME> (<EMAIL>) The Pennsylvania",
"Python library.\" parser = argparse.ArgumentParser(description=description) parser.add_argument(\"xml\", help=\"XML file to validate\") parser.add_argument(\"xsd\", help=\"XSD schema",
"collections import namedtuple from minixsv.pyxsval import parseAndValidate from genxmlif import GenXmlIfError from minixsv.xsvalErrorHandler",
"ValidationResult(False, errstr) except GenXmlIfError, errstr: return ValidationResult(False, errstr) except XsvalError, errstr: return ValidationResult(False,",
"from collections import namedtuple from minixsv.pyxsval import parseAndValidate from genxmlif import GenXmlIfError from",
"help=\"XML file to validate\") parser.add_argument(\"xsd\", help=\"XSD schema to validate against\") return parser.parse_args() def",
"file to validate\") parser.add_argument(\"xsd\", help=\"XSD schema to validate against\") return parser.parse_args() def validate(xml,",
"{1}\".format(xml, xsd)) def cli(): args = get_args() result = validate(args.xml, args.xsd) print result.message",
"namedtuple from minixsv.pyxsval import parseAndValidate from genxmlif import GenXmlIfError from minixsv.xsvalErrorHandler import XsvalError",
"import XsvalError ValidationResult = namedtuple(\"Result\", \"passed message\") def get_args(): description = \"Validate XML",
"against XSD schema using \"\\ \"the minixsd Python library.\" parser = argparse.ArgumentParser(description=description) parser.add_argument(\"xml\",",
"parser.parse_args() def validate(xml, xsd): try: parseAndValidate(xml, xsdFile=xsd) except IOError, errstr: return ValidationResult(False, errstr)",
"get_args() result = validate(args.xml, args.xsd) print result.message if __name__ == \"__main__\": cli() #",
"GenXmlIfError, errstr: return ValidationResult(False, errstr) except XsvalError, errstr: return ValidationResult(False, errstr) return ValidationResult(True,",
"\"the minixsd Python library.\" parser = argparse.ArgumentParser(description=description) parser.add_argument(\"xml\", help=\"XML file to validate\") parser.add_argument(\"xsd\",",
"errstr: return ValidationResult(False, errstr) except XsvalError, errstr: return ValidationResult(False, errstr) return ValidationResult(True, \"{0}",
"cli(): args = get_args() result = validate(args.xml, args.xsd) print result.message if __name__ ==",
"library. <NAME> (<EMAIL>) The Pennsylvania State University Applied Research Laboratory 2012 \"\"\" import",
"except GenXmlIfError, errstr: return ValidationResult(False, errstr) except XsvalError, errstr: return ValidationResult(False, errstr) return",
"import argparse from collections import namedtuple from minixsv.pyxsval import parseAndValidate from genxmlif import",
"from minixsv.pyxsval import parseAndValidate from genxmlif import GenXmlIfError from minixsv.xsvalErrorHandler import XsvalError ValidationResult",
"The Pennsylvania State University Applied Research Laboratory 2012 \"\"\" import argparse from collections",
"validate(xml, xsd): try: parseAndValidate(xml, xsdFile=xsd) except IOError, errstr: return ValidationResult(False, errstr) except GenXmlIfError,",
"library.\" parser = argparse.ArgumentParser(description=description) parser.add_argument(\"xml\", help=\"XML file to validate\") parser.add_argument(\"xsd\", help=\"XSD schema to",
"xsd)) def cli(): args = get_args() result = validate(args.xml, args.xsd) print result.message if",
"against XSD schema using minixsd library. <NAME> (<EMAIL>) The Pennsylvania State University Applied",
"import GenXmlIfError from minixsv.xsvalErrorHandler import XsvalError ValidationResult = namedtuple(\"Result\", \"passed message\") def get_args():",
"schema using \"\\ \"the minixsd Python library.\" parser = argparse.ArgumentParser(description=description) parser.add_argument(\"xml\", help=\"XML file",
"<NAME> (<EMAIL>) The Pennsylvania State University Applied Research Laboratory 2012 \"\"\" import argparse",
"help=\"XSD schema to validate against\") return parser.parse_args() def validate(xml, xsd): try: parseAndValidate(xml, xsdFile=xsd)",
"return parser.parse_args() def validate(xml, xsd): try: parseAndValidate(xml, xsdFile=xsd) except IOError, errstr: return ValidationResult(False,",
"result = validate(args.xml, args.xsd) print result.message if __name__ == \"__main__\": cli() # vim:ts=4:sw=4:expandtab:fdm=indent:wrap",
"Applied Research Laboratory 2012 \"\"\" import argparse from collections import namedtuple from minixsv.pyxsval",
"try: parseAndValidate(xml, xsdFile=xsd) except IOError, errstr: return ValidationResult(False, errstr) except GenXmlIfError, errstr: return",
"IOError, errstr: return ValidationResult(False, errstr) except GenXmlIfError, errstr: return ValidationResult(False, errstr) except XsvalError,",
"Research Laboratory 2012 \"\"\" import argparse from collections import namedtuple from minixsv.pyxsval import",
"namedtuple(\"Result\", \"passed message\") def get_args(): description = \"Validate XML file against XSD schema",
"return ValidationResult(False, errstr) except XsvalError, errstr: return ValidationResult(False, errstr) return ValidationResult(True, \"{0} complies",
"errstr: return ValidationResult(False, errstr) except GenXmlIfError, errstr: return ValidationResult(False, errstr) except XsvalError, errstr:",
"University Applied Research Laboratory 2012 \"\"\" import argparse from collections import namedtuple from",
"argparse.ArgumentParser(description=description) parser.add_argument(\"xml\", help=\"XML file to validate\") parser.add_argument(\"xsd\", help=\"XSD schema to validate against\") return",
"parseAndValidate(xml, xsdFile=xsd) except IOError, errstr: return ValidationResult(False, errstr) except GenXmlIfError, errstr: return ValidationResult(False,",
"XML file against XSD schema using minixsd library. <NAME> (<EMAIL>) The Pennsylvania State",
"\"passed message\") def get_args(): description = \"Validate XML file against XSD schema using",
"using minixsd library. <NAME> (<EMAIL>) The Pennsylvania State University Applied Research Laboratory 2012",
"def get_args(): description = \"Validate XML file against XSD schema using \"\\ \"the",
"= \"Validate XML file against XSD schema using \"\\ \"the minixsd Python library.\"",
"State University Applied Research Laboratory 2012 \"\"\" import argparse from collections import namedtuple",
"complies to {1}\".format(xml, xsd)) def cli(): args = get_args() result = validate(args.xml, args.xsd)",
"args = get_args() result = validate(args.xml, args.xsd) print result.message if __name__ == \"__main__\":",
"errstr) except XsvalError, errstr: return ValidationResult(False, errstr) return ValidationResult(True, \"{0} complies to {1}\".format(xml,",
"errstr) except GenXmlIfError, errstr: return ValidationResult(False, errstr) except XsvalError, errstr: return ValidationResult(False, errstr)",
"XsvalError ValidationResult = namedtuple(\"Result\", \"passed message\") def get_args(): description = \"Validate XML file",
"parser.add_argument(\"xml\", help=\"XML file to validate\") parser.add_argument(\"xsd\", help=\"XSD schema to validate against\") return parser.parse_args()",
"xsdFile=xsd) except IOError, errstr: return ValidationResult(False, errstr) except GenXmlIfError, errstr: return ValidationResult(False, errstr)",
"from minixsv.xsvalErrorHandler import XsvalError ValidationResult = namedtuple(\"Result\", \"passed message\") def get_args(): description =",
"\"{0} complies to {1}\".format(xml, xsd)) def cli(): args = get_args() result = validate(args.xml,",
"Laboratory 2012 \"\"\" import argparse from collections import namedtuple from minixsv.pyxsval import parseAndValidate",
"parseAndValidate from genxmlif import GenXmlIfError from minixsv.xsvalErrorHandler import XsvalError ValidationResult = namedtuple(\"Result\", \"passed",
"return ValidationResult(False, errstr) return ValidationResult(True, \"{0} complies to {1}\".format(xml, xsd)) def cli(): args",
"message\") def get_args(): description = \"Validate XML file against XSD schema using \"\\",
"except IOError, errstr: return ValidationResult(False, errstr) except GenXmlIfError, errstr: return ValidationResult(False, errstr) except",
"\"\"\" validate.py Validate XML file against XSD schema using minixsd library. <NAME> (<EMAIL>)",
"\"\"\" import argparse from collections import namedtuple from minixsv.pyxsval import parseAndValidate from genxmlif",
"XSD schema using minixsd library. <NAME> (<EMAIL>) The Pennsylvania State University Applied Research",
"description = \"Validate XML file against XSD schema using \"\\ \"the minixsd Python",
"from genxmlif import GenXmlIfError from minixsv.xsvalErrorHandler import XsvalError ValidationResult = namedtuple(\"Result\", \"passed message\")",
"against\") return parser.parse_args() def validate(xml, xsd): try: parseAndValidate(xml, xsdFile=xsd) except IOError, errstr: return",
"to {1}\".format(xml, xsd)) def cli(): args = get_args() result = validate(args.xml, args.xsd) print",
"import parseAndValidate from genxmlif import GenXmlIfError from minixsv.xsvalErrorHandler import XsvalError ValidationResult = namedtuple(\"Result\",",
"return ValidationResult(True, \"{0} complies to {1}\".format(xml, xsd)) def cli(): args = get_args() result",
"XsvalError, errstr: return ValidationResult(False, errstr) return ValidationResult(True, \"{0} complies to {1}\".format(xml, xsd)) def",
"ValidationResult(False, errstr) return ValidationResult(True, \"{0} complies to {1}\".format(xml, xsd)) def cli(): args =",
"= validate(args.xml, args.xsd) print result.message if __name__ == \"__main__\": cli() # vim:ts=4:sw=4:expandtab:fdm=indent:wrap lbr:ai",
"minixsv.pyxsval import parseAndValidate from genxmlif import GenXmlIfError from minixsv.xsvalErrorHandler import XsvalError ValidationResult =",
"get_args(): description = \"Validate XML file against XSD schema using \"\\ \"the minixsd",
"import namedtuple from minixsv.pyxsval import parseAndValidate from genxmlif import GenXmlIfError from minixsv.xsvalErrorHandler import",
"validate.py Validate XML file against XSD schema using minixsd library. <NAME> (<EMAIL>) The",
"XML file against XSD schema using \"\\ \"the minixsd Python library.\" parser =",
"minixsd Python library.\" parser = argparse.ArgumentParser(description=description) parser.add_argument(\"xml\", help=\"XML file to validate\") parser.add_argument(\"xsd\", help=\"XSD",
"argparse from collections import namedtuple from minixsv.pyxsval import parseAndValidate from genxmlif import GenXmlIfError",
"= namedtuple(\"Result\", \"passed message\") def get_args(): description = \"Validate XML file against XSD",
"ValidationResult(False, errstr) except XsvalError, errstr: return ValidationResult(False, errstr) return ValidationResult(True, \"{0} complies to",
"ValidationResult(True, \"{0} complies to {1}\".format(xml, xsd)) def cli(): args = get_args() result =",
"errstr: return ValidationResult(False, errstr) return ValidationResult(True, \"{0} complies to {1}\".format(xml, xsd)) def cli():",
"to validate\") parser.add_argument(\"xsd\", help=\"XSD schema to validate against\") return parser.parse_args() def validate(xml, xsd):",
"\"Validate XML file against XSD schema using \"\\ \"the minixsd Python library.\" parser",
"ValidationResult = namedtuple(\"Result\", \"passed message\") def get_args(): description = \"Validate XML file against",
"schema using minixsd library. <NAME> (<EMAIL>) The Pennsylvania State University Applied Research Laboratory",
"GenXmlIfError from minixsv.xsvalErrorHandler import XsvalError ValidationResult = namedtuple(\"Result\", \"passed message\") def get_args(): description",
"minixsv.xsvalErrorHandler import XsvalError ValidationResult = namedtuple(\"Result\", \"passed message\") def get_args(): description = \"Validate",
"2012 \"\"\" import argparse from collections import namedtuple from minixsv.pyxsval import parseAndValidate from",
"parser = argparse.ArgumentParser(description=description) parser.add_argument(\"xml\", help=\"XML file to validate\") parser.add_argument(\"xsd\", help=\"XSD schema to validate",
"validate\") parser.add_argument(\"xsd\", help=\"XSD schema to validate against\") return parser.parse_args() def validate(xml, xsd): try:",
"= argparse.ArgumentParser(description=description) parser.add_argument(\"xml\", help=\"XML file to validate\") parser.add_argument(\"xsd\", help=\"XSD schema to validate against\")",
"def validate(xml, xsd): try: parseAndValidate(xml, xsdFile=xsd) except IOError, errstr: return ValidationResult(False, errstr) except"
] |
[
"one face\")) continue X.append(face_recognition.face_encodings(image, known_face_locations=faces_bboxes)[0]) y.append(class_dir) if n_neighbors is None: n_neighbors = int(round(sqrt(len(X))))",
"from face_recognition import face_locations from face_recognition.cli import image_files_in_folder import cv2 def train(train_dir, n_neighbors",
"< 1 else \"found more than one face\")) continue X.append(face_recognition.face_encodings(image, known_face_locations=faces_bboxes)[0]) y.append(class_dir) if",
"= 'ball_tree', verbose=False): X = [] y = [] for class_dir in listdir(train_dir):",
"the file to save as pkl file with open(model_save_path, 'wb') as model_pkl: pickle.dump(knn_clf,",
"with Pickle model_save_path = '/home/pi/Desktop/model_classifier.pkl' # Open the file to save as pkl",
"isdir(join(train_dir, class_dir)): continue for img_path in image_files_in_folder(join(train_dir, class_dir)): image = face_recognition.load_image_file(img_path) faces_bboxes =",
"knn_algo = 'ball_tree', verbose=False): X = [] y = [] for class_dir in",
"verbose: print(\"image {} not fit for training: {}\".format(img_path, \"didn't find a face\" if",
"'wb') as model_pkl: pickle.dump(knn_clf, model_pkl) # Close the pickle instance model_pkl.close() print(\"Model created",
"from math import sqrt from sklearn import neighbors from os import listdir from",
"neighbors.KNeighborsClassifier(n_neighbors=n_neighbors, algorithm=knn_algo, weights='distance') knn_clf.fit(X, y) # Dump the trained decision tree classifier with",
"= [] y = [] for class_dir in listdir(train_dir): if not isdir(join(train_dir, class_dir)):",
"n_neighbors automatically as:\", n_neighbors) knn_clf = neighbors.KNeighborsClassifier(n_neighbors=n_neighbors, algorithm=knn_algo, weights='distance') knn_clf.fit(X, y) # Dump",
"def train(train_dir, n_neighbors = None, knn_algo = 'ball_tree', verbose=False): X = [] y",
"import listdir from os.path import isdir, join, isfile, splitext import pickle import face_recognition",
"n_neighbors = int(round(sqrt(len(X)))) if verbose: print(\"Chose n_neighbors automatically as:\", n_neighbors) knn_clf = neighbors.KNeighborsClassifier(n_neighbors=n_neighbors,",
"from os.path import isdir, join, isfile, splitext import pickle import face_recognition from face_recognition",
"X = [] y = [] for class_dir in listdir(train_dir): if not isdir(join(train_dir,",
"faces_bboxes = face_locations(image) if len(faces_bboxes) != 1: if verbose: print(\"image {} not fit",
"face_recognition.load_image_file(img_path) faces_bboxes = face_locations(image) if len(faces_bboxes) != 1: if verbose: print(\"image {} not",
"print(\"Chose n_neighbors automatically as:\", n_neighbors) knn_clf = neighbors.KNeighborsClassifier(n_neighbors=n_neighbors, algorithm=knn_algo, weights='distance') knn_clf.fit(X, y) #",
"tree classifier with Pickle model_save_path = '/home/pi/Desktop/model_classifier.pkl' # Open the file to save",
"neighbors from os import listdir from os.path import isdir, join, isfile, splitext import",
"as:\", n_neighbors) knn_clf = neighbors.KNeighborsClassifier(n_neighbors=n_neighbors, algorithm=knn_algo, weights='distance') knn_clf.fit(X, y) # Dump the trained",
"[] y = [] for class_dir in listdir(train_dir): if not isdir(join(train_dir, class_dir)): continue",
"if not isdir(join(train_dir, class_dir)): continue for img_path in image_files_in_folder(join(train_dir, class_dir)): image = face_recognition.load_image_file(img_path)",
"a face\" if len(faces_bboxes) < 1 else \"found more than one face\")) continue",
"Pickle model_save_path = '/home/pi/Desktop/model_classifier.pkl' # Open the file to save as pkl file",
"{} not fit for training: {}\".format(img_path, \"didn't find a face\" if len(faces_bboxes) <",
"the trained decision tree classifier with Pickle model_save_path = '/home/pi/Desktop/model_classifier.pkl' # Open the",
"training: {}\".format(img_path, \"didn't find a face\" if len(faces_bboxes) < 1 else \"found more",
"weights='distance') knn_clf.fit(X, y) # Dump the trained decision tree classifier with Pickle model_save_path",
"{}\".format(img_path, \"didn't find a face\" if len(faces_bboxes) < 1 else \"found more than",
"# Open the file to save as pkl file with open(model_save_path, 'wb') as",
"to save as pkl file with open(model_save_path, 'wb') as model_pkl: pickle.dump(knn_clf, model_pkl) #",
"if verbose: print(\"image {} not fit for training: {}\".format(img_path, \"didn't find a face\"",
"1: if verbose: print(\"image {} not fit for training: {}\".format(img_path, \"didn't find a",
"train(train_dir, n_neighbors = None, knn_algo = 'ball_tree', verbose=False): X = [] y =",
"decision tree classifier with Pickle model_save_path = '/home/pi/Desktop/model_classifier.pkl' # Open the file to",
"import face_locations from face_recognition.cli import image_files_in_folder import cv2 def train(train_dir, n_neighbors = None,",
"y) # Dump the trained decision tree classifier with Pickle model_save_path = '/home/pi/Desktop/model_classifier.pkl'",
"listdir from os.path import isdir, join, isfile, splitext import pickle import face_recognition from",
"<filename>src/resources/face_train.py from math import sqrt from sklearn import neighbors from os import listdir",
"in listdir(train_dir): if not isdir(join(train_dir, class_dir)): continue for img_path in image_files_in_folder(join(train_dir, class_dir)): image",
"in image_files_in_folder(join(train_dir, class_dir)): image = face_recognition.load_image_file(img_path) faces_bboxes = face_locations(image) if len(faces_bboxes) != 1:",
"class_dir)): continue for img_path in image_files_in_folder(join(train_dir, class_dir)): image = face_recognition.load_image_file(img_path) faces_bboxes = face_locations(image)",
"class_dir in listdir(train_dir): if not isdir(join(train_dir, class_dir)): continue for img_path in image_files_in_folder(join(train_dir, class_dir)):",
"= neighbors.KNeighborsClassifier(n_neighbors=n_neighbors, algorithm=knn_algo, weights='distance') knn_clf.fit(X, y) # Dump the trained decision tree classifier",
"if len(faces_bboxes) != 1: if verbose: print(\"image {} not fit for training: {}\".format(img_path,",
"algorithm=knn_algo, weights='distance') knn_clf.fit(X, y) # Dump the trained decision tree classifier with Pickle",
"known_face_locations=faces_bboxes)[0]) y.append(class_dir) if n_neighbors is None: n_neighbors = int(round(sqrt(len(X)))) if verbose: print(\"Chose n_neighbors",
"# Dump the trained decision tree classifier with Pickle model_save_path = '/home/pi/Desktop/model_classifier.pkl' #",
"import isdir, join, isfile, splitext import pickle import face_recognition from face_recognition import face_locations",
"isdir, join, isfile, splitext import pickle import face_recognition from face_recognition import face_locations from",
"listdir(train_dir): if not isdir(join(train_dir, class_dir)): continue for img_path in image_files_in_folder(join(train_dir, class_dir)): image =",
"y.append(class_dir) if n_neighbors is None: n_neighbors = int(round(sqrt(len(X)))) if verbose: print(\"Chose n_neighbors automatically",
"verbose=False): X = [] y = [] for class_dir in listdir(train_dir): if not",
"model_pkl: pickle.dump(knn_clf, model_pkl) # Close the pickle instance model_pkl.close() print(\"Model created successfully.\") #return",
"n_neighbors = None, knn_algo = 'ball_tree', verbose=False): X = [] y = []",
"len(faces_bboxes) < 1 else \"found more than one face\")) continue X.append(face_recognition.face_encodings(image, known_face_locations=faces_bboxes)[0]) y.append(class_dir)",
"cv2 def train(train_dir, n_neighbors = None, knn_algo = 'ball_tree', verbose=False): X = []",
"class_dir)): image = face_recognition.load_image_file(img_path) faces_bboxes = face_locations(image) if len(faces_bboxes) != 1: if verbose:",
"knn_clf = neighbors.KNeighborsClassifier(n_neighbors=n_neighbors, algorithm=knn_algo, weights='distance') knn_clf.fit(X, y) # Dump the trained decision tree",
"= face_locations(image) if len(faces_bboxes) != 1: if verbose: print(\"image {} not fit for",
"more than one face\")) continue X.append(face_recognition.face_encodings(image, known_face_locations=faces_bboxes)[0]) y.append(class_dir) if n_neighbors is None: n_neighbors",
"import pickle import face_recognition from face_recognition import face_locations from face_recognition.cli import image_files_in_folder import",
"img_path in image_files_in_folder(join(train_dir, class_dir)): image = face_recognition.load_image_file(img_path) faces_bboxes = face_locations(image) if len(faces_bboxes) !=",
"if len(faces_bboxes) < 1 else \"found more than one face\")) continue X.append(face_recognition.face_encodings(image, known_face_locations=faces_bboxes)[0])",
"os.path import isdir, join, isfile, splitext import pickle import face_recognition from face_recognition import",
"as pkl file with open(model_save_path, 'wb') as model_pkl: pickle.dump(knn_clf, model_pkl) # Close the",
"fit for training: {}\".format(img_path, \"didn't find a face\" if len(faces_bboxes) < 1 else",
"from os import listdir from os.path import isdir, join, isfile, splitext import pickle",
"not isdir(join(train_dir, class_dir)): continue for img_path in image_files_in_folder(join(train_dir, class_dir)): image = face_recognition.load_image_file(img_path) faces_bboxes",
"import image_files_in_folder import cv2 def train(train_dir, n_neighbors = None, knn_algo = 'ball_tree', verbose=False):",
"Dump the trained decision tree classifier with Pickle model_save_path = '/home/pi/Desktop/model_classifier.pkl' # Open",
"file to save as pkl file with open(model_save_path, 'wb') as model_pkl: pickle.dump(knn_clf, model_pkl)",
"pkl file with open(model_save_path, 'wb') as model_pkl: pickle.dump(knn_clf, model_pkl) # Close the pickle",
"for img_path in image_files_in_folder(join(train_dir, class_dir)): image = face_recognition.load_image_file(img_path) faces_bboxes = face_locations(image) if len(faces_bboxes)",
"face_recognition import face_locations from face_recognition.cli import image_files_in_folder import cv2 def train(train_dir, n_neighbors =",
"if verbose: print(\"Chose n_neighbors automatically as:\", n_neighbors) knn_clf = neighbors.KNeighborsClassifier(n_neighbors=n_neighbors, algorithm=knn_algo, weights='distance') knn_clf.fit(X,",
"= [] for class_dir in listdir(train_dir): if not isdir(join(train_dir, class_dir)): continue for img_path",
"file with open(model_save_path, 'wb') as model_pkl: pickle.dump(knn_clf, model_pkl) # Close the pickle instance",
"= face_recognition.load_image_file(img_path) faces_bboxes = face_locations(image) if len(faces_bboxes) != 1: if verbose: print(\"image {}",
"n_neighbors is None: n_neighbors = int(round(sqrt(len(X)))) if verbose: print(\"Chose n_neighbors automatically as:\", n_neighbors)",
"os import listdir from os.path import isdir, join, isfile, splitext import pickle import",
"math import sqrt from sklearn import neighbors from os import listdir from os.path",
"face\" if len(faces_bboxes) < 1 else \"found more than one face\")) continue X.append(face_recognition.face_encodings(image,",
"= '/home/pi/Desktop/model_classifier.pkl' # Open the file to save as pkl file with open(model_save_path,",
"face_recognition.cli import image_files_in_folder import cv2 def train(train_dir, n_neighbors = None, knn_algo = 'ball_tree',",
"pickle.dump(knn_clf, model_pkl) # Close the pickle instance model_pkl.close() print(\"Model created successfully.\") #return knn_clf",
"trained decision tree classifier with Pickle model_save_path = '/home/pi/Desktop/model_classifier.pkl' # Open the file",
"else \"found more than one face\")) continue X.append(face_recognition.face_encodings(image, known_face_locations=faces_bboxes)[0]) y.append(class_dir) if n_neighbors is",
"than one face\")) continue X.append(face_recognition.face_encodings(image, known_face_locations=faces_bboxes)[0]) y.append(class_dir) if n_neighbors is None: n_neighbors =",
"save as pkl file with open(model_save_path, 'wb') as model_pkl: pickle.dump(knn_clf, model_pkl) # Close",
"find a face\" if len(faces_bboxes) < 1 else \"found more than one face\"))",
"classifier with Pickle model_save_path = '/home/pi/Desktop/model_classifier.pkl' # Open the file to save as",
"image_files_in_folder(join(train_dir, class_dir)): image = face_recognition.load_image_file(img_path) faces_bboxes = face_locations(image) if len(faces_bboxes) != 1: if",
"n_neighbors) knn_clf = neighbors.KNeighborsClassifier(n_neighbors=n_neighbors, algorithm=knn_algo, weights='distance') knn_clf.fit(X, y) # Dump the trained decision",
"X.append(face_recognition.face_encodings(image, known_face_locations=faces_bboxes)[0]) y.append(class_dir) if n_neighbors is None: n_neighbors = int(round(sqrt(len(X)))) if verbose: print(\"Chose",
"print(\"image {} not fit for training: {}\".format(img_path, \"didn't find a face\" if len(faces_bboxes)",
"import sqrt from sklearn import neighbors from os import listdir from os.path import",
"face_locations from face_recognition.cli import image_files_in_folder import cv2 def train(train_dir, n_neighbors = None, knn_algo",
"for class_dir in listdir(train_dir): if not isdir(join(train_dir, class_dir)): continue for img_path in image_files_in_folder(join(train_dir,",
"pickle import face_recognition from face_recognition import face_locations from face_recognition.cli import image_files_in_folder import cv2",
"continue for img_path in image_files_in_folder(join(train_dir, class_dir)): image = face_recognition.load_image_file(img_path) faces_bboxes = face_locations(image) if",
"None, knn_algo = 'ball_tree', verbose=False): X = [] y = [] for class_dir",
"for training: {}\".format(img_path, \"didn't find a face\" if len(faces_bboxes) < 1 else \"found",
"import neighbors from os import listdir from os.path import isdir, join, isfile, splitext",
"\"didn't find a face\" if len(faces_bboxes) < 1 else \"found more than one",
"face_recognition from face_recognition import face_locations from face_recognition.cli import image_files_in_folder import cv2 def train(train_dir,",
"sqrt from sklearn import neighbors from os import listdir from os.path import isdir,",
"verbose: print(\"Chose n_neighbors automatically as:\", n_neighbors) knn_clf = neighbors.KNeighborsClassifier(n_neighbors=n_neighbors, algorithm=knn_algo, weights='distance') knn_clf.fit(X, y)",
"knn_clf.fit(X, y) # Dump the trained decision tree classifier with Pickle model_save_path =",
"image_files_in_folder import cv2 def train(train_dir, n_neighbors = None, knn_algo = 'ball_tree', verbose=False): X",
"not fit for training: {}\".format(img_path, \"didn't find a face\" if len(faces_bboxes) < 1",
"face_locations(image) if len(faces_bboxes) != 1: if verbose: print(\"image {} not fit for training:",
"sklearn import neighbors from os import listdir from os.path import isdir, join, isfile,",
"Open the file to save as pkl file with open(model_save_path, 'wb') as model_pkl:",
"automatically as:\", n_neighbors) knn_clf = neighbors.KNeighborsClassifier(n_neighbors=n_neighbors, algorithm=knn_algo, weights='distance') knn_clf.fit(X, y) # Dump the",
"import face_recognition from face_recognition import face_locations from face_recognition.cli import image_files_in_folder import cv2 def",
"model_pkl) # Close the pickle instance model_pkl.close() print(\"Model created successfully.\") #return knn_clf train(\"TrainData\")",
"y = [] for class_dir in listdir(train_dir): if not isdir(join(train_dir, class_dir)): continue for",
"import cv2 def train(train_dir, n_neighbors = None, knn_algo = 'ball_tree', verbose=False): X =",
"= None, knn_algo = 'ball_tree', verbose=False): X = [] y = [] for",
"is None: n_neighbors = int(round(sqrt(len(X)))) if verbose: print(\"Chose n_neighbors automatically as:\", n_neighbors) knn_clf",
"= int(round(sqrt(len(X)))) if verbose: print(\"Chose n_neighbors automatically as:\", n_neighbors) knn_clf = neighbors.KNeighborsClassifier(n_neighbors=n_neighbors, algorithm=knn_algo,",
"from sklearn import neighbors from os import listdir from os.path import isdir, join,",
"len(faces_bboxes) != 1: if verbose: print(\"image {} not fit for training: {}\".format(img_path, \"didn't",
"as model_pkl: pickle.dump(knn_clf, model_pkl) # Close the pickle instance model_pkl.close() print(\"Model created successfully.\")",
"1 else \"found more than one face\")) continue X.append(face_recognition.face_encodings(image, known_face_locations=faces_bboxes)[0]) y.append(class_dir) if n_neighbors",
"face\")) continue X.append(face_recognition.face_encodings(image, known_face_locations=faces_bboxes)[0]) y.append(class_dir) if n_neighbors is None: n_neighbors = int(round(sqrt(len(X)))) if",
"'/home/pi/Desktop/model_classifier.pkl' # Open the file to save as pkl file with open(model_save_path, 'wb')",
"model_save_path = '/home/pi/Desktop/model_classifier.pkl' # Open the file to save as pkl file with",
"open(model_save_path, 'wb') as model_pkl: pickle.dump(knn_clf, model_pkl) # Close the pickle instance model_pkl.close() print(\"Model",
"!= 1: if verbose: print(\"image {} not fit for training: {}\".format(img_path, \"didn't find",
"[] for class_dir in listdir(train_dir): if not isdir(join(train_dir, class_dir)): continue for img_path in",
"with open(model_save_path, 'wb') as model_pkl: pickle.dump(knn_clf, model_pkl) # Close the pickle instance model_pkl.close()",
"isfile, splitext import pickle import face_recognition from face_recognition import face_locations from face_recognition.cli import",
"\"found more than one face\")) continue X.append(face_recognition.face_encodings(image, known_face_locations=faces_bboxes)[0]) y.append(class_dir) if n_neighbors is None:",
"continue X.append(face_recognition.face_encodings(image, known_face_locations=faces_bboxes)[0]) y.append(class_dir) if n_neighbors is None: n_neighbors = int(round(sqrt(len(X)))) if verbose:",
"splitext import pickle import face_recognition from face_recognition import face_locations from face_recognition.cli import image_files_in_folder",
"None: n_neighbors = int(round(sqrt(len(X)))) if verbose: print(\"Chose n_neighbors automatically as:\", n_neighbors) knn_clf =",
"join, isfile, splitext import pickle import face_recognition from face_recognition import face_locations from face_recognition.cli",
"if n_neighbors is None: n_neighbors = int(round(sqrt(len(X)))) if verbose: print(\"Chose n_neighbors automatically as:\",",
"from face_recognition.cli import image_files_in_folder import cv2 def train(train_dir, n_neighbors = None, knn_algo =",
"image = face_recognition.load_image_file(img_path) faces_bboxes = face_locations(image) if len(faces_bboxes) != 1: if verbose: print(\"image",
"'ball_tree', verbose=False): X = [] y = [] for class_dir in listdir(train_dir): if",
"int(round(sqrt(len(X)))) if verbose: print(\"Chose n_neighbors automatically as:\", n_neighbors) knn_clf = neighbors.KNeighborsClassifier(n_neighbors=n_neighbors, algorithm=knn_algo, weights='distance')"
] |
[
"import BaseModel class Chat(BaseModel): telegram_id = BigIntegerField(unique=True) title = TextField(null=True) link = TextField(null=True)",
"from peewee import * from .base_model import BaseModel class Chat(BaseModel): telegram_id = BigIntegerField(unique=True)",
"from .base_model import BaseModel class Chat(BaseModel): telegram_id = BigIntegerField(unique=True) title = TextField(null=True) link",
".base_model import BaseModel class Chat(BaseModel): telegram_id = BigIntegerField(unique=True) title = TextField(null=True) link =",
"import * from .base_model import BaseModel class Chat(BaseModel): telegram_id = BigIntegerField(unique=True) title =",
"peewee import * from .base_model import BaseModel class Chat(BaseModel): telegram_id = BigIntegerField(unique=True) title",
"* from .base_model import BaseModel class Chat(BaseModel): telegram_id = BigIntegerField(unique=True) title = TextField(null=True)"
] |
[
"data_quiz, columns=['Chapter','Problem Set','Percent','Date','Completed'] ) quiz_df['Percent'] = pd.to_numeric(quiz_df['Percent']) quiz_df['days ago'] = pd.to_datetime(quiz_df['Date'])\\ .apply(lambda x:",
"locally\"\"\" studytimes = get_logins(sid,token) completion = get_completion_perc(sid,token) quiz_df = get_quiz_results(sid,token) # reindex studytimes",
"datetime.datetime.now() ) studytimes_reidx = studytimes.reindex(all_dates,fill_value=0) # WGU colors taken from https://www.wgu.edu/about/brand.html blue =",
"studytimes = pd.DataFrame( # first 10 characters of 'first_accessed' gives the date [(x['first_accessed'][:10],x['duration']/3600)",
"want Chapter 1 on top, Ch.7 on bottom plt.xlim(0,105) ax.set_xticks(np.arange(0,105,10)) ax.tick_params(length=0) ax.yaxis.grid(True, which='minor')",
"studytimes_reidx['duration']) ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d')) datemin = studytimes_reidx.index.min() datemax = datetime.datetime.today() ax.set_xlim(datemin, datemax) ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval=1)) plt.xticks(rotation=45);",
"get_me_sid(email,token): \"\"\"get MindEdge Student ID\"\"\" r = requests.post(base_url+'students', json={'token':token,'dId':55,'emailAddress':email}) return r.json()[0].get('sId') def get_completion_perc(sid,token):",
"give: # the ch number, quiz number, percent, date, and # of Q's",
"return completion def get_quiz_results(sid,token): r4 = requests.post(base_url+'studentTestData', json={'token':token,'dId':55,'cId':612,'sId':sid}) # parsing the text names",
"percent completion by module\"\"\" r3 = requests.post(base_url+'studentCompleteAssignments', json={'token':token,'dId':55,'cId':612,'sId':sid}) read_pages = [t['title'] for t",
"reindex studytimes to ensure that at least one month is visible # so",
"# select only pages with learning content: pages = [title for title in",
"without MindEdge access / password if 'un' not in vars(): un = 'wgudb'",
"except Exception as e: print('status: ',r.status_code,':',r.reason) print(e) print(\"Token not returned. Check password is",
"API token, and image output filename. Gathers all student data and creates dashboard",
"visible # so min of date_rage is the lesser of 1 mo ago",
"pd.to_numeric(quiz_df['Percent']) quiz_df['days ago'] = pd.to_datetime(quiz_df['Date'])\\ .apply(lambda x: (datetime.datetime.now()-x).days) quiz_df['# correct'] = quiz_df['Percent']/100 *",
"Q's answered data_quiz = [ (*test['title'].split('Module ')[1].split('Problem Set '), result['final_score'], result['dateCompleted'], result['totalQuestions'] )",
"ago'],cmap=plt.cm.viridis_r, vmin=0,vmax=max(14,quiz_df['days ago'].max()) ) cbar = plt.colorbar(sc) cbar.set_label(\"Days Since Quiz\") ax.set_yticks(np.arange(0.5,7.5,1), minor=True) plt.ylim(0.5,7.5)",
"'), result['final_score'], result['dateCompleted'], result['totalQuestions'] ) for test in r4.json() for result in test['resultData']",
"as pd import numpy as np import requests, datetime, webbrowser ## This code",
"and 'Problem Set' not in title )] idx = [i for i in",
"- study times vertical bar chart ax = plt.subplot(2,1,2) plt.bar(studytimes_reidx.index, studytimes_reidx['duration']) ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))",
"requests.post(base_url+'auth', json = {'username':un,'password':password}) try: return r.json()[0]['token'] except Exception as e: print('status: ',r.status_code,':',r.reason)",
"= pd.Series([23, 22, 30, 17, 8, 12, 16],index=idx) completion=100*pd.Series([int(p[0]) for p in pages])\\",
"in r4.json() for result in test['resultData'] ] quiz_df = pd.DataFrame( data_quiz, columns=['Chapter','Problem Set','Percent','Date','Completed']",
"top right axis - circle plot for quiz results ax = plt.subplot(2,2,2); sc",
"get_completion_perc(sid,token): \"\"\"returns dataframe of percent completion by module\"\"\" r3 = requests.post(base_url+'studentCompleteAssignments', json={'token':token,'dId':55,'cId':612,'sId':sid}) read_pages",
"t in r3.json()] # titles of pages read # select only pages with",
"2, figsize=(12, 8),sharey='row') fig.patch.set_facecolor('white') plt.subplots_adjust(hspace = 0.3) #more horizontal space between plots #top",
"date [(x['first_accessed'][:10],x['duration']/3600) for x in r5.json()] ) studytimes.columns = ['date','duration'] studytimes = studytimes.groupby('date').sum()",
"r = requests.post(base_url+'students', json={'token':token,'dId':55,'emailAddress':email}) return r.json()[0].get('sId') def get_completion_perc(sid,token): \"\"\"returns dataframe of percent completion",
"as plt from matplotlib import rcParams import matplotlib.dates as mdates import pandas as",
"get_quiz_results(sid,token) # reindex studytimes to ensure that at least one month is visible",
"completion = get_completion_perc(sid,token) quiz_df = get_quiz_results(sid,token) # reindex studytimes to ensure that at",
"text names of the quizzes to give: # the ch number, quiz number,",
"and 'Review' not in title and 'Problem Set' not in title )] idx",
"token, and image output filename. Gathers all student data and creates dashboard locally\"\"\"",
"green = '#509E2F' # change font rcParams['font.sans-serif'] = \"Futura Lt BT\" rcParams['font.family'] =",
"completion by module\"\"\" r3 = requests.post(base_url+'studentCompleteAssignments', json={'token':token,'dId':55,'cId':612,'sId':sid}) read_pages = [t['title'] for t in",
"quiz_df['y_value'], s=700,alpha=0.8,c=quiz_df['days ago'],cmap=plt.cm.viridis_r, vmin=0,vmax=max(14,quiz_df['days ago'].max()) ) cbar = plt.colorbar(sc) cbar.set_label(\"Days Since Quiz\") ax.set_yticks(np.arange(0.5,7.5,1),",
"quiz_df['Percent'] = pd.to_numeric(quiz_df['Percent']) quiz_df['days ago'] = pd.to_datetime(quiz_df['Date'])\\ .apply(lambda x: (datetime.datetime.now()-x).days) quiz_df['# correct'] =",
"#more horizontal space between plots #top left axis - completion horiz bar chart",
"\"\"\"returns dataframe of percent completion by module\"\"\" r3 = requests.post(base_url+'studentCompleteAssignments', json={'token':token,'dId':55,'cId':612,'sId':sid}) read_pages =",
"= [t['title'] for t in r3.json()] # titles of pages read # select",
"is visible # so min of date_rage is the lesser of 1 mo",
"get_completion_perc(sid,token) quiz_df = get_quiz_results(sid,token) # reindex studytimes to ensure that at least one",
"number, quiz number, percent, date, and # of Q's answered data_quiz = [",
"x: (datetime.datetime.now()-x).days) quiz_df['# correct'] = quiz_df['Percent']/100 * quiz_df['Completed'] quiz_df['y_value'] = pd.to_numeric(quiz_df['Chapter']) return quiz_df",
"trim outliers/glitches (e.g. 300 hours spent in one session) # we make 10",
"ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d')) datemin = studytimes_reidx.index.min() datemax = datetime.datetime.today() ax.set_xlim(datemin, datemax) ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval=1)) plt.xticks(rotation=45); ax.set_ylabel('hours",
"Exception as e: print('status: ',r.status_code,':',r.reason) print(e) print(\"Token not returned. Check password is correct\")",
"in title and 'Review' not in title and 'Problem Set' not in title",
"# to trim outliers/glitches (e.g. 300 hours spent in one session) # we",
"i in range(1,8)] # all_pages gives the total possible pages indexed by module",
"read_pages if ( '.' in title and 'Feedback' not in title and 'Flashcards'",
"mindedge_dashboard(sid,token,filename='dashboard.png'): \"\"\"input: studentID, active API token, and image output filename. Gathers all student",
"quiz_df['days ago'] = pd.to_datetime(quiz_df['Date'])\\ .apply(lambda x: (datetime.datetime.now()-x).days) quiz_df['# correct'] = quiz_df['Percent']/100 * quiz_df['Completed']",
"0.3) #more horizontal space between plots #top left axis - completion horiz bar",
"https://www.wgu.edu/about/brand.html blue = '#003057' lblue = '#4986AD' green = '#509E2F' # change font",
"pages with learning content: pages = [title for title in read_pages if (",
"minor=True) plt.ylim(0.5,7.5) plt.gca().invert_yaxis() # want Chapter 1 on top, Ch.7 on bottom plt.xlim(0,105)",
"pd.to_datetime(quiz_df['Date'])\\ .apply(lambda x: (datetime.datetime.now()-x).days) quiz_df['# correct'] = quiz_df['Percent']/100 * quiz_df['Completed'] quiz_df['y_value'] = pd.to_numeric(quiz_df['Chapter'])",
"12, 16],index=idx) completion=100*pd.Series([int(p[0]) for p in pages])\\ .value_counts().reindex(idx,fill_value=0)/all_pages return completion def get_quiz_results(sid,token): r4",
"change font rcParams['font.sans-serif'] = \"Futura Lt BT\" rcParams['font.family'] = \"sans-serif\" rcParams['font.size'] = 14",
"figsize=(12, 8),sharey='row') fig.patch.set_facecolor('white') plt.subplots_adjust(hspace = 0.3) #more horizontal space between plots #top left",
"%d')) datemin = studytimes_reidx.index.min() datemax = datetime.datetime.today() ax.set_xlim(datemin, datemax) ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval=1)) plt.xticks(rotation=45); ax.set_ylabel('hours studied');",
"= pd.to_numeric(quiz_df['Percent']) quiz_df['days ago'] = pd.to_datetime(quiz_df['Date'])\\ .apply(lambda x: (datetime.datetime.now()-x).days) quiz_df['# correct'] = quiz_df['Percent']/100",
"Mindedge password:\") base_url = 'https://wguapps.mindedgeonline.com/services/api/' domain_id = 55 def get_token(password): r = requests.post(base_url+'auth',",
"import matplotlib.pyplot as plt from matplotlib import rcParams import matplotlib.dates as mdates import",
"number, percent, date, and # of Q's answered data_quiz = [ (*test['title'].split('Module ')[1].split('Problem",
"rcParams['font.size'] = 14 fig, axs = plt.subplots(2, 2, figsize=(12, 8),sharey='row') fig.patch.set_facecolor('white') plt.subplots_adjust(hspace =",
"Student ID\"\"\" r = requests.post(base_url+'students', json={'token':token,'dId':55,'emailAddress':email}) return r.json()[0].get('sId') def get_completion_perc(sid,token): \"\"\"returns dataframe of",
"and creates dashboard locally\"\"\" studytimes = get_logins(sid,token) completion = get_completion_perc(sid,token) quiz_df = get_quiz_results(sid,token)",
"all student data and creates dashboard locally\"\"\" studytimes = get_logins(sid,token) completion = get_completion_perc(sid,token)",
"pd.DataFrame( # first 10 characters of 'first_accessed' gives the date [(x['first_accessed'][:10],x['duration']/3600) for x",
"matplotlib import rcParams import matplotlib.dates as mdates import pandas as pd import numpy",
"[0,20,40,60,80,100] plt.xticks(ticks_set,[str(val)+'%' for val in ticks_set]) plt.yticks(range(1,8)) # top right axis - circle",
"= requests.post(base_url+'students', json={'token':token,'dId':55,'emailAddress':email}) return r.json()[0].get('sId') def get_completion_perc(sid,token): \"\"\"returns dataframe of percent completion by",
"(*test['title'].split('Module ')[1].split('Problem Set '), result['final_score'], result['dateCompleted'], result['totalQuestions'] ) for test in r4.json() for",
"BT\" rcParams['font.family'] = \"sans-serif\" rcParams['font.size'] = 14 fig, axs = plt.subplots(2, 2, figsize=(12,",
"ago'].max()) ) cbar = plt.colorbar(sc) cbar.set_label(\"Days Since Quiz\") ax.set_yticks(np.arange(0.5,7.5,1), minor=True) plt.ylim(0.5,7.5) plt.gca().invert_yaxis() #",
"plots #top left axis - completion horiz bar chart ax = plt.subplot(2,2,1) colors",
"= '#003057' lblue = '#4986AD' green = '#509E2F' # change font rcParams['font.sans-serif'] =",
"of Q's answered data_quiz = [ (*test['title'].split('Module ')[1].split('Problem Set '), result['final_score'], result['dateCompleted'], result['totalQuestions']",
"print(e) print(\"Token not returned. Check password is correct\") def get_me_sid(email,token): \"\"\"get MindEdge Student",
"= studytimes.reindex(all_dates,fill_value=0) # WGU colors taken from https://www.wgu.edu/about/brand.html blue = '#003057' lblue =",
"the total possible pages indexed by module # counted manually in Sep 2020",
"result['dateCompleted'], result['totalQuestions'] ) for test in r4.json() for result in test['resultData'] ] quiz_df",
"session studytimes[studytimes>10] = 10 studytimes.index = pd.to_datetime(studytimes.index) return studytimes def mindedge_dashboard(sid,token,filename='dashboard.png'): \"\"\"input: studentID,",
"to ensure that at least one month is visible # so min of",
"least one month is visible # so min of date_rage is the lesser",
"characters of 'first_accessed' gives the date [(x['first_accessed'][:10],x['duration']/3600) for x in r5.json()] ) studytimes.columns",
"10 the maximum reported hours possible in one session studytimes[studytimes>10] = 10 studytimes.index",
"17, 8, 12, 16],index=idx) completion=100*pd.Series([int(p[0]) for p in pages])\\ .value_counts().reindex(idx,fill_value=0)/all_pages return completion def",
"ax = plt.subplot(2,1,2) plt.bar(studytimes_reidx.index, studytimes_reidx['duration']) ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d')) datemin = studytimes_reidx.index.min() datemax = datetime.datetime.today()",
"access / password if 'un' not in vars(): un = 'wgudb' pw =",
"8, 12, 16],index=idx) completion=100*pd.Series([int(p[0]) for p in pages])\\ .value_counts().reindex(idx,fill_value=0)/all_pages return completion def get_quiz_results(sid,token):",
"Resource (%)') ticks_set = [0,20,40,60,80,100] plt.xticks(ticks_set,[str(val)+'%' for val in ticks_set]) plt.yticks(range(1,8)) # top",
"maximum reported hours possible in one session studytimes[studytimes>10] = 10 studytimes.index = pd.to_datetime(studytimes.index)",
"= 55 def get_token(password): r = requests.post(base_url+'auth', json = {'username':un,'password':password}) try: return r.json()[0]['token']",
"= input(\"Enter Mindedge password:\") base_url = 'https://wguapps.mindedgeonline.com/services/api/' domain_id = 55 def get_token(password): r",
"requests, datetime, webbrowser ## This code will not run without MindEdge access /",
"Results') plt.yticks(range(1,8)) # bottom axis - study times vertical bar chart ax =",
"#top left axis - completion horiz bar chart ax = plt.subplot(2,2,1) colors =",
"the lesser of 1 mo ago and the min date month_ago = (datetime.datetime.now()+datetime.timedelta(days=-30)).date()",
"axis - completion horiz bar chart ax = plt.subplot(2,2,1) colors = [lblue]*7 for",
"not in title and 'Flashcards' not in title and 'Review' not in title",
"pd.date_range( min(month_ago, studytimes.index.min()), datetime.datetime.now() ) studytimes_reidx = studytimes.reindex(all_dates,fill_value=0) # WGU colors taken from",
"gives the total possible pages indexed by module # counted manually in Sep",
"quiz_df['Completed'] quiz_df['y_value'] = pd.to_numeric(quiz_df['Chapter']) return quiz_df def get_logins(sid,token): \"\"\"given studentID and active API",
"\"sans-serif\" rcParams['font.size'] = 14 fig, axs = plt.subplots(2, 2, figsize=(12, 8),sharey='row') fig.patch.set_facecolor('white') plt.subplots_adjust(hspace",
"output filename. Gathers all student data and creates dashboard locally\"\"\" studytimes = get_logins(sid,token)",
"columns=['Chapter','Problem Set','Percent','Date','Completed'] ) quiz_df['Percent'] = pd.to_numeric(quiz_df['Percent']) quiz_df['days ago'] = pd.to_datetime(quiz_df['Date'])\\ .apply(lambda x: (datetime.datetime.now()-x).days)",
"result['final_score'], result['dateCompleted'], result['totalQuestions'] ) for test in r4.json() for result in test['resultData'] ]",
"= get_completion_perc(sid,token) quiz_df = get_quiz_results(sid,token) # reindex studytimes to ensure that at least",
"s=700,alpha=0.8,c=quiz_df['days ago'],cmap=plt.cm.viridis_r, vmin=0,vmax=max(14,quiz_df['days ago'].max()) ) cbar = plt.colorbar(sc) cbar.set_label(\"Days Since Quiz\") ax.set_yticks(np.arange(0.5,7.5,1), minor=True)",
"get_token(password): r = requests.post(base_url+'auth', json = {'username':un,'password':password}) try: return r.json()[0]['token'] except Exception as",
"r.json()[0].get('sId') def get_completion_perc(sid,token): \"\"\"returns dataframe of percent completion by module\"\"\" r3 = requests.post(base_url+'studentCompleteAssignments',",
"that at least one month is visible # so min of date_rage is",
"at least one month is visible # so min of date_rage is the",
"10 characters of 'first_accessed' gives the date [(x['first_accessed'][:10],x['duration']/3600) for x in r5.json()] )",
"chart ax = plt.subplot(2,2,1) colors = [lblue]*7 for i in range(7): if completion.iloc[i]==100:",
"= get_quiz_results(sid,token) # reindex studytimes to ensure that at least one month is",
"json={'token':token,'dId':55,'emailAddress':email}) return r.json()[0].get('sId') def get_completion_perc(sid,token): \"\"\"returns dataframe of percent completion by module\"\"\" r3",
"colors[i]=blue plt.barh(completion.index,completion.values, height=1,color=colors,edgecolor='black') plt.ylim(0.5,7.5) plt.xlim(0,100) ax.invert_yaxis() ax.set_ylabel('Chapter') ax.set_title('Completion of Learning Resource (%)') ticks_set",
"(%)') ticks_set = [0,20,40,60,80,100] plt.xticks(ticks_set,[str(val)+'%' for val in ticks_set]) plt.yticks(range(1,8)) # top right",
"Ch.7 on bottom plt.xlim(0,105) ax.set_xticks(np.arange(0,105,10)) ax.tick_params(length=0) ax.yaxis.grid(True, which='minor') ax.set_ylabel('Chapter') ax.set_title('Quiz Results') plt.yticks(range(1,8)) #",
"= pd.date_range( min(month_ago, studytimes.index.min()), datetime.datetime.now() ) studytimes_reidx = studytimes.reindex(all_dates,fill_value=0) # WGU colors taken",
"requests.post(base_url+'studentTestData', json={'token':token,'dId':55,'cId':612,'sId':sid}) # parsing the text names of the quizzes to give: #",
"as e: print('status: ',r.status_code,':',r.reason) print(e) print(\"Token not returned. Check password is correct\") def",
"titles of pages read # select only pages with learning content: pages =",
"get_logins(sid,token) completion = get_completion_perc(sid,token) quiz_df = get_quiz_results(sid,token) # reindex studytimes to ensure that",
"Since Quiz\") ax.set_yticks(np.arange(0.5,7.5,1), minor=True) plt.ylim(0.5,7.5) plt.gca().invert_yaxis() # want Chapter 1 on top, Ch.7",
"learning content: pages = [title for title in read_pages if ( '.' in",
"matplotlib.dates as mdates import pandas as pd import numpy as np import requests,",
"study times vertical bar chart ax = plt.subplot(2,1,2) plt.bar(studytimes_reidx.index, studytimes_reidx['duration']) ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d')) datemin",
"reported hours possible in one session studytimes[studytimes>10] = 10 studytimes.index = pd.to_datetime(studytimes.index) return",
"will not run without MindEdge access / password if 'un' not in vars():",
"[ (*test['title'].split('Module ')[1].split('Problem Set '), result['final_score'], result['dateCompleted'], result['totalQuestions'] ) for test in r4.json()",
"module # counted manually in Sep 2020 all_pages = pd.Series([23, 22, 30, 17,",
"data_quiz = [ (*test['title'].split('Module ')[1].split('Problem Set '), result['final_score'], result['dateCompleted'], result['totalQuestions'] ) for test",
"quiz_df = pd.DataFrame( data_quiz, columns=['Chapter','Problem Set','Percent','Date','Completed'] ) quiz_df['Percent'] = pd.to_numeric(quiz_df['Percent']) quiz_df['days ago'] =",
"r4 = requests.post(base_url+'studentTestData', json={'token':token,'dId':55,'cId':612,'sId':sid}) # parsing the text names of the quizzes to",
"ID\"\"\" r = requests.post(base_url+'students', json={'token':token,'dId':55,'emailAddress':email}) return r.json()[0].get('sId') def get_completion_perc(sid,token): \"\"\"returns dataframe of percent",
"8),sharey='row') fig.patch.set_facecolor('white') plt.subplots_adjust(hspace = 0.3) #more horizontal space between plots #top left axis",
"hours spent in one session) # we make 10 the maximum reported hours",
"if ( '.' in title and 'Feedback' not in title and 'Flashcards' not",
"= {'username':un,'password':password}) try: return r.json()[0]['token'] except Exception as e: print('status: ',r.status_code,':',r.reason) print(e) print(\"Token",
"json={'token':token,'dId':55,'cId':612,'sId':sid}) read_pages = [t['title'] for t in r3.json()] # titles of pages read",
"= requests.post(base_url+'auth', json = {'username':un,'password':password}) try: return r.json()[0]['token'] except Exception as e: print('status:",
"plt.gca().invert_yaxis() # want Chapter 1 on top, Ch.7 on bottom plt.xlim(0,105) ax.set_xticks(np.arange(0,105,10)) ax.tick_params(length=0)",
"for i in range(7): if completion.iloc[i]==100: colors[i]=blue plt.barh(completion.index,completion.values, height=1,color=colors,edgecolor='black') plt.ylim(0.5,7.5) plt.xlim(0,100) ax.invert_yaxis() ax.set_ylabel('Chapter')",
") quiz_df['Percent'] = pd.to_numeric(quiz_df['Percent']) quiz_df['days ago'] = pd.to_datetime(quiz_df['Date'])\\ .apply(lambda x: (datetime.datetime.now()-x).days) quiz_df['# correct']",
"font rcParams['font.sans-serif'] = \"Futura Lt BT\" rcParams['font.family'] = \"sans-serif\" rcParams['font.size'] = 14 fig,",
"by module\"\"\" r3 = requests.post(base_url+'studentCompleteAssignments', json={'token':token,'dId':55,'cId':612,'sId':sid}) read_pages = [t['title'] for t in r3.json()]",
"plt.subplot(2,1,2) plt.bar(studytimes_reidx.index, studytimes_reidx['duration']) ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d')) datemin = studytimes_reidx.index.min() datemax = datetime.datetime.today() ax.set_xlim(datemin, datemax)",
"ax.set_xlim(datemin, datemax) ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval=1)) plt.xticks(rotation=45); ax.set_ylabel('hours studied'); ax.set_title('Hours engaged in Learning Resource'); plt.savefig(filename,dpi=300,bbox_inches='tight') #webbrowser.open(filename)",
"results ax = plt.subplot(2,2,2); sc = plt.scatter( quiz_df['Percent'].apply(lambda x: x+np.random.normal(0,0.1)), quiz_df['y_value'], s=700,alpha=0.8,c=quiz_df['days ago'],cmap=plt.cm.viridis_r,",
"# WGU colors taken from https://www.wgu.edu/about/brand.html blue = '#003057' lblue = '#4986AD' green",
"of Learning Resource (%)') ticks_set = [0,20,40,60,80,100] plt.xticks(ticks_set,[str(val)+'%' for val in ticks_set]) plt.yticks(range(1,8))",
"= pd.to_numeric(quiz_df['Chapter']) return quiz_df def get_logins(sid,token): \"\"\"given studentID and active API token, returns",
"json={'token':token,'dId':55,'cId':612,'sId':sid}) # parsing the text names of the quizzes to give: # the",
"] quiz_df = pd.DataFrame( data_quiz, columns=['Chapter','Problem Set','Percent','Date','Completed'] ) quiz_df['Percent'] = pd.to_numeric(quiz_df['Percent']) quiz_df['days ago']",
"This code will not run without MindEdge access / password if 'un' not",
"ax = plt.subplot(2,2,2); sc = plt.scatter( quiz_df['Percent'].apply(lambda x: x+np.random.normal(0,0.1)), quiz_df['y_value'], s=700,alpha=0.8,c=quiz_df['days ago'],cmap=plt.cm.viridis_r, vmin=0,vmax=max(14,quiz_df['days",
"e: print('status: ',r.status_code,':',r.reason) print(e) print(\"Token not returned. Check password is correct\") def get_me_sid(email,token):",
"plt.subplots(2, 2, figsize=(12, 8),sharey='row') fig.patch.set_facecolor('white') plt.subplots_adjust(hspace = 0.3) #more horizontal space between plots",
"[i for i in range(1,8)] # all_pages gives the total possible pages indexed",
"'https://wguapps.mindedgeonline.com/services/api/' domain_id = 55 def get_token(password): r = requests.post(base_url+'auth', json = {'username':un,'password':password}) try:",
"MindEdge Student ID\"\"\" r = requests.post(base_url+'students', json={'token':token,'dId':55,'emailAddress':email}) return r.json()[0].get('sId') def get_completion_perc(sid,token): \"\"\"returns dataframe",
"dashboard locally\"\"\" studytimes = get_logins(sid,token) completion = get_completion_perc(sid,token) quiz_df = get_quiz_results(sid,token) # reindex",
"',r.status_code,':',r.reason) print(e) print(\"Token not returned. Check password is correct\") def get_me_sid(email,token): \"\"\"get MindEdge",
"quizzes to give: # the ch number, quiz number, percent, date, and #",
"ax.set_yticks(np.arange(0.5,7.5,1), minor=True) plt.ylim(0.5,7.5) plt.gca().invert_yaxis() # want Chapter 1 on top, Ch.7 on bottom",
"= [ (*test['title'].split('Module ')[1].split('Problem Set '), result['final_score'], result['dateCompleted'], result['totalQuestions'] ) for test in",
"on top, Ch.7 on bottom plt.xlim(0,105) ax.set_xticks(np.arange(0,105,10)) ax.tick_params(length=0) ax.yaxis.grid(True, which='minor') ax.set_ylabel('Chapter') ax.set_title('Quiz Results')",
"studytimes_reidx.index.min() datemax = datetime.datetime.today() ax.set_xlim(datemin, datemax) ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval=1)) plt.xticks(rotation=45); ax.set_ylabel('hours studied'); ax.set_title('Hours engaged in",
"parsing the text names of the quizzes to give: # the ch number,",
"\"Futura Lt BT\" rcParams['font.family'] = \"sans-serif\" rcParams['font.size'] = 14 fig, axs = plt.subplots(2,",
"ax = plt.subplot(2,2,1) colors = [lblue]*7 for i in range(7): if completion.iloc[i]==100: colors[i]=blue",
"for result in test['resultData'] ] quiz_df = pd.DataFrame( data_quiz, columns=['Chapter','Problem Set','Percent','Date','Completed'] ) quiz_df['Percent']",
"ax.set_title('Quiz Results') plt.yticks(range(1,8)) # bottom axis - study times vertical bar chart ax",
"ticks_set]) plt.yticks(range(1,8)) # top right axis - circle plot for quiz results ax",
"x+np.random.normal(0,0.1)), quiz_df['y_value'], s=700,alpha=0.8,c=quiz_df['days ago'],cmap=plt.cm.viridis_r, vmin=0,vmax=max(14,quiz_df['days ago'].max()) ) cbar = plt.colorbar(sc) cbar.set_label(\"Days Since Quiz\")",
"plt.yticks(range(1,8)) # top right axis - circle plot for quiz results ax =",
"in r3.json()] # titles of pages read # select only pages with learning",
"= requests.post(base_url+'studentCompleteAssignments', json={'token':token,'dId':55,'cId':612,'sId':sid}) read_pages = [t['title'] for t in r3.json()] # titles of",
"300 hours spent in one session) # we make 10 the maximum reported",
"in title and 'Flashcards' not in title and 'Review' not in title and",
"one session) # we make 10 the maximum reported hours possible in one",
"not in title and 'Problem Set' not in title )] idx = [i",
"cbar = plt.colorbar(sc) cbar.set_label(\"Days Since Quiz\") ax.set_yticks(np.arange(0.5,7.5,1), minor=True) plt.ylim(0.5,7.5) plt.gca().invert_yaxis() # want Chapter",
"of date_rage is the lesser of 1 mo ago and the min date",
"for val in ticks_set]) plt.yticks(range(1,8)) # top right axis - circle plot for",
"ax.set_ylabel('Chapter') ax.set_title('Quiz Results') plt.yticks(range(1,8)) # bottom axis - study times vertical bar chart",
"= pd.DataFrame( # first 10 characters of 'first_accessed' gives the date [(x['first_accessed'][:10],x['duration']/3600) for",
"code will not run without MindEdge access / password if 'un' not in",
"in title and 'Problem Set' not in title )] idx = [i for",
"plt.scatter( quiz_df['Percent'].apply(lambda x: x+np.random.normal(0,0.1)), quiz_df['y_value'], s=700,alpha=0.8,c=quiz_df['days ago'],cmap=plt.cm.viridis_r, vmin=0,vmax=max(14,quiz_df['days ago'].max()) ) cbar = plt.colorbar(sc)",
"def get_me_sid(email,token): \"\"\"get MindEdge Student ID\"\"\" r = requests.post(base_url+'students', json={'token':token,'dId':55,'emailAddress':email}) return r.json()[0].get('sId') def",
"[lblue]*7 for i in range(7): if completion.iloc[i]==100: colors[i]=blue plt.barh(completion.index,completion.values, height=1,color=colors,edgecolor='black') plt.ylim(0.5,7.5) plt.xlim(0,100) ax.invert_yaxis()",
"ax.invert_yaxis() ax.set_ylabel('Chapter') ax.set_title('Completion of Learning Resource (%)') ticks_set = [0,20,40,60,80,100] plt.xticks(ticks_set,[str(val)+'%' for val",
"'Problem Set' not in title )] idx = [i for i in range(1,8)]",
"= plt.subplot(2,2,1) colors = [lblue]*7 for i in range(7): if completion.iloc[i]==100: colors[i]=blue plt.barh(completion.index,completion.values,",
"## This code will not run without MindEdge access / password if 'un'",
"module\"\"\" r3 = requests.post(base_url+'studentCompleteAssignments', json={'token':token,'dId':55,'cId':612,'sId':sid}) read_pages = [t['title'] for t in r3.json()] #",
"to give: # the ch number, quiz number, percent, date, and # of",
"ax.tick_params(length=0) ax.yaxis.grid(True, which='minor') ax.set_ylabel('Chapter') ax.set_title('Quiz Results') plt.yticks(range(1,8)) # bottom axis - study times",
"= [0,20,40,60,80,100] plt.xticks(ticks_set,[str(val)+'%' for val in ticks_set]) plt.yticks(range(1,8)) # top right axis -",
"pd.to_datetime(studytimes.index) return studytimes def mindedge_dashboard(sid,token,filename='dashboard.png'): \"\"\"input: studentID, active API token, and image output",
"domain_id = 55 def get_token(password): r = requests.post(base_url+'auth', json = {'username':un,'password':password}) try: return",
"image output filename. Gathers all student data and creates dashboard locally\"\"\" studytimes =",
"requests.post(base_url+'studentCompleteAssignments', json={'token':token,'dId':55,'cId':612,'sId':sid}) read_pages = [t['title'] for t in r3.json()] # titles of pages",
"min(month_ago, studytimes.index.min()), datetime.datetime.now() ) studytimes_reidx = studytimes.reindex(all_dates,fill_value=0) # WGU colors taken from https://www.wgu.edu/about/brand.html",
"= '#4986AD' green = '#509E2F' # change font rcParams['font.sans-serif'] = \"Futura Lt BT\"",
"pages indexed by module # counted manually in Sep 2020 all_pages = pd.Series([23,",
"so min of date_rage is the lesser of 1 mo ago and the",
"in read_pages if ( '.' in title and 'Feedback' not in title and",
"= plt.colorbar(sc) cbar.set_label(\"Days Since Quiz\") ax.set_yticks(np.arange(0.5,7.5,1), minor=True) plt.ylim(0.5,7.5) plt.gca().invert_yaxis() # want Chapter 1",
") cbar = plt.colorbar(sc) cbar.set_label(\"Days Since Quiz\") ax.set_yticks(np.arange(0.5,7.5,1), minor=True) plt.ylim(0.5,7.5) plt.gca().invert_yaxis() # want",
"plt.barh(completion.index,completion.values, height=1,color=colors,edgecolor='black') plt.ylim(0.5,7.5) plt.xlim(0,100) ax.invert_yaxis() ax.set_ylabel('Chapter') ax.set_title('Completion of Learning Resource (%)') ticks_set =",
"# counted manually in Sep 2020 all_pages = pd.Series([23, 22, 30, 17, 8,",
") for test in r4.json() for result in test['resultData'] ] quiz_df = pd.DataFrame(",
"completion def get_quiz_results(sid,token): r4 = requests.post(base_url+'studentTestData', json={'token':token,'dId':55,'cId':612,'sId':sid}) # parsing the text names of",
"Set' not in title )] idx = [i for i in range(1,8)] #",
"# all_pages gives the total possible pages indexed by module # counted manually",
"input(\"Enter Mindedge password:\") base_url = 'https://wguapps.mindedgeonline.com/services/api/' domain_id = 55 def get_token(password): r =",
"circle plot for quiz results ax = plt.subplot(2,2,2); sc = plt.scatter( quiz_df['Percent'].apply(lambda x:",
"16],index=idx) completion=100*pd.Series([int(p[0]) for p in pages])\\ .value_counts().reindex(idx,fill_value=0)/all_pages return completion def get_quiz_results(sid,token): r4 =",
"we make 10 the maximum reported hours possible in one session studytimes[studytimes>10] =",
"and 'Flashcards' not in title and 'Review' not in title and 'Problem Set'",
"title and 'Problem Set' not in title )] idx = [i for i",
"def get_token(password): r = requests.post(base_url+'auth', json = {'username':un,'password':password}) try: return r.json()[0]['token'] except Exception",
"in range(1,8)] # all_pages gives the total possible pages indexed by module #",
"in pages])\\ .value_counts().reindex(idx,fill_value=0)/all_pages return completion def get_quiz_results(sid,token): r4 = requests.post(base_url+'studentTestData', json={'token':token,'dId':55,'cId':612,'sId':sid}) # parsing",
"\"\"\"given studentID and active API token, returns dataframe of login dates and login",
"rcParams['font.sans-serif'] = \"Futura Lt BT\" rcParams['font.family'] = \"sans-serif\" rcParams['font.size'] = 14 fig, axs",
"month_ago = (datetime.datetime.now()+datetime.timedelta(days=-30)).date() all_dates = pd.date_range( min(month_ago, studytimes.index.min()), datetime.datetime.now() ) studytimes_reidx = studytimes.reindex(all_dates,fill_value=0)",
"one session studytimes[studytimes>10] = 10 studytimes.index = pd.to_datetime(studytimes.index) return studytimes def mindedge_dashboard(sid,token,filename='dashboard.png'): \"\"\"input:",
"top, Ch.7 on bottom plt.xlim(0,105) ax.set_xticks(np.arange(0,105,10)) ax.tick_params(length=0) ax.yaxis.grid(True, which='minor') ax.set_ylabel('Chapter') ax.set_title('Quiz Results') plt.yticks(range(1,8))",
"title and 'Flashcards' not in title and 'Review' not in title and 'Problem",
"plt.xticks(ticks_set,[str(val)+'%' for val in ticks_set]) plt.yticks(range(1,8)) # top right axis - circle plot",
"get_logins(sid,token): \"\"\"given studentID and active API token, returns dataframe of login dates and",
"not returned. Check password is correct\") def get_me_sid(email,token): \"\"\"get MindEdge Student ID\"\"\" r",
"r5 = requests.post(base_url+'studentLogins', json={'token':token,'dId':55,'cId':612,'sId':sid}) studytimes = pd.DataFrame( # first 10 characters of 'first_accessed'",
"one month is visible # so min of date_rage is the lesser of",
"plt from matplotlib import rcParams import matplotlib.dates as mdates import pandas as pd",
"counted manually in Sep 2020 all_pages = pd.Series([23, 22, 30, 17, 8, 12,",
"quiz number, percent, date, and # of Q's answered data_quiz = [ (*test['title'].split('Module",
"= \"Futura Lt BT\" rcParams['font.family'] = \"sans-serif\" rcParams['font.size'] = 14 fig, axs =",
"title in read_pages if ( '.' in title and 'Feedback' not in title",
"pages = [title for title in read_pages if ( '.' in title and",
"which='minor') ax.set_ylabel('Chapter') ax.set_title('Quiz Results') plt.yticks(range(1,8)) # bottom axis - study times vertical bar",
"all_pages gives the total possible pages indexed by module # counted manually in",
"space between plots #top left axis - completion horiz bar chart ax =",
"left axis - completion horiz bar chart ax = plt.subplot(2,2,1) colors = [lblue]*7",
"studytimes to ensure that at least one month is visible # so min",
"un = 'wgudb' pw = '' if pw=='': pw = input(\"Enter Mindedge password:\")",
"and the min date month_ago = (datetime.datetime.now()+datetime.timedelta(days=-30)).date() all_dates = pd.date_range( min(month_ago, studytimes.index.min()), datetime.datetime.now()",
"22, 30, 17, 8, 12, 16],index=idx) completion=100*pd.Series([int(p[0]) for p in pages])\\ .value_counts().reindex(idx,fill_value=0)/all_pages return",
"p in pages])\\ .value_counts().reindex(idx,fill_value=0)/all_pages return completion def get_quiz_results(sid,token): r4 = requests.post(base_url+'studentTestData', json={'token':token,'dId':55,'cId':612,'sId':sid}) #",
"and 'Feedback' not in title and 'Flashcards' not in title and 'Review' not",
"pandas as pd import numpy as np import requests, datetime, webbrowser ## This",
"from matplotlib import rcParams import matplotlib.dates as mdates import pandas as pd import",
"studytimes_reidx = studytimes.reindex(all_dates,fill_value=0) # WGU colors taken from https://www.wgu.edu/about/brand.html blue = '#003057' lblue",
"axs = plt.subplots(2, 2, figsize=(12, 8),sharey='row') fig.patch.set_facecolor('white') plt.subplots_adjust(hspace = 0.3) #more horizontal space",
"2020 all_pages = pd.Series([23, 22, 30, 17, 8, 12, 16],index=idx) completion=100*pd.Series([int(p[0]) for p",
"horizontal space between plots #top left axis - completion horiz bar chart ax",
"for x in r5.json()] ) studytimes.columns = ['date','duration'] studytimes = studytimes.groupby('date').sum() # to",
"studytimes = studytimes.groupby('date').sum() # to trim outliers/glitches (e.g. 300 hours spent in one",
"the quizzes to give: # the ch number, quiz number, percent, date, and",
"= 14 fig, axs = plt.subplots(2, 2, figsize=(12, 8),sharey='row') fig.patch.set_facecolor('white') plt.subplots_adjust(hspace = 0.3)",
"Learning Resource (%)') ticks_set = [0,20,40,60,80,100] plt.xticks(ticks_set,[str(val)+'%' for val in ticks_set]) plt.yticks(range(1,8)) #",
"test['resultData'] ] quiz_df = pd.DataFrame( data_quiz, columns=['Chapter','Problem Set','Percent','Date','Completed'] ) quiz_df['Percent'] = pd.to_numeric(quiz_df['Percent']) quiz_df['days",
"x in r5.json()] ) studytimes.columns = ['date','duration'] studytimes = studytimes.groupby('date').sum() # to trim",
"'.' in title and 'Feedback' not in title and 'Flashcards' not in title",
"all_pages = pd.Series([23, 22, 30, 17, 8, 12, 16],index=idx) completion=100*pd.Series([int(p[0]) for p in",
"and image output filename. Gathers all student data and creates dashboard locally\"\"\" studytimes",
"datemax = datetime.datetime.today() ax.set_xlim(datemin, datemax) ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval=1)) plt.xticks(rotation=45); ax.set_ylabel('hours studied'); ax.set_title('Hours engaged in Learning",
"'first_accessed' gives the date [(x['first_accessed'][:10],x['duration']/3600) for x in r5.json()] ) studytimes.columns = ['date','duration']",
"')[1].split('Problem Set '), result['final_score'], result['dateCompleted'], result['totalQuestions'] ) for test in r4.json() for result",
"def get_quiz_results(sid,token): r4 = requests.post(base_url+'studentTestData', json={'token':token,'dId':55,'cId':612,'sId':sid}) # parsing the text names of the",
"if pw=='': pw = input(\"Enter Mindedge password:\") base_url = 'https://wguapps.mindedgeonline.com/services/api/' domain_id = 55",
"in title and 'Feedback' not in title and 'Flashcards' not in title and",
"datemin = studytimes_reidx.index.min() datemax = datetime.datetime.today() ax.set_xlim(datemin, datemax) ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval=1)) plt.xticks(rotation=45); ax.set_ylabel('hours studied'); ax.set_title('Hours",
"# bottom axis - study times vertical bar chart ax = plt.subplot(2,1,2) plt.bar(studytimes_reidx.index,",
"= plt.subplots(2, 2, figsize=(12, 8),sharey='row') fig.patch.set_facecolor('white') plt.subplots_adjust(hspace = 0.3) #more horizontal space between",
"and # of Q's answered data_quiz = [ (*test['title'].split('Module ')[1].split('Problem Set '), result['final_score'],",
"ch number, quiz number, percent, date, and # of Q's answered data_quiz =",
"as np import requests, datetime, webbrowser ## This code will not run without",
"plt.ylim(0.5,7.5) plt.gca().invert_yaxis() # want Chapter 1 on top, Ch.7 on bottom plt.xlim(0,105) ax.set_xticks(np.arange(0,105,10))",
"password if 'un' not in vars(): un = 'wgudb' pw = '' if",
"webbrowser ## This code will not run without MindEdge access / password if",
"not run without MindEdge access / password if 'un' not in vars(): un",
"'un' not in vars(): un = 'wgudb' pw = '' if pw=='': pw",
"\"\"\"input: studentID, active API token, and image output filename. Gathers all student data",
"matplotlib.pyplot as plt from matplotlib import rcParams import matplotlib.dates as mdates import pandas",
"outliers/glitches (e.g. 300 hours spent in one session) # we make 10 the",
"for i in range(1,8)] # all_pages gives the total possible pages indexed by",
"import rcParams import matplotlib.dates as mdates import pandas as pd import numpy as",
"[title for title in read_pages if ( '.' in title and 'Feedback' not",
"studytimes.columns = ['date','duration'] studytimes = studytimes.groupby('date').sum() # to trim outliers/glitches (e.g. 300 hours",
"= get_logins(sid,token) completion = get_completion_perc(sid,token) quiz_df = get_quiz_results(sid,token) # reindex studytimes to ensure",
"answered data_quiz = [ (*test['title'].split('Module ')[1].split('Problem Set '), result['final_score'], result['dateCompleted'], result['totalQuestions'] ) for",
"# so min of date_rage is the lesser of 1 mo ago and",
"blue = '#003057' lblue = '#4986AD' green = '#509E2F' # change font rcParams['font.sans-serif']",
"active API token, returns dataframe of login dates and login duration\"\"\" r5 =",
"of pages read # select only pages with learning content: pages = [title",
"login duration\"\"\" r5 = requests.post(base_url+'studentLogins', json={'token':token,'dId':55,'cId':612,'sId':sid}) studytimes = pd.DataFrame( # first 10 characters",
"session) # we make 10 the maximum reported hours possible in one session",
"in range(7): if completion.iloc[i]==100: colors[i]=blue plt.barh(completion.index,completion.values, height=1,color=colors,edgecolor='black') plt.ylim(0.5,7.5) plt.xlim(0,100) ax.invert_yaxis() ax.set_ylabel('Chapter') ax.set_title('Completion of",
"title )] idx = [i for i in range(1,8)] # all_pages gives the",
"password:\") base_url = 'https://wguapps.mindedgeonline.com/services/api/' domain_id = 55 def get_token(password): r = requests.post(base_url+'auth', json",
"studytimes.groupby('date').sum() # to trim outliers/glitches (e.g. 300 hours spent in one session) #",
"all_dates = pd.date_range( min(month_ago, studytimes.index.min()), datetime.datetime.now() ) studytimes_reidx = studytimes.reindex(all_dates,fill_value=0) # WGU colors",
"possible pages indexed by module # counted manually in Sep 2020 all_pages =",
"14 fig, axs = plt.subplots(2, 2, figsize=(12, 8),sharey='row') fig.patch.set_facecolor('white') plt.subplots_adjust(hspace = 0.3) #more",
"- completion horiz bar chart ax = plt.subplot(2,2,1) colors = [lblue]*7 for i",
"colors = [lblue]*7 for i in range(7): if completion.iloc[i]==100: colors[i]=blue plt.barh(completion.index,completion.values, height=1,color=colors,edgecolor='black') plt.ylim(0.5,7.5)",
"import numpy as np import requests, datetime, webbrowser ## This code will not",
"= studytimes.groupby('date').sum() # to trim outliers/glitches (e.g. 300 hours spent in one session)",
"r3 = requests.post(base_url+'studentCompleteAssignments', json={'token':token,'dId':55,'cId':612,'sId':sid}) read_pages = [t['title'] for t in r3.json()] # titles",
"/ password if 'un' not in vars(): un = 'wgudb' pw = ''",
"studytimes.index = pd.to_datetime(studytimes.index) return studytimes def mindedge_dashboard(sid,token,filename='dashboard.png'): \"\"\"input: studentID, active API token, and",
"json={'token':token,'dId':55,'cId':612,'sId':sid}) studytimes = pd.DataFrame( # first 10 characters of 'first_accessed' gives the date",
"Chapter 1 on top, Ch.7 on bottom plt.xlim(0,105) ax.set_xticks(np.arange(0,105,10)) ax.tick_params(length=0) ax.yaxis.grid(True, which='minor') ax.set_ylabel('Chapter')",
"plt.ylim(0.5,7.5) plt.xlim(0,100) ax.invert_yaxis() ax.set_ylabel('Chapter') ax.set_title('Completion of Learning Resource (%)') ticks_set = [0,20,40,60,80,100] plt.xticks(ticks_set,[str(val)+'%'",
"possible in one session studytimes[studytimes>10] = 10 studytimes.index = pd.to_datetime(studytimes.index) return studytimes def",
"# want Chapter 1 on top, Ch.7 on bottom plt.xlim(0,105) ax.set_xticks(np.arange(0,105,10)) ax.tick_params(length=0) ax.yaxis.grid(True,",
"# the ch number, quiz number, percent, date, and # of Q's answered",
"55 def get_token(password): r = requests.post(base_url+'auth', json = {'username':un,'password':password}) try: return r.json()[0]['token'] except",
"import matplotlib.dates as mdates import pandas as pd import numpy as np import",
"dataframe of percent completion by module\"\"\" r3 = requests.post(base_url+'studentCompleteAssignments', json={'token':token,'dId':55,'cId':612,'sId':sid}) read_pages = [t['title']",
"= [lblue]*7 for i in range(7): if completion.iloc[i]==100: colors[i]=blue plt.barh(completion.index,completion.values, height=1,color=colors,edgecolor='black') plt.ylim(0.5,7.5) plt.xlim(0,100)",
"is the lesser of 1 mo ago and the min date month_ago =",
"{'username':un,'password':password}) try: return r.json()[0]['token'] except Exception as e: print('status: ',r.status_code,':',r.reason) print(e) print(\"Token not",
"= pd.to_datetime(studytimes.index) return studytimes def mindedge_dashboard(sid,token,filename='dashboard.png'): \"\"\"input: studentID, active API token, and image",
"the ch number, quiz number, percent, date, and # of Q's answered data_quiz",
"dates and login duration\"\"\" r5 = requests.post(base_url+'studentLogins', json={'token':token,'dId':55,'cId':612,'sId':sid}) studytimes = pd.DataFrame( # first",
"= 0.3) #more horizontal space between plots #top left axis - completion horiz",
"1 mo ago and the min date month_ago = (datetime.datetime.now()+datetime.timedelta(days=-30)).date() all_dates = pd.date_range(",
"ax.yaxis.grid(True, which='minor') ax.set_ylabel('Chapter') ax.set_title('Quiz Results') plt.yticks(range(1,8)) # bottom axis - study times vertical",
"r3.json()] # titles of pages read # select only pages with learning content:",
"in one session) # we make 10 the maximum reported hours possible in",
"content: pages = [title for title in read_pages if ( '.' in title",
"pw=='': pw = input(\"Enter Mindedge password:\") base_url = 'https://wguapps.mindedgeonline.com/services/api/' domain_id = 55 def",
"from https://www.wgu.edu/about/brand.html blue = '#003057' lblue = '#4986AD' green = '#509E2F' # change",
"pd.to_numeric(quiz_df['Chapter']) return quiz_df def get_logins(sid,token): \"\"\"given studentID and active API token, returns dataframe",
"plt.subplot(2,2,1) colors = [lblue]*7 for i in range(7): if completion.iloc[i]==100: colors[i]=blue plt.barh(completion.index,completion.values, height=1,color=colors,edgecolor='black')",
"= 'https://wguapps.mindedgeonline.com/services/api/' domain_id = 55 def get_token(password): r = requests.post(base_url+'auth', json = {'username':un,'password':password})",
"bar chart ax = plt.subplot(2,2,1) colors = [lblue]*7 for i in range(7): if",
"the maximum reported hours possible in one session studytimes[studytimes>10] = 10 studytimes.index =",
"x: x+np.random.normal(0,0.1)), quiz_df['y_value'], s=700,alpha=0.8,c=quiz_df['days ago'],cmap=plt.cm.viridis_r, vmin=0,vmax=max(14,quiz_df['days ago'].max()) ) cbar = plt.colorbar(sc) cbar.set_label(\"Days Since",
"hours possible in one session studytimes[studytimes>10] = 10 studytimes.index = pd.to_datetime(studytimes.index) return studytimes",
"studytimes[studytimes>10] = 10 studytimes.index = pd.to_datetime(studytimes.index) return studytimes def mindedge_dashboard(sid,token,filename='dashboard.png'): \"\"\"input: studentID, active",
"'wgudb' pw = '' if pw=='': pw = input(\"Enter Mindedge password:\") base_url =",
"plt.yticks(range(1,8)) # bottom axis - study times vertical bar chart ax = plt.subplot(2,1,2)",
"= '' if pw=='': pw = input(\"Enter Mindedge password:\") base_url = 'https://wguapps.mindedgeonline.com/services/api/' domain_id",
"Gathers all student data and creates dashboard locally\"\"\" studytimes = get_logins(sid,token) completion =",
"return r.json()[0].get('sId') def get_completion_perc(sid,token): \"\"\"returns dataframe of percent completion by module\"\"\" r3 =",
"indexed by module # counted manually in Sep 2020 all_pages = pd.Series([23, 22,",
"ago and the min date month_ago = (datetime.datetime.now()+datetime.timedelta(days=-30)).date() all_dates = pd.date_range( min(month_ago, studytimes.index.min()),",
"requests.post(base_url+'students', json={'token':token,'dId':55,'emailAddress':email}) return r.json()[0].get('sId') def get_completion_perc(sid,token): \"\"\"returns dataframe of percent completion by module\"\"\"",
"run without MindEdge access / password if 'un' not in vars(): un =",
"r = requests.post(base_url+'auth', json = {'username':un,'password':password}) try: return r.json()[0]['token'] except Exception as e:",
"val in ticks_set]) plt.yticks(range(1,8)) # top right axis - circle plot for quiz",
"(datetime.datetime.now()-x).days) quiz_df['# correct'] = quiz_df['Percent']/100 * quiz_df['Completed'] quiz_df['y_value'] = pd.to_numeric(quiz_df['Chapter']) return quiz_df def",
"creates dashboard locally\"\"\" studytimes = get_logins(sid,token) completion = get_completion_perc(sid,token) quiz_df = get_quiz_results(sid,token) #",
"# titles of pages read # select only pages with learning content: pages",
"for title in read_pages if ( '.' in title and 'Feedback' not in",
"result in test['resultData'] ] quiz_df = pd.DataFrame( data_quiz, columns=['Chapter','Problem Set','Percent','Date','Completed'] ) quiz_df['Percent'] =",
".apply(lambda x: (datetime.datetime.now()-x).days) quiz_df['# correct'] = quiz_df['Percent']/100 * quiz_df['Completed'] quiz_df['y_value'] = pd.to_numeric(quiz_df['Chapter']) return",
"# top right axis - circle plot for quiz results ax = plt.subplot(2,2,2);",
"pw = input(\"Enter Mindedge password:\") base_url = 'https://wguapps.mindedgeonline.com/services/api/' domain_id = 55 def get_token(password):",
"in one session studytimes[studytimes>10] = 10 studytimes.index = pd.to_datetime(studytimes.index) return studytimes def mindedge_dashboard(sid,token,filename='dashboard.png'):",
"for p in pages])\\ .value_counts().reindex(idx,fill_value=0)/all_pages return completion def get_quiz_results(sid,token): r4 = requests.post(base_url+'studentTestData', json={'token':token,'dId':55,'cId':612,'sId':sid})",
"= requests.post(base_url+'studentLogins', json={'token':token,'dId':55,'cId':612,'sId':sid}) studytimes = pd.DataFrame( # first 10 characters of 'first_accessed' gives",
"login dates and login duration\"\"\" r5 = requests.post(base_url+'studentLogins', json={'token':token,'dId':55,'cId':612,'sId':sid}) studytimes = pd.DataFrame( #",
"password is correct\") def get_me_sid(email,token): \"\"\"get MindEdge Student ID\"\"\" r = requests.post(base_url+'students', json={'token':token,'dId':55,'emailAddress':email})",
"not in title )] idx = [i for i in range(1,8)] # all_pages",
"by module # counted manually in Sep 2020 all_pages = pd.Series([23, 22, 30,",
"quiz_df['Percent'].apply(lambda x: x+np.random.normal(0,0.1)), quiz_df['y_value'], s=700,alpha=0.8,c=quiz_df['days ago'],cmap=plt.cm.viridis_r, vmin=0,vmax=max(14,quiz_df['days ago'].max()) ) cbar = plt.colorbar(sc) cbar.set_label(\"Days",
"on bottom plt.xlim(0,105) ax.set_xticks(np.arange(0,105,10)) ax.tick_params(length=0) ax.yaxis.grid(True, which='minor') ax.set_ylabel('Chapter') ax.set_title('Quiz Results') plt.yticks(range(1,8)) # bottom",
"lblue = '#4986AD' green = '#509E2F' # change font rcParams['font.sans-serif'] = \"Futura Lt",
"data and creates dashboard locally\"\"\" studytimes = get_logins(sid,token) completion = get_completion_perc(sid,token) quiz_df =",
"completion=100*pd.Series([int(p[0]) for p in pages])\\ .value_counts().reindex(idx,fill_value=0)/all_pages return completion def get_quiz_results(sid,token): r4 = requests.post(base_url+'studentTestData',",
"= '#509E2F' # change font rcParams['font.sans-serif'] = \"Futura Lt BT\" rcParams['font.family'] = \"sans-serif\"",
"ticks_set = [0,20,40,60,80,100] plt.xticks(ticks_set,[str(val)+'%' for val in ticks_set]) plt.yticks(range(1,8)) # top right axis",
"return r.json()[0]['token'] except Exception as e: print('status: ',r.status_code,':',r.reason) print(e) print(\"Token not returned. Check",
"times vertical bar chart ax = plt.subplot(2,1,2) plt.bar(studytimes_reidx.index, studytimes_reidx['duration']) ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d')) datemin =",
"import pandas as pd import numpy as np import requests, datetime, webbrowser ##",
"completion horiz bar chart ax = plt.subplot(2,2,1) colors = [lblue]*7 for i in",
"studytimes.index.min()), datetime.datetime.now() ) studytimes_reidx = studytimes.reindex(all_dates,fill_value=0) # WGU colors taken from https://www.wgu.edu/about/brand.html blue",
"[t['title'] for t in r3.json()] # titles of pages read # select only",
"import requests, datetime, webbrowser ## This code will not run without MindEdge access",
"'#003057' lblue = '#4986AD' green = '#509E2F' # change font rcParams['font.sans-serif'] = \"Futura",
"'#4986AD' green = '#509E2F' # change font rcParams['font.sans-serif'] = \"Futura Lt BT\" rcParams['font.family']",
"mo ago and the min date month_ago = (datetime.datetime.now()+datetime.timedelta(days=-30)).date() all_dates = pd.date_range( min(month_ago,",
"= 10 studytimes.index = pd.to_datetime(studytimes.index) return studytimes def mindedge_dashboard(sid,token,filename='dashboard.png'): \"\"\"input: studentID, active API",
"'' if pw=='': pw = input(\"Enter Mindedge password:\") base_url = 'https://wguapps.mindedgeonline.com/services/api/' domain_id =",
"= ['date','duration'] studytimes = studytimes.groupby('date').sum() # to trim outliers/glitches (e.g. 300 hours spent",
"right axis - circle plot for quiz results ax = plt.subplot(2,2,2); sc =",
"manually in Sep 2020 all_pages = pd.Series([23, 22, 30, 17, 8, 12, 16],index=idx)",
"the text names of the quizzes to give: # the ch number, quiz",
"datetime.datetime.today() ax.set_xlim(datemin, datemax) ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval=1)) plt.xticks(rotation=45); ax.set_ylabel('hours studied'); ax.set_title('Hours engaged in Learning Resource'); plt.savefig(filename,dpi=300,bbox_inches='tight')",
"in vars(): un = 'wgudb' pw = '' if pw=='': pw = input(\"Enter",
"for test in r4.json() for result in test['resultData'] ] quiz_df = pd.DataFrame( data_quiz,",
"min of date_rage is the lesser of 1 mo ago and the min",
"= pd.to_datetime(quiz_df['Date'])\\ .apply(lambda x: (datetime.datetime.now()-x).days) quiz_df['# correct'] = quiz_df['Percent']/100 * quiz_df['Completed'] quiz_df['y_value'] =",
"range(1,8)] # all_pages gives the total possible pages indexed by module # counted",
"month is visible # so min of date_rage is the lesser of 1",
"select only pages with learning content: pages = [title for title in read_pages",
"bar chart ax = plt.subplot(2,1,2) plt.bar(studytimes_reidx.index, studytimes_reidx['duration']) ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d')) datemin = studytimes_reidx.index.min() datemax",
"dataframe of login dates and login duration\"\"\" r5 = requests.post(base_url+'studentLogins', json={'token':token,'dId':55,'cId':612,'sId':sid}) studytimes =",
"for t in r3.json()] # titles of pages read # select only pages",
"datetime, webbrowser ## This code will not run without MindEdge access / password",
"sc = plt.scatter( quiz_df['Percent'].apply(lambda x: x+np.random.normal(0,0.1)), quiz_df['y_value'], s=700,alpha=0.8,c=quiz_df['days ago'],cmap=plt.cm.viridis_r, vmin=0,vmax=max(14,quiz_df['days ago'].max()) ) cbar",
"range(7): if completion.iloc[i]==100: colors[i]=blue plt.barh(completion.index,completion.values, height=1,color=colors,edgecolor='black') plt.ylim(0.5,7.5) plt.xlim(0,100) ax.invert_yaxis() ax.set_ylabel('Chapter') ax.set_title('Completion of Learning",
"= studytimes_reidx.index.min() datemax = datetime.datetime.today() ax.set_xlim(datemin, datemax) ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval=1)) plt.xticks(rotation=45); ax.set_ylabel('hours studied'); ax.set_title('Hours engaged",
"is correct\") def get_me_sid(email,token): \"\"\"get MindEdge Student ID\"\"\" r = requests.post(base_url+'students', json={'token':token,'dId':55,'emailAddress':email}) return",
"studytimes.reindex(all_dates,fill_value=0) # WGU colors taken from https://www.wgu.edu/about/brand.html blue = '#003057' lblue = '#4986AD'",
"in title )] idx = [i for i in range(1,8)] # all_pages gives",
"pw = '' if pw=='': pw = input(\"Enter Mindedge password:\") base_url = 'https://wguapps.mindedgeonline.com/services/api/'",
"in ticks_set]) plt.yticks(range(1,8)) # top right axis - circle plot for quiz results",
"'Feedback' not in title and 'Flashcards' not in title and 'Review' not in",
"'Review' not in title and 'Problem Set' not in title )] idx =",
"completion.iloc[i]==100: colors[i]=blue plt.barh(completion.index,completion.values, height=1,color=colors,edgecolor='black') plt.ylim(0.5,7.5) plt.xlim(0,100) ax.invert_yaxis() ax.set_ylabel('Chapter') ax.set_title('Completion of Learning Resource (%)')",
"# of Q's answered data_quiz = [ (*test['title'].split('Module ')[1].split('Problem Set '), result['final_score'], result['dateCompleted'],",
"* quiz_df['Completed'] quiz_df['y_value'] = pd.to_numeric(quiz_df['Chapter']) return quiz_df def get_logins(sid,token): \"\"\"given studentID and active",
"filename. Gathers all student data and creates dashboard locally\"\"\" studytimes = get_logins(sid,token) completion",
"vmin=0,vmax=max(14,quiz_df['days ago'].max()) ) cbar = plt.colorbar(sc) cbar.set_label(\"Days Since Quiz\") ax.set_yticks(np.arange(0.5,7.5,1), minor=True) plt.ylim(0.5,7.5) plt.gca().invert_yaxis()",
"returns dataframe of login dates and login duration\"\"\" r5 = requests.post(base_url+'studentLogins', json={'token':token,'dId':55,'cId':612,'sId':sid}) studytimes",
"quiz_df['# correct'] = quiz_df['Percent']/100 * quiz_df['Completed'] quiz_df['y_value'] = pd.to_numeric(quiz_df['Chapter']) return quiz_df def get_logins(sid,token):",
"read # select only pages with learning content: pages = [title for title",
"plt.subplots_adjust(hspace = 0.3) #more horizontal space between plots #top left axis - completion",
"r.json()[0]['token'] except Exception as e: print('status: ',r.status_code,':',r.reason) print(e) print(\"Token not returned. Check password",
"r5.json()] ) studytimes.columns = ['date','duration'] studytimes = studytimes.groupby('date').sum() # to trim outliers/glitches (e.g.",
"with learning content: pages = [title for title in read_pages if ( '.'",
"studytimes def mindedge_dashboard(sid,token,filename='dashboard.png'): \"\"\"input: studentID, active API token, and image output filename. Gathers",
"= plt.scatter( quiz_df['Percent'].apply(lambda x: x+np.random.normal(0,0.1)), quiz_df['y_value'], s=700,alpha=0.8,c=quiz_df['days ago'],cmap=plt.cm.viridis_r, vmin=0,vmax=max(14,quiz_df['days ago'].max()) ) cbar =",
"= plt.subplot(2,1,2) plt.bar(studytimes_reidx.index, studytimes_reidx['duration']) ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d')) datemin = studytimes_reidx.index.min() datemax = datetime.datetime.today() ax.set_xlim(datemin,",
"= plt.subplot(2,2,2); sc = plt.scatter( quiz_df['Percent'].apply(lambda x: x+np.random.normal(0,0.1)), quiz_df['y_value'], s=700,alpha=0.8,c=quiz_df['days ago'],cmap=plt.cm.viridis_r, vmin=0,vmax=max(14,quiz_df['days ago'].max())",
"Lt BT\" rcParams['font.family'] = \"sans-serif\" rcParams['font.size'] = 14 fig, axs = plt.subplots(2, 2,",
"height=1,color=colors,edgecolor='black') plt.ylim(0.5,7.5) plt.xlim(0,100) ax.invert_yaxis() ax.set_ylabel('Chapter') ax.set_title('Completion of Learning Resource (%)') ticks_set = [0,20,40,60,80,100]",
"(e.g. 300 hours spent in one session) # we make 10 the maximum",
"not in title and 'Review' not in title and 'Problem Set' not in",
"fig, axs = plt.subplots(2, 2, figsize=(12, 8),sharey='row') fig.patch.set_facecolor('white') plt.subplots_adjust(hspace = 0.3) #more horizontal",
"date_rage is the lesser of 1 mo ago and the min date month_ago",
"lesser of 1 mo ago and the min date month_ago = (datetime.datetime.now()+datetime.timedelta(days=-30)).date() all_dates",
"if completion.iloc[i]==100: colors[i]=blue plt.barh(completion.index,completion.values, height=1,color=colors,edgecolor='black') plt.ylim(0.5,7.5) plt.xlim(0,100) ax.invert_yaxis() ax.set_ylabel('Chapter') ax.set_title('Completion of Learning Resource",
"bottom axis - study times vertical bar chart ax = plt.subplot(2,1,2) plt.bar(studytimes_reidx.index, studytimes_reidx['duration'])",
"30, 17, 8, 12, 16],index=idx) completion=100*pd.Series([int(p[0]) for p in pages])\\ .value_counts().reindex(idx,fill_value=0)/all_pages return completion",
"ensure that at least one month is visible # so min of date_rage",
"the date [(x['first_accessed'][:10],x['duration']/3600) for x in r5.json()] ) studytimes.columns = ['date','duration'] studytimes =",
"vars(): un = 'wgudb' pw = '' if pw=='': pw = input(\"Enter Mindedge",
"plt.xlim(0,100) ax.invert_yaxis() ax.set_ylabel('Chapter') ax.set_title('Completion of Learning Resource (%)') ticks_set = [0,20,40,60,80,100] plt.xticks(ticks_set,[str(val)+'%' for",
"of the quizzes to give: # the ch number, quiz number, percent, date,",
"studentID, active API token, and image output filename. Gathers all student data and",
"mdates import pandas as pd import numpy as np import requests, datetime, webbrowser",
"= datetime.datetime.today() ax.set_xlim(datemin, datemax) ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval=1)) plt.xticks(rotation=45); ax.set_ylabel('hours studied'); ax.set_title('Hours engaged in Learning Resource');",
"studentID and active API token, returns dataframe of login dates and login duration\"\"\"",
".value_counts().reindex(idx,fill_value=0)/all_pages return completion def get_quiz_results(sid,token): r4 = requests.post(base_url+'studentTestData', json={'token':token,'dId':55,'cId':612,'sId':sid}) # parsing the text",
"ax.set_ylabel('Chapter') ax.set_title('Completion of Learning Resource (%)') ticks_set = [0,20,40,60,80,100] plt.xticks(ticks_set,[str(val)+'%' for val in",
"rcParams import matplotlib.dates as mdates import pandas as pd import numpy as np",
"total possible pages indexed by module # counted manually in Sep 2020 all_pages",
"colors taken from https://www.wgu.edu/about/brand.html blue = '#003057' lblue = '#4986AD' green = '#509E2F'",
"horiz bar chart ax = plt.subplot(2,2,1) colors = [lblue]*7 for i in range(7):",
"vertical bar chart ax = plt.subplot(2,1,2) plt.bar(studytimes_reidx.index, studytimes_reidx['duration']) ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d')) datemin = studytimes_reidx.index.min()",
"correct\") def get_me_sid(email,token): \"\"\"get MindEdge Student ID\"\"\" r = requests.post(base_url+'students', json={'token':token,'dId':55,'emailAddress':email}) return r.json()[0].get('sId')",
"as mdates import pandas as pd import numpy as np import requests, datetime,",
"WGU colors taken from https://www.wgu.edu/about/brand.html blue = '#003057' lblue = '#4986AD' green =",
"# first 10 characters of 'first_accessed' gives the date [(x['first_accessed'][:10],x['duration']/3600) for x in",
"r4.json() for result in test['resultData'] ] quiz_df = pd.DataFrame( data_quiz, columns=['Chapter','Problem Set','Percent','Date','Completed'] )",
"in r5.json()] ) studytimes.columns = ['date','duration'] studytimes = studytimes.groupby('date').sum() # to trim outliers/glitches",
"cbar.set_label(\"Days Since Quiz\") ax.set_yticks(np.arange(0.5,7.5,1), minor=True) plt.ylim(0.5,7.5) plt.gca().invert_yaxis() # want Chapter 1 on top,",
"# change font rcParams['font.sans-serif'] = \"Futura Lt BT\" rcParams['font.family'] = \"sans-serif\" rcParams['font.size'] =",
"- circle plot for quiz results ax = plt.subplot(2,2,2); sc = plt.scatter( quiz_df['Percent'].apply(lambda",
"if 'un' not in vars(): un = 'wgudb' pw = '' if pw=='':",
"quiz results ax = plt.subplot(2,2,2); sc = plt.scatter( quiz_df['Percent'].apply(lambda x: x+np.random.normal(0,0.1)), quiz_df['y_value'], s=700,alpha=0.8,c=quiz_df['days",
"def get_completion_perc(sid,token): \"\"\"returns dataframe of percent completion by module\"\"\" r3 = requests.post(base_url+'studentCompleteAssignments', json={'token':token,'dId':55,'cId':612,'sId':sid})",
") studytimes_reidx = studytimes.reindex(all_dates,fill_value=0) # WGU colors taken from https://www.wgu.edu/about/brand.html blue = '#003057'",
"plt.xlim(0,105) ax.set_xticks(np.arange(0,105,10)) ax.tick_params(length=0) ax.yaxis.grid(True, which='minor') ax.set_ylabel('Chapter') ax.set_title('Quiz Results') plt.yticks(range(1,8)) # bottom axis -",
"= (datetime.datetime.now()+datetime.timedelta(days=-30)).date() all_dates = pd.date_range( min(month_ago, studytimes.index.min()), datetime.datetime.now() ) studytimes_reidx = studytimes.reindex(all_dates,fill_value=0) #",
"the min date month_ago = (datetime.datetime.now()+datetime.timedelta(days=-30)).date() all_dates = pd.date_range( min(month_ago, studytimes.index.min()), datetime.datetime.now() )",
"correct'] = quiz_df['Percent']/100 * quiz_df['Completed'] quiz_df['y_value'] = pd.to_numeric(quiz_df['Chapter']) return quiz_df def get_logins(sid,token): \"\"\"given",
"= \"sans-serif\" rcParams['font.size'] = 14 fig, axs = plt.subplots(2, 2, figsize=(12, 8),sharey='row') fig.patch.set_facecolor('white')",
"plt.bar(studytimes_reidx.index, studytimes_reidx['duration']) ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d')) datemin = studytimes_reidx.index.min() datemax = datetime.datetime.today() ax.set_xlim(datemin, datemax) ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval=1))",
"json = {'username':un,'password':password}) try: return r.json()[0]['token'] except Exception as e: print('status: ',r.status_code,':',r.reason) print(e)",
"requests.post(base_url+'studentLogins', json={'token':token,'dId':55,'cId':612,'sId':sid}) studytimes = pd.DataFrame( # first 10 characters of 'first_accessed' gives the",
"taken from https://www.wgu.edu/about/brand.html blue = '#003057' lblue = '#4986AD' green = '#509E2F' #",
"Set','Percent','Date','Completed'] ) quiz_df['Percent'] = pd.to_numeric(quiz_df['Percent']) quiz_df['days ago'] = pd.to_datetime(quiz_df['Date'])\\ .apply(lambda x: (datetime.datetime.now()-x).days) quiz_df['#",
"= quiz_df['Percent']/100 * quiz_df['Completed'] quiz_df['y_value'] = pd.to_numeric(quiz_df['Chapter']) return quiz_df def get_logins(sid,token): \"\"\"given studentID",
"for quiz results ax = plt.subplot(2,2,2); sc = plt.scatter( quiz_df['Percent'].apply(lambda x: x+np.random.normal(0,0.1)), quiz_df['y_value'],",
"in Sep 2020 all_pages = pd.Series([23, 22, 30, 17, 8, 12, 16],index=idx) completion=100*pd.Series([int(p[0])",
"and login duration\"\"\" r5 = requests.post(base_url+'studentLogins', json={'token':token,'dId':55,'cId':612,'sId':sid}) studytimes = pd.DataFrame( # first 10",
"10 studytimes.index = pd.to_datetime(studytimes.index) return studytimes def mindedge_dashboard(sid,token,filename='dashboard.png'): \"\"\"input: studentID, active API token,",
"pd.DataFrame( data_quiz, columns=['Chapter','Problem Set','Percent','Date','Completed'] ) quiz_df['Percent'] = pd.to_numeric(quiz_df['Percent']) quiz_df['days ago'] = pd.to_datetime(quiz_df['Date'])\\ .apply(lambda",
"'#509E2F' # change font rcParams['font.sans-serif'] = \"Futura Lt BT\" rcParams['font.family'] = \"sans-serif\" rcParams['font.size']",
"print('status: ',r.status_code,':',r.reason) print(e) print(\"Token not returned. Check password is correct\") def get_me_sid(email,token): \"\"\"get",
"active API token, and image output filename. Gathers all student data and creates",
"names of the quizzes to give: # the ch number, quiz number, percent,",
"pd.Series([23, 22, 30, 17, 8, 12, 16],index=idx) completion=100*pd.Series([int(p[0]) for p in pages])\\ .value_counts().reindex(idx,fill_value=0)/all_pages",
"ago'] = pd.to_datetime(quiz_df['Date'])\\ .apply(lambda x: (datetime.datetime.now()-x).days) quiz_df['# correct'] = quiz_df['Percent']/100 * quiz_df['Completed'] quiz_df['y_value']",
"numpy as np import requests, datetime, webbrowser ## This code will not run",
"title and 'Feedback' not in title and 'Flashcards' not in title and 'Review'",
"# reindex studytimes to ensure that at least one month is visible #",
"Quiz\") ax.set_yticks(np.arange(0.5,7.5,1), minor=True) plt.ylim(0.5,7.5) plt.gca().invert_yaxis() # want Chapter 1 on top, Ch.7 on",
"print(\"Token not returned. Check password is correct\") def get_me_sid(email,token): \"\"\"get MindEdge Student ID\"\"\"",
"MindEdge access / password if 'un' not in vars(): un = 'wgudb' pw",
"'Flashcards' not in title and 'Review' not in title and 'Problem Set' not",
"date, and # of Q's answered data_quiz = [ (*test['title'].split('Module ')[1].split('Problem Set '),",
"first 10 characters of 'first_accessed' gives the date [(x['first_accessed'][:10],x['duration']/3600) for x in r5.json()]",
"axis - study times vertical bar chart ax = plt.subplot(2,1,2) plt.bar(studytimes_reidx.index, studytimes_reidx['duration']) ax.xaxis.set_major_formatter(mdates.DateFormatter('%b",
"Set '), result['final_score'], result['dateCompleted'], result['totalQuestions'] ) for test in r4.json() for result in",
"API token, returns dataframe of login dates and login duration\"\"\" r5 = requests.post(base_url+'studentLogins',",
"fig.patch.set_facecolor('white') plt.subplots_adjust(hspace = 0.3) #more horizontal space between plots #top left axis -",
"= [i for i in range(1,8)] # all_pages gives the total possible pages",
"# parsing the text names of the quizzes to give: # the ch",
") studytimes.columns = ['date','duration'] studytimes = studytimes.groupby('date').sum() # to trim outliers/glitches (e.g. 300",
"= requests.post(base_url+'studentTestData', json={'token':token,'dId':55,'cId':612,'sId':sid}) # parsing the text names of the quizzes to give:",
"= [title for title in read_pages if ( '.' in title and 'Feedback'",
"and active API token, returns dataframe of login dates and login duration\"\"\" r5",
"in test['resultData'] ] quiz_df = pd.DataFrame( data_quiz, columns=['Chapter','Problem Set','Percent','Date','Completed'] ) quiz_df['Percent'] = pd.to_numeric(quiz_df['Percent'])",
"to trim outliers/glitches (e.g. 300 hours spent in one session) # we make",
"student data and creates dashboard locally\"\"\" studytimes = get_logins(sid,token) completion = get_completion_perc(sid,token) quiz_df",
"ax.set_xticks(np.arange(0,105,10)) ax.tick_params(length=0) ax.yaxis.grid(True, which='minor') ax.set_ylabel('Chapter') ax.set_title('Quiz Results') plt.yticks(range(1,8)) # bottom axis - study",
"quiz_df def get_logins(sid,token): \"\"\"given studentID and active API token, returns dataframe of login",
"Sep 2020 all_pages = pd.Series([23, 22, 30, 17, 8, 12, 16],index=idx) completion=100*pd.Series([int(p[0]) for",
"(datetime.datetime.now()+datetime.timedelta(days=-30)).date() all_dates = pd.date_range( min(month_ago, studytimes.index.min()), datetime.datetime.now() ) studytimes_reidx = studytimes.reindex(all_dates,fill_value=0) # WGU",
"read_pages = [t['title'] for t in r3.json()] # titles of pages read #",
"of login dates and login duration\"\"\" r5 = requests.post(base_url+'studentLogins', json={'token':token,'dId':55,'cId':612,'sId':sid}) studytimes = pd.DataFrame(",
"def mindedge_dashboard(sid,token,filename='dashboard.png'): \"\"\"input: studentID, active API token, and image output filename. Gathers all",
"of percent completion by module\"\"\" r3 = requests.post(base_url+'studentCompleteAssignments', json={'token':token,'dId':55,'cId':612,'sId':sid}) read_pages = [t['title'] for",
"returned. Check password is correct\") def get_me_sid(email,token): \"\"\"get MindEdge Student ID\"\"\" r =",
"def get_logins(sid,token): \"\"\"given studentID and active API token, returns dataframe of login dates",
"only pages with learning content: pages = [title for title in read_pages if",
"( '.' in title and 'Feedback' not in title and 'Flashcards' not in",
")] idx = [i for i in range(1,8)] # all_pages gives the total",
"base_url = 'https://wguapps.mindedgeonline.com/services/api/' domain_id = 55 def get_token(password): r = requests.post(base_url+'auth', json =",
"pages read # select only pages with learning content: pages = [title for",
"pages])\\ .value_counts().reindex(idx,fill_value=0)/all_pages return completion def get_quiz_results(sid,token): r4 = requests.post(base_url+'studentTestData', json={'token':token,'dId':55,'cId':612,'sId':sid}) # parsing the",
"1 on top, Ch.7 on bottom plt.xlim(0,105) ax.set_xticks(np.arange(0,105,10)) ax.tick_params(length=0) ax.yaxis.grid(True, which='minor') ax.set_ylabel('Chapter') ax.set_title('Quiz",
"pd import numpy as np import requests, datetime, webbrowser ## This code will",
"i in range(7): if completion.iloc[i]==100: colors[i]=blue plt.barh(completion.index,completion.values, height=1,color=colors,edgecolor='black') plt.ylim(0.5,7.5) plt.xlim(0,100) ax.invert_yaxis() ax.set_ylabel('Chapter') ax.set_title('Completion",
"spent in one session) # we make 10 the maximum reported hours possible",
"quiz_df = get_quiz_results(sid,token) # reindex studytimes to ensure that at least one month",
"= 'wgudb' pw = '' if pw=='': pw = input(\"Enter Mindedge password:\") base_url",
"min date month_ago = (datetime.datetime.now()+datetime.timedelta(days=-30)).date() all_dates = pd.date_range( min(month_ago, studytimes.index.min()), datetime.datetime.now() ) studytimes_reidx",
"try: return r.json()[0]['token'] except Exception as e: print('status: ',r.status_code,':',r.reason) print(e) print(\"Token not returned.",
"make 10 the maximum reported hours possible in one session studytimes[studytimes>10] = 10",
"bottom plt.xlim(0,105) ax.set_xticks(np.arange(0,105,10)) ax.tick_params(length=0) ax.yaxis.grid(True, which='minor') ax.set_ylabel('Chapter') ax.set_title('Quiz Results') plt.yticks(range(1,8)) # bottom axis",
"= pd.DataFrame( data_quiz, columns=['Chapter','Problem Set','Percent','Date','Completed'] ) quiz_df['Percent'] = pd.to_numeric(quiz_df['Percent']) quiz_df['days ago'] = pd.to_datetime(quiz_df['Date'])\\",
"ax.set_title('Completion of Learning Resource (%)') ticks_set = [0,20,40,60,80,100] plt.xticks(ticks_set,[str(val)+'%' for val in ticks_set])",
"quiz_df['y_value'] = pd.to_numeric(quiz_df['Chapter']) return quiz_df def get_logins(sid,token): \"\"\"given studentID and active API token,",
"gives the date [(x['first_accessed'][:10],x['duration']/3600) for x in r5.json()] ) studytimes.columns = ['date','duration'] studytimes",
"duration\"\"\" r5 = requests.post(base_url+'studentLogins', json={'token':token,'dId':55,'cId':612,'sId':sid}) studytimes = pd.DataFrame( # first 10 characters of",
"rcParams['font.family'] = \"sans-serif\" rcParams['font.size'] = 14 fig, axs = plt.subplots(2, 2, figsize=(12, 8),sharey='row')",
"[(x['first_accessed'][:10],x['duration']/3600) for x in r5.json()] ) studytimes.columns = ['date','duration'] studytimes = studytimes.groupby('date').sum() #",
"percent, date, and # of Q's answered data_quiz = [ (*test['title'].split('Module ')[1].split('Problem Set",
"return studytimes def mindedge_dashboard(sid,token,filename='dashboard.png'): \"\"\"input: studentID, active API token, and image output filename.",
"\"\"\"get MindEdge Student ID\"\"\" r = requests.post(base_url+'students', json={'token':token,'dId':55,'emailAddress':email}) return r.json()[0].get('sId') def get_completion_perc(sid,token): \"\"\"returns",
"plt.colorbar(sc) cbar.set_label(\"Days Since Quiz\") ax.set_yticks(np.arange(0.5,7.5,1), minor=True) plt.ylim(0.5,7.5) plt.gca().invert_yaxis() # want Chapter 1 on",
"<filename>student_dashboard_prototype.py<gh_stars>1-10 import matplotlib.pyplot as plt from matplotlib import rcParams import matplotlib.dates as mdates",
"idx = [i for i in range(1,8)] # all_pages gives the total possible",
"['date','duration'] studytimes = studytimes.groupby('date').sum() # to trim outliers/glitches (e.g. 300 hours spent in",
"result['totalQuestions'] ) for test in r4.json() for result in test['resultData'] ] quiz_df =",
"# we make 10 the maximum reported hours possible in one session studytimes[studytimes>10]",
"between plots #top left axis - completion horiz bar chart ax = plt.subplot(2,2,1)",
"quiz_df['Percent']/100 * quiz_df['Completed'] quiz_df['y_value'] = pd.to_numeric(quiz_df['Chapter']) return quiz_df def get_logins(sid,token): \"\"\"given studentID and",
"token, returns dataframe of login dates and login duration\"\"\" r5 = requests.post(base_url+'studentLogins', json={'token':token,'dId':55,'cId':612,'sId':sid})",
"test in r4.json() for result in test['resultData'] ] quiz_df = pd.DataFrame( data_quiz, columns=['Chapter','Problem",
"Check password is correct\") def get_me_sid(email,token): \"\"\"get MindEdge Student ID\"\"\" r = requests.post(base_url+'students',",
"np import requests, datetime, webbrowser ## This code will not run without MindEdge",
"get_quiz_results(sid,token): r4 = requests.post(base_url+'studentTestData', json={'token':token,'dId':55,'cId':612,'sId':sid}) # parsing the text names of the quizzes",
"plot for quiz results ax = plt.subplot(2,2,2); sc = plt.scatter( quiz_df['Percent'].apply(lambda x: x+np.random.normal(0,0.1)),",
"of 'first_accessed' gives the date [(x['first_accessed'][:10],x['duration']/3600) for x in r5.json()] ) studytimes.columns =",
"chart ax = plt.subplot(2,1,2) plt.bar(studytimes_reidx.index, studytimes_reidx['duration']) ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d')) datemin = studytimes_reidx.index.min() datemax =",
"title and 'Review' not in title and 'Problem Set' not in title )]",
"return quiz_df def get_logins(sid,token): \"\"\"given studentID and active API token, returns dataframe of",
"axis - circle plot for quiz results ax = plt.subplot(2,2,2); sc = plt.scatter(",
"plt.subplot(2,2,2); sc = plt.scatter( quiz_df['Percent'].apply(lambda x: x+np.random.normal(0,0.1)), quiz_df['y_value'], s=700,alpha=0.8,c=quiz_df['days ago'],cmap=plt.cm.viridis_r, vmin=0,vmax=max(14,quiz_df['days ago'].max()) )",
"studytimes = get_logins(sid,token) completion = get_completion_perc(sid,token) quiz_df = get_quiz_results(sid,token) # reindex studytimes to",
"not in vars(): un = 'wgudb' pw = '' if pw=='': pw =",
"of 1 mo ago and the min date month_ago = (datetime.datetime.now()+datetime.timedelta(days=-30)).date() all_dates =",
"date month_ago = (datetime.datetime.now()+datetime.timedelta(days=-30)).date() all_dates = pd.date_range( min(month_ago, studytimes.index.min()), datetime.datetime.now() ) studytimes_reidx ="
] |
[
"# rsa.encrypt(plainMessage, ) pass def do_decrypt(cipher_data): pass if __name__ == \"__main__\": message =",
"import rsa def do_encrypt(plain_data): # rsa.encrypt(plainMessage, ) pass def do_decrypt(cipher_data): pass if __name__",
"def do_encrypt(plain_data): # rsa.encrypt(plainMessage, ) pass def do_decrypt(cipher_data): pass if __name__ == \"__main__\":",
") pass def do_decrypt(cipher_data): pass if __name__ == \"__main__\": message = \"hello world\"",
"def do_decrypt(cipher_data): pass if __name__ == \"__main__\": message = \"hello world\" pubkey =",
"\"hello world\" pubkey = \"\" # 加密 cipherMessage = rsa.encrypt(message.encode(), pubkey) print cipherMessage",
"do_decrypt(cipher_data): pass if __name__ == \"__main__\": message = \"hello world\" pubkey = \"\"",
"\"__main__\": message = \"hello world\" pubkey = \"\" # 加密 cipherMessage = rsa.encrypt(message.encode(),",
"# -*- coding: utf-8 -*- import rsa def do_encrypt(plain_data): # rsa.encrypt(plainMessage, ) pass",
"= \"hello world\" pubkey = \"\" # 加密 cipherMessage = rsa.encrypt(message.encode(), pubkey) print",
"if __name__ == \"__main__\": message = \"hello world\" pubkey = \"\" # 加密",
"-*- coding: utf-8 -*- import rsa def do_encrypt(plain_data): # rsa.encrypt(plainMessage, ) pass def",
"== \"__main__\": message = \"hello world\" pubkey = \"\" # 加密 cipherMessage =",
"coding: utf-8 -*- import rsa def do_encrypt(plain_data): # rsa.encrypt(plainMessage, ) pass def do_decrypt(cipher_data):",
"utf-8 -*- import rsa def do_encrypt(plain_data): # rsa.encrypt(plainMessage, ) pass def do_decrypt(cipher_data): pass",
"-*- import rsa def do_encrypt(plain_data): # rsa.encrypt(plainMessage, ) pass def do_decrypt(cipher_data): pass if",
"pass if __name__ == \"__main__\": message = \"hello world\" pubkey = \"\" #",
"message = \"hello world\" pubkey = \"\" # 加密 cipherMessage = rsa.encrypt(message.encode(), pubkey)",
"do_encrypt(plain_data): # rsa.encrypt(plainMessage, ) pass def do_decrypt(cipher_data): pass if __name__ == \"__main__\": message",
"__name__ == \"__main__\": message = \"hello world\" pubkey = \"\" # 加密 cipherMessage",
"python # -*- coding: utf-8 -*- import rsa def do_encrypt(plain_data): # rsa.encrypt(plainMessage, )",
"rsa.encrypt(plainMessage, ) pass def do_decrypt(cipher_data): pass if __name__ == \"__main__\": message = \"hello",
"pass def do_decrypt(cipher_data): pass if __name__ == \"__main__\": message = \"hello world\" pubkey",
"#!/usr/bin/env python # -*- coding: utf-8 -*- import rsa def do_encrypt(plain_data): # rsa.encrypt(plainMessage,",
"rsa def do_encrypt(plain_data): # rsa.encrypt(plainMessage, ) pass def do_decrypt(cipher_data): pass if __name__ =="
] |
[
"number of edge combinations \"\"\" # Copy the given degree sequence to use",
"the s function e, p, c = s(deg_seq) # Append the edges edges.append(e)",
"greater than 0 i = np.where(r == np.amin(r[r > 0]))[0][-1] c *= factorial(r[i])",
"is True: print \"Total computation time : \" + str(time_elapsed) return estimate, std",
"the number of edge combinations \"\"\" # Copy the given degree sequence to",
"\" + str(time_elapsed) return [] edges = [] for _ in range(num_of_samples): #",
"of samples which will be generated :return: \"\"\" # Get the initial time",
"time_start = time.clock() # If the sequence is empty or is not graphical",
"s(deg_seq) weights[i] = 1.0 / float(c * p) estimate = (1.0 / float(num_of_samples))",
"std: Estimation for the number of graphs satisfying the given degree sequence d",
"the edges edges.append(e) # Get the total computation time time_elapsed = (time.clock() -",
"is_graphical(r): J = np.append(J, j) # Increase degrees by one (r[i], r[j]) =",
"start from 1 # Add the chosen vertex to the list in order",
"s(deg_seq) # Append the edges edges.append(e) # Get the total computation time time_elapsed",
"graph for a given degree sequence d :param deg_seq: Given degree sequence :return",
"o in np.arange(N) if (r[o] > 0 and o != i and (o",
"# add the the vertex j to candidate list J, if residual sequence",
"graphical if is_graphical(r): J = np.append(J, j) # Increase degrees by one (r[i],",
"if residual sequence is graphical if is_graphical(r): J = np.append(J, j) # Increase",
"degrees by one (r[i], r[j]) = (r[i] - 1, r[j] - 1) #",
"computation time : \" + str(time_elapsed) return 0.0, 0.0 weights = np.zeros(num_of_samples, dtype=float)",
"vertex having minimum degree greater than 0 i = np.where(r == np.amin(r[r >",
"r[j] + 1) # Pick a vertex j in the candidate list J",
"one (r[i], r[j]) = (r[i] + 1, r[j] + 1) # Pick a",
"sequence 'deg_seq' with vertex labels {1,...,len(deg_seq}} :param deg_seq: Degree sequence :param num_of_samples: Number",
"from sacorg.algorithms.isgraphical import * def s(deg_seq): \"\"\" Generates a sample graph for a",
"# probability of the generated graph c = 1 # the number of",
"edges with vertex labels starting from 1, probability of the generated graph and",
"the initial time time_start = time.clock() # If the sequence is empty or",
"the given degree sequence to use it as residual sequence r = deg_seq.copy()",
"and (o not in adjacentVertices[i]))] for j in possibleVertices: # Decrease degrees by",
"possibleVertices: # Decrease degrees by one (r[i], r[j]) = (r[i] - 1, r[j]",
"degree sequence :return E, p, c: edges with vertex labels starting from 1,",
"its degree d_j degrees = np.asarray([r[u] for u in J]) prob = degrees",
"(r[i] - 1, r[j] - 1) # add the the vertex j to",
"return [] edges = [] for _ in range(num_of_samples): # Call the s",
"Estimation for the number of graphs satisfying the given degree sequence d and",
"list of edges N = len(r) # length of the sequence adjacentVertices =",
"(r[i], r[j]) = (r[i] + 1, r[j] + 1) # Pick a vertex",
"= [o for o in np.arange(N) if (r[o] > 0 and o !=",
"float(num_of_samples)) * np.sum(weights) std = np.std(weights, ddof=1) # Get the total computation time",
"Append the edges edges.append(e) # Get the total computation time time_elapsed = (time.clock()",
"p=prob, size=1)[0] # Add the found edge to the edge lists if i",
"number of graphs satisfying the degree sequence :param deq_seq: Degree sequence :param num_of_samples:",
"graphs satisfying the degree sequence :param deq_seq: Degree sequence :param num_of_samples: number of",
"# Construct candidate list J possibleVertices = [o for o in np.arange(N) if",
"verbose is True: print \"Total computation time : \" + str(time_elapsed) # Return",
"will be generated :return: \"\"\" # Get the initial time time_start = time.clock()",
"edges edges.append(e) # Get the total computation time time_elapsed = (time.clock() - time_start)",
"in J]) prob = degrees / float(np.sum(degrees)) j = np.random.choice(J, p=prob, size=1)[0] #",
"time_start) print \"Total computation time : \" + str(time_elapsed) return [] edges =",
"range(num_of_samples): # Call the s function e, p, c = s(deg_seq) # Append",
"in np.arange(N) if (r[o] > 0 and o != i and (o not",
"completely becomes 0 vector while np.any(r != 0): # Get the index of",
"# Append the edges edges.append(e) # Get the total computation time time_elapsed =",
"count(deg_seq, num_of_samples=1000, verbose=False): \"\"\" Estimates the number of graphs satisfying the degree sequence",
"time_elapsed = (time.clock() - time_start) print \"Total computation time : \" + str(time_elapsed)",
"estimation :return estimation, std: Estimation for the number of graphs satisfying the given",
"+ 1, r[j] + 1) # Pick a vertex j in the candidate",
"(r[i] - 1, r[j] - 1) p *= prob[J == j][0] # Sort",
"+ 1, j + 1]) # indices start from 1 else: E.append([j +",
"graph that can be generated by the algorithm E = [] # list",
"E = [] # list of edges N = len(r) # length of",
"Sort the edge sequences E.sort() return E, p, c def get_sample(deg_seq, num_of_samples, verbose=False):",
"# Get initial time time_start = time.clock() # If the sequence is empty",
"initial time time_start = time.clock() # If the sequence is empty or is",
"j in the candidate list J with probability proportional to its degree d_j",
"[] for _ in range(num_of_samples): # Call the s function e, p, c",
"= np.std(weights, ddof=1) # Get the total computation time time_elapsed = (time.clock() -",
"J with probability proportional to its degree d_j degrees = np.asarray([r[u] for u",
"j: E.append([i + 1, j + 1]) # indices start from 1 else:",
"*= factorial(r[i]) while r[i] != 0: J = np.asarray([], dtype=np.int) # Construct candidate",
"= s(deg_seq) # Append the edges edges.append(e) # Get the total computation time",
"the number of edge combinations for the same graph that can be generated",
"for the same graph that can be generated by the algorithm E =",
"!= 0): # Get the index of vertex having minimum degree greater than",
"if (r[o] > 0 and o != i and (o not in adjacentVertices[i]))]",
"d_j degrees = np.asarray([r[u] for u in J]) prob = degrees / float(np.sum(degrees))",
"1, j + 1]) # indices start from 1 else: E.append([j + 1,",
"not choose it again adjacentVertices[i].append(j) # Decrease degrees by 1 (r[i], r[j]) =",
"Increase degrees by one (r[i], r[j]) = (r[i] + 1, r[j] + 1)",
"edge to the edge lists if i < j: E.append([i + 1, j",
"Add the found edge to the edge lists if i < j: E.append([i",
"for i in range(num_of_samples): (edges, p, c) = s(deg_seq) weights[i] = 1.0 /",
"import * from sacorg.algorithms.isgraphical import * def s(deg_seq): \"\"\" Generates a sample graph",
"by the algorithm E = [] # list of edges N = len(r)",
"time : \" + str(time_elapsed) return 0.0, 0.0 weights = np.zeros(num_of_samples, dtype=float) for",
"the chosen vertex to the list in order to not choose it again",
"same graph that can be generated by the algorithm E = [] #",
":param deg_seq: Degree sequence :param num_of_samples: Number of samples which will be generated",
"float(np.sum(degrees)) j = np.random.choice(J, p=prob, size=1)[0] # Add the found edge to the",
"sequence d :param deg_seq: Given degree sequence :return E, p, c: edges with",
"of edge combinations for the same graph that can be generated by the",
"Pick a vertex j in the candidate list J with probability proportional to",
"order to not choose it again adjacentVertices[i].append(j) # Decrease degrees by 1 (r[i],",
"i < j: E.append([i + 1, j + 1]) # indices start from",
"/ float(num_of_samples)) * np.sum(weights) std = np.std(weights, ddof=1) # Get the total computation",
"candidate list J with probability proportional to its degree d_j degrees = np.asarray([r[u]",
"sequence :param deq_seq: Degree sequence :param num_of_samples: number of samples used in estimation",
"degree sequence 'deg_seq' with vertex labels {1,...,len(deg_seq}} :param deg_seq: Degree sequence :param num_of_samples:",
"!= i and (o not in adjacentVertices[i]))] for j in possibleVertices: # Decrease",
"combinations \"\"\" # Copy the given degree sequence to use it as residual",
"= np.zeros(num_of_samples, dtype=float) for i in range(num_of_samples): (edges, p, c) = s(deg_seq) weights[i]",
"float(c * p) estimate = (1.0 / float(num_of_samples)) * np.sum(weights) std = np.std(weights,",
"adjacentVertices[i]))] for j in possibleVertices: # Decrease degrees by one (r[i], r[j]) =",
"- 1) # add the the vertex j to candidate list J, if",
"= np.where(r == np.amin(r[r > 0]))[0][-1] c *= factorial(r[i]) while r[i] != 0:",
"(o not in adjacentVertices[i]))] for j in possibleVertices: # Decrease degrees by one",
":param deg_seq: Given degree sequence :return E, p, c: edges with vertex labels",
"1, r[j] - 1) p *= prob[J == j][0] # Sort the edge",
"1 else: E.append([j + 1, i + 1]) # indices start from 1",
"in range(num_of_samples): (edges, p, c) = s(deg_seq) weights[i] = 1.0 / float(c *",
"and the number of edge combinations \"\"\" # Copy the given degree sequence",
"get_sample(deg_seq, num_of_samples, verbose=False): \"\"\" Generates graphs realizing the degree sequence 'deg_seq' with vertex",
"the generated graph and the number of edge combinations \"\"\" # Copy the",
"generated :return: \"\"\" # Get the initial time time_start = time.clock() # If",
"dtype=np.int) # Construct candidate list J possibleVertices = [o for o in np.arange(N)",
"< j: E.append([i + 1, j + 1]) # indices start from 1",
"graphs realizing the degree sequence 'deg_seq' with vertex labels {1,...,len(deg_seq}} :param deg_seq: Degree",
"= (r[i] - 1, r[j] - 1) # add the the vertex j",
"adjacentVertices = [[] for _ in range(N)] # stores the vertices which are",
"satisfying the degree sequence :param deq_seq: Degree sequence :param num_of_samples: number of samples",
"# Call the s function e, p, c = s(deg_seq) # Append the",
"number of graphs satisfying the given degree sequence d and standard deviation \"\"\"",
"= (1.0 / float(num_of_samples)) * np.sum(weights) std = np.std(weights, ddof=1) # Get the",
"in possibleVertices: # Decrease degrees by one (r[i], r[j]) = (r[i] - 1,",
"(time.clock() - time_start) if verbose is True: print \"Total computation time : \"",
"1) # Pick a vertex j in the candidate list J with probability",
"lists if i < j: E.append([i + 1, j + 1]) # indices",
"edge combinations \"\"\" # Copy the given degree sequence to use it as",
"r[i] != 0: J = np.asarray([], dtype=np.int) # Construct candidate list J possibleVertices",
"vertex labels {1,...,len(deg_seq}} :param deg_seq: Degree sequence :param num_of_samples: Number of samples which",
"until residual sequence completely becomes 0 vector while np.any(r != 0): # Get",
"the edges return edges def count(deg_seq, num_of_samples=1000, verbose=False): \"\"\" Estimates the number of",
"Degree sequence :param num_of_samples: Number of samples which will be generated :return: \"\"\"",
"the found edge to the edge lists if i < j: E.append([i +",
"as residual sequence r = deg_seq.copy() p = 1.0 # probability of the",
"j to candidate list J, if residual sequence is graphical if is_graphical(r): J",
"1.0 # probability of the generated graph c = 1 # the number",
"= 0.0 # Get initial time time_start = time.clock() # If the sequence",
"standard deviation \"\"\" estimate = 0.0 # Get initial time time_start = time.clock()",
"(r[i], r[j]) = (r[i] - 1, r[j] - 1) # add the the",
"choose it again adjacentVertices[i].append(j) # Decrease degrees by 1 (r[i], r[j]) = (r[i]",
"c def get_sample(deg_seq, num_of_samples, verbose=False): \"\"\" Generates graphs realizing the degree sequence 'deg_seq'",
"found edge to the edge lists if i < j: E.append([i + 1,",
":param num_of_samples: number of samples used in estimation :return estimation, std: Estimation for",
"for _ in range(N)] # stores the vertices which are adjacent # run",
"with probability proportional to its degree d_j degrees = np.asarray([r[u] for u in",
"+ 1, i + 1]) # indices start from 1 # Add the",
"samples which will be generated :return: \"\"\" # Get the initial time time_start",
"np.where(r == np.amin(r[r > 0]))[0][-1] c *= factorial(r[i]) while r[i] != 0: J",
"0: J = np.asarray([], dtype=np.int) # Construct candidate list J possibleVertices = [o",
"if is_graphical(r): J = np.append(J, j) # Increase degrees by one (r[i], r[j])",
"= time.clock() # If the sequence is empty or is not graphical if",
"run until residual sequence completely becomes 0 vector while np.any(r != 0): #",
"num_of_samples, verbose=False): \"\"\" Generates graphs realizing the degree sequence 'deg_seq' with vertex labels",
"generated by the algorithm E = [] # list of edges N =",
"list J with probability proportional to its degree d_j degrees = np.asarray([r[u] for",
"time time_start = time.clock() # If the sequence is empty or is not",
"number of edge combinations for the same graph that can be generated by",
"i + 1]) # indices start from 1 # Add the chosen vertex",
"Decrease degrees by one (r[i], r[j]) = (r[i] - 1, r[j] - 1)",
"J]) prob = degrees / float(np.sum(degrees)) j = np.random.choice(J, p=prob, size=1)[0] # Add",
"0.0 weights = np.zeros(num_of_samples, dtype=float) for i in range(num_of_samples): (edges, p, c) =",
"range(num_of_samples): (edges, p, c) = s(deg_seq) weights[i] = 1.0 / float(c * p)",
"N = len(r) # length of the sequence adjacentVertices = [[] for _",
"edges def count(deg_seq, num_of_samples=1000, verbose=False): \"\"\" Estimates the number of graphs satisfying the",
"num_of_samples: Number of samples which will be generated :return: \"\"\" # Get the",
"number of samples used in estimation :return estimation, std: Estimation for the number",
"time : \" + str(time_elapsed) # Return the edges return edges def count(deg_seq,",
"J, if residual sequence is graphical if is_graphical(r): J = np.append(J, j) #",
"which are adjacent # run until residual sequence completely becomes 0 vector while",
"samples used in estimation :return estimation, std: Estimation for the number of graphs",
"* def s(deg_seq): \"\"\" Generates a sample graph for a given degree sequence",
"for the number of graphs satisfying the given degree sequence d and standard",
"degrees / float(np.sum(degrees)) j = np.random.choice(J, p=prob, size=1)[0] # Add the found edge",
"\"\"\" Generates a sample graph for a given degree sequence d :param deg_seq:",
"np.sum(weights) std = np.std(weights, ddof=1) # Get the total computation time time_elapsed =",
"by one (r[i], r[j]) = (r[i] - 1, r[j] - 1) # add",
"that can be generated by the algorithm E = [] # list of",
"with vertex labels {1,...,len(deg_seq}} :param deg_seq: Degree sequence :param num_of_samples: Number of samples",
"1, probability of the generated graph and the number of edge combinations \"\"\"",
"degree greater than 0 i = np.where(r == np.amin(r[r > 0]))[0][-1] c *=",
"# stores the vertices which are adjacent # run until residual sequence completely",
"Get the total computation time time_elapsed = (time.clock() - time_start) print \"Total computation",
"std = np.std(weights, ddof=1) # Get the total computation time time_elapsed = (time.clock()",
"c *= factorial(r[i]) while r[i] != 0: J = np.asarray([], dtype=np.int) # Construct",
"while np.any(r != 0): # Get the index of vertex having minimum degree",
"time : \" + str(time_elapsed) return [] edges = [] for _ in",
"of samples used in estimation :return estimation, std: Estimation for the number of",
"degree sequence d :param deg_seq: Given degree sequence :return E, p, c: edges",
"= np.asarray([], dtype=np.int) # Construct candidate list J possibleVertices = [o for o",
": \" + str(time_elapsed) return [] edges = [] for _ in range(num_of_samples):",
"= (r[i] + 1, r[j] + 1) # Pick a vertex j in",
"# Get the index of vertex having minimum degree greater than 0 i",
"is False: if verbose is True: # Get the total computation time time_elapsed",
"given degree sequence to use it as residual sequence r = deg_seq.copy() p",
"(r[o] > 0 and o != i and (o not in adjacentVertices[i]))] for",
"np.asarray([r[u] for u in J]) prob = degrees / float(np.sum(degrees)) j = np.random.choice(J,",
"np.asarray([], dtype=np.int) # Construct candidate list J possibleVertices = [o for o in",
"- time_start) print \"Total computation time : \" + str(time_elapsed) return 0.0, 0.0",
"not graphical if len(deg_seq) == 0 or is_graphical(deg_seq) is False: if verbose is",
"graphical if len(deg_seq) == 0 or is_graphical(deg_seq) is False: if verbose is True:",
"sequence adjacentVertices = [[] for _ in range(N)] # stores the vertices which",
"p = 1.0 # probability of the generated graph c = 1 #",
"np.any(r != 0): # Get the index of vertex having minimum degree greater",
"the candidate list J with probability proportional to its degree d_j degrees =",
"\"Total computation time : \" + str(time_elapsed) return [] edges = [] for",
"# length of the sequence adjacentVertices = [[] for _ in range(N)] #",
"deviation \"\"\" estimate = 0.0 # Get initial time time_start = time.clock() #",
"# list of edges N = len(r) # length of the sequence adjacentVertices",
"* p) estimate = (1.0 / float(num_of_samples)) * np.sum(weights) std = np.std(weights, ddof=1)",
"print \"Total computation time : \" + str(time_elapsed) return [] edges = []",
"to the edge lists if i < j: E.append([i + 1, j +",
"generated graph c = 1 # the number of edge combinations for the",
"stores the vertices which are adjacent # run until residual sequence completely becomes",
"to its degree d_j degrees = np.asarray([r[u] for u in J]) prob =",
"E.sort() return E, p, c def get_sample(deg_seq, num_of_samples, verbose=False): \"\"\" Generates graphs realizing",
"Degree sequence :param num_of_samples: number of samples used in estimation :return estimation, std:",
"for o in np.arange(N) if (r[o] > 0 and o != i and",
"to the list in order to not choose it again adjacentVertices[i].append(j) # Decrease",
"candidate list J possibleVertices = [o for o in np.arange(N) if (r[o] >",
"the edge lists if i < j: E.append([i + 1, j + 1])",
"the degree sequence :param deq_seq: Degree sequence :param num_of_samples: number of samples used",
"- time_start) print \"Total computation time : \" + str(time_elapsed) return [] edges",
"* from sacorg.algorithms.isgraphical import * def s(deg_seq): \"\"\" Generates a sample graph for",
"list J possibleVertices = [o for o in np.arange(N) if (r[o] > 0",
":param num_of_samples: Number of samples which will be generated :return: \"\"\" # Get",
"0.0, 0.0 weights = np.zeros(num_of_samples, dtype=float) for i in range(num_of_samples): (edges, p, c)",
"degree sequence d and standard deviation \"\"\" estimate = 0.0 # Get initial",
"(r[i] + 1, r[j] + 1) # Pick a vertex j in the",
"the the vertex j to candidate list J, if residual sequence is graphical",
"prob[J == j][0] # Sort the edge sequences E.sort() return E, p, c",
"vertex j to candidate list J, if residual sequence is graphical if is_graphical(r):",
"of edges N = len(r) # length of the sequence adjacentVertices = [[]",
"sequence :param num_of_samples: number of samples used in estimation :return estimation, std: Estimation",
"_ in range(num_of_samples): # Call the s function e, p, c = s(deg_seq)",
"of the sequence adjacentVertices = [[] for _ in range(N)] # stores the",
"again adjacentVertices[i].append(j) # Decrease degrees by 1 (r[i], r[j]) = (r[i] - 1,",
"print \"Total computation time : \" + str(time_elapsed) # Return the edges return",
"p, c) = s(deg_seq) weights[i] = 1.0 / float(c * p) estimate =",
"j + 1]) # indices start from 1 else: E.append([j + 1, i",
"== np.amin(r[r > 0]))[0][-1] c *= factorial(r[i]) while r[i] != 0: J =",
"are adjacent # run until residual sequence completely becomes 0 vector while np.any(r",
"+ 1) # Pick a vertex j in the candidate list J with",
"graphs satisfying the given degree sequence d and standard deviation \"\"\" estimate =",
"labels {1,...,len(deg_seq}} :param deg_seq: Degree sequence :param num_of_samples: Number of samples which will",
"estimation, std: Estimation for the number of graphs satisfying the given degree sequence",
"deg_seq: Degree sequence :param num_of_samples: Number of samples which will be generated :return:",
"c = 1 # the number of edge combinations for the same graph",
"p, c = s(deg_seq) # Append the edges edges.append(e) # Get the total",
"from 1 # Add the chosen vertex to the list in order to",
"of the generated graph c = 1 # the number of edge combinations",
"def count(deg_seq, num_of_samples=1000, verbose=False): \"\"\" Estimates the number of graphs satisfying the degree",
"edges.append(e) # Get the total computation time time_elapsed = (time.clock() - time_start) if",
"# run until residual sequence completely becomes 0 vector while np.any(r != 0):",
"= [] for _ in range(num_of_samples): # Call the s function e, p,",
"factorial(r[i]) while r[i] != 0: J = np.asarray([], dtype=np.int) # Construct candidate list",
"weights[i] = 1.0 / float(c * p) estimate = (1.0 / float(num_of_samples)) *",
"deg_seq: Given degree sequence :return E, p, c: edges with vertex labels starting",
": \" + str(time_elapsed) # Return the edges return edges def count(deg_seq, num_of_samples=1000,",
"r[j]) = (r[i] - 1, r[j] - 1) # add the the vertex",
"# indices start from 1 # Add the chosen vertex to the list",
"with vertex labels starting from 1, probability of the generated graph and the",
"computation time time_elapsed = (time.clock() - time_start) print \"Total computation time : \"",
"time_start) print \"Total computation time : \" + str(time_elapsed) return 0.0, 0.0 weights",
"# Decrease degrees by one (r[i], r[j]) = (r[i] - 1, r[j] -",
"generated graph and the number of edge combinations \"\"\" # Copy the given",
"combinations for the same graph that can be generated by the algorithm E",
"total computation time time_elapsed = (time.clock() - time_start) print \"Total computation time :",
"if verbose is True: print \"Total computation time : \" + str(time_elapsed) return",
"len(deg_seq) == 0 or is_graphical(deg_seq) is False: if verbose is True: # Get",
"Copy the given degree sequence to use it as residual sequence r =",
"j = np.random.choice(J, p=prob, size=1)[0] # Add the found edge to the edge",
"(time.clock() - time_start) print \"Total computation time : \" + str(time_elapsed) return []",
"from sacorg.utils import * from sacorg.algorithms.isgraphical import * def s(deg_seq): \"\"\" Generates a",
"which will be generated :return: \"\"\" # Get the initial time time_start =",
"indices start from 1 # Add the chosen vertex to the list in",
":param deq_seq: Degree sequence :param num_of_samples: number of samples used in estimation :return",
"given degree sequence d and standard deviation \"\"\" estimate = 0.0 # Get",
"list in order to not choose it again adjacentVertices[i].append(j) # Decrease degrees by",
"\"\"\" # Get the initial time time_start = time.clock() # If the sequence",
"in range(N)] # stores the vertices which are adjacent # run until residual",
"weights = np.zeros(num_of_samples, dtype=float) for i in range(num_of_samples): (edges, p, c) = s(deg_seq)",
"+ str(time_elapsed) return [] edges = [] for _ in range(num_of_samples): # Call",
"degrees = np.asarray([r[u] for u in J]) prob = degrees / float(np.sum(degrees)) j",
"0 and o != i and (o not in adjacentVertices[i]))] for j in",
"vertex labels starting from 1, probability of the generated graph and the number",
"1, r[j] + 1) # Pick a vertex j in the candidate list",
"return E, p, c def get_sample(deg_seq, num_of_samples, verbose=False): \"\"\" Generates graphs realizing the",
"degrees by 1 (r[i], r[j]) = (r[i] - 1, r[j] - 1) p",
"having minimum degree greater than 0 i = np.where(r == np.amin(r[r > 0]))[0][-1]",
"# the number of edge combinations for the same graph that can be",
"E, p, c: edges with vertex labels starting from 1, probability of the",
"deq_seq: Degree sequence :param num_of_samples: number of samples used in estimation :return estimation,",
"to use it as residual sequence r = deg_seq.copy() p = 1.0 #",
"Return the edges return edges def count(deg_seq, num_of_samples=1000, verbose=False): \"\"\" Estimates the number",
"return edges def count(deg_seq, num_of_samples=1000, verbose=False): \"\"\" Estimates the number of graphs satisfying",
"Construct candidate list J possibleVertices = [o for o in np.arange(N) if (r[o]",
"for u in J]) prob = degrees / float(np.sum(degrees)) j = np.random.choice(J, p=prob,",
"0): # Get the index of vertex having minimum degree greater than 0",
"in adjacentVertices[i]))] for j in possibleVertices: # Decrease degrees by one (r[i], r[j])",
"\"\"\" estimate = 0.0 # Get initial time time_start = time.clock() # If",
"- 1, r[j] - 1) # add the the vertex j to candidate",
"(time.clock() - time_start) print \"Total computation time : \" + str(time_elapsed) return 0.0,",
"verbose is True: print \"Total computation time : \" + str(time_elapsed) return estimate,",
"Get the initial time time_start = time.clock() # If the sequence is empty",
"estimate = (1.0 / float(num_of_samples)) * np.sum(weights) std = np.std(weights, ddof=1) # Get",
"graph and the number of edge combinations \"\"\" # Copy the given degree",
"1 (r[i], r[j]) = (r[i] - 1, r[j] - 1) p *= prob[J",
"Get initial time time_start = time.clock() # If the sequence is empty or",
"list J, if residual sequence is graphical if is_graphical(r): J = np.append(J, j)",
"sacorg.utils import * from sacorg.algorithms.isgraphical import * def s(deg_seq): \"\"\" Generates a sample",
"verbose is True: # Get the total computation time time_elapsed = (time.clock() -",
"time_start) if verbose is True: print \"Total computation time : \" + str(time_elapsed)",
"minimum degree greater than 0 i = np.where(r == np.amin(r[r > 0]))[0][-1] c",
"indices start from 1 else: E.append([j + 1, i + 1]) # indices",
"+ 1]) # indices start from 1 else: E.append([j + 1, i +",
"the algorithm E = [] # list of edges N = len(r) #",
"one (r[i], r[j]) = (r[i] - 1, r[j] - 1) # add the",
"can be generated by the algorithm E = [] # list of edges",
"(1.0 / float(num_of_samples)) * np.sum(weights) std = np.std(weights, ddof=1) # Get the total",
"chosen vertex to the list in order to not choose it again adjacentVertices[i].append(j)",
"Get the index of vertex having minimum degree greater than 0 i =",
"*= prob[J == j][0] # Sort the edge sequences E.sort() return E, p,",
"= np.append(J, j) # Increase degrees by one (r[i], r[j]) = (r[i] +",
"edges N = len(r) # length of the sequence adjacentVertices = [[] for",
"length of the sequence adjacentVertices = [[] for _ in range(N)] # stores",
"import * def s(deg_seq): \"\"\" Generates a sample graph for a given degree",
"np.std(weights, ddof=1) # Get the total computation time time_elapsed = (time.clock() - time_start)",
"if verbose is True: # Get the total computation time time_elapsed = (time.clock()",
"i = np.where(r == np.amin(r[r > 0]))[0][-1] c *= factorial(r[i]) while r[i] !=",
"if len(deg_seq) == 0 or is_graphical(deg_seq) is False: if verbose is True: #",
"computation time : \" + str(time_elapsed) # Return the edges return edges def",
"be generated :return: \"\"\" # Get the initial time time_start = time.clock() #",
"total computation time time_elapsed = (time.clock() - time_start) if verbose is True: print",
"# If the sequence is empty or is not graphical if len(deg_seq) ==",
"Decrease degrees by 1 (r[i], r[j]) = (r[i] - 1, r[j] - 1)",
"residual sequence is graphical if is_graphical(r): J = np.append(J, j) # Increase degrees",
"edges return edges def count(deg_seq, num_of_samples=1000, verbose=False): \"\"\" Estimates the number of graphs",
"\"\"\" Generates graphs realizing the degree sequence 'deg_seq' with vertex labels {1,...,len(deg_seq}} :param",
"\"Total computation time : \" + str(time_elapsed) return 0.0, 0.0 weights = np.zeros(num_of_samples,",
"edge lists if i < j: E.append([i + 1, j + 1]) #",
"def s(deg_seq): \"\"\" Generates a sample graph for a given degree sequence d",
"Get the total computation time time_elapsed = (time.clock() - time_start) if verbose is",
"time_elapsed = (time.clock() - time_start) if verbose is True: print \"Total computation time",
"in estimation :return estimation, std: Estimation for the number of graphs satisfying the",
"or is_graphical(deg_seq) is False: if verbose is True: # Get the total computation",
"if verbose is True: print \"Total computation time : \" + str(time_elapsed) #",
"probability of the generated graph c = 1 # the number of edge",
"print \"Total computation time : \" + str(time_elapsed) return 0.0, 0.0 weights =",
"+ 1]) # indices start from 1 # Add the chosen vertex to",
"residual sequence completely becomes 0 vector while np.any(r != 0): # Get the",
"j][0] # Sort the edge sequences E.sort() return E, p, c def get_sample(deg_seq,",
"def get_sample(deg_seq, num_of_samples, verbose=False): \"\"\" Generates graphs realizing the degree sequence 'deg_seq' with",
"* np.sum(weights) std = np.std(weights, ddof=1) # Get the total computation time time_elapsed",
"from 1, probability of the generated graph and the number of edge combinations",
": \" + str(time_elapsed) return 0.0, 0.0 weights = np.zeros(num_of_samples, dtype=float) for i",
"the number of graphs satisfying the given degree sequence d and standard deviation",
"of vertex having minimum degree greater than 0 i = np.where(r == np.amin(r[r",
"start from 1 else: E.append([j + 1, i + 1]) # indices start",
"str(time_elapsed) return [] edges = [] for _ in range(num_of_samples): # Call the",
"the number of graphs satisfying the degree sequence :param deq_seq: Degree sequence :param",
"is not graphical if len(deg_seq) == 0 or is_graphical(deg_seq) is False: if verbose",
"the vertex j to candidate list J, if residual sequence is graphical if",
"= np.random.choice(J, p=prob, size=1)[0] # Add the found edge to the edge lists",
"np.append(J, j) # Increase degrees by one (r[i], r[j]) = (r[i] + 1,",
"= (time.clock() - time_start) print \"Total computation time : \" + str(time_elapsed) return",
"add the the vertex j to candidate list J, if residual sequence is",
"# Get the initial time time_start = time.clock() # If the sequence is",
"and o != i and (o not in adjacentVertices[i]))] for j in possibleVertices:",
"to not choose it again adjacentVertices[i].append(j) # Decrease degrees by 1 (r[i], r[j])",
"the total computation time time_elapsed = (time.clock() - time_start) print \"Total computation time",
"proportional to its degree d_j degrees = np.asarray([r[u] for u in J]) prob",
"np.random.choice(J, p=prob, size=1)[0] # Add the found edge to the edge lists if",
"(r[i], r[j]) = (r[i] - 1, r[j] - 1) p *= prob[J ==",
"J possibleVertices = [o for o in np.arange(N) if (r[o] > 0 and",
"/ float(c * p) estimate = (1.0 / float(num_of_samples)) * np.sum(weights) std =",
"time time_elapsed = (time.clock() - time_start) print \"Total computation time : \" +",
"c = s(deg_seq) # Append the edges edges.append(e) # Get the total computation",
"1.0 / float(c * p) estimate = (1.0 / float(num_of_samples)) * np.sum(weights) std",
"np.amin(r[r > 0]))[0][-1] c *= factorial(r[i]) while r[i] != 0: J = np.asarray([],",
"# Copy the given degree sequence to use it as residual sequence r",
"degrees by one (r[i], r[j]) = (r[i] + 1, r[j] + 1) #",
"vertex to the list in order to not choose it again adjacentVertices[i].append(j) #",
"r = deg_seq.copy() p = 1.0 # probability of the generated graph c",
"probability proportional to its degree d_j degrees = np.asarray([r[u] for u in J])",
"= 1.0 / float(c * p) estimate = (1.0 / float(num_of_samples)) * np.sum(weights)",
"time time_elapsed = (time.clock() - time_start) if verbose is True: print \"Total computation",
"vertices which are adjacent # run until residual sequence completely becomes 0 vector",
"\"\"\" Estimates the number of graphs satisfying the degree sequence :param deq_seq: Degree",
"E, p, c def get_sample(deg_seq, num_of_samples, verbose=False): \"\"\" Generates graphs realizing the degree",
"# indices start from 1 else: E.append([j + 1, i + 1]) #",
"= degrees / float(np.sum(degrees)) j = np.random.choice(J, p=prob, size=1)[0] # Add the found",
"given degree sequence d :param deg_seq: Given degree sequence :return E, p, c:",
"1) p *= prob[J == j][0] # Sort the edge sequences E.sort() return",
"be generated by the algorithm E = [] # list of edges N",
"1, r[j] - 1) # add the the vertex j to candidate list",
"labels starting from 1, probability of the generated graph and the number of",
"r[j] - 1) # add the the vertex j to candidate list J,",
"= deg_seq.copy() p = 1.0 # probability of the generated graph c =",
"Generates a sample graph for a given degree sequence d :param deg_seq: Given",
"s function e, p, c = s(deg_seq) # Append the edges edges.append(e) #",
"0 vector while np.any(r != 0): # Get the index of vertex having",
"sacorg.algorithms.isgraphical import * def s(deg_seq): \"\"\" Generates a sample graph for a given",
"if i < j: E.append([i + 1, j + 1]) # indices start",
"r[j]) = (r[i] - 1, r[j] - 1) p *= prob[J == j][0]",
"the index of vertex having minimum degree greater than 0 i = np.where(r",
"range(N)] # stores the vertices which are adjacent # run until residual sequence",
"j in possibleVertices: # Decrease degrees by one (r[i], r[j]) = (r[i] -",
"graph c = 1 # the number of edge combinations for the same",
"use it as residual sequence r = deg_seq.copy() p = 1.0 # probability",
"empty or is not graphical if len(deg_seq) == 0 or is_graphical(deg_seq) is False:",
"{1,...,len(deg_seq}} :param deg_seq: Degree sequence :param num_of_samples: Number of samples which will be",
"= [] # list of edges N = len(r) # length of the",
"\" + str(time_elapsed) return 0.0, 0.0 weights = np.zeros(num_of_samples, dtype=float) for i in",
"edge sequences E.sort() return E, p, c def get_sample(deg_seq, num_of_samples, verbose=False): \"\"\" Generates",
"is empty or is not graphical if len(deg_seq) == 0 or is_graphical(deg_seq) is",
"E.append([i + 1, j + 1]) # indices start from 1 else: E.append([j",
"- time_start) if verbose is True: print \"Total computation time : \" +",
"return 0.0, 0.0 weights = np.zeros(num_of_samples, dtype=float) for i in range(num_of_samples): (edges, p,",
"possibleVertices = [o for o in np.arange(N) if (r[o] > 0 and o",
"(edges, p, c) = s(deg_seq) weights[i] = 1.0 / float(c * p) estimate",
"residual sequence r = deg_seq.copy() p = 1.0 # probability of the generated",
"while r[i] != 0: J = np.asarray([], dtype=np.int) # Construct candidate list J",
"computation time : \" + str(time_elapsed) return [] edges = [] for _",
"e, p, c = s(deg_seq) # Append the edges edges.append(e) # Get the",
"used in estimation :return estimation, std: Estimation for the number of graphs satisfying",
"r[j] - 1) p *= prob[J == j][0] # Sort the edge sequences",
"sequence r = deg_seq.copy() p = 1.0 # probability of the generated graph",
"# Add the found edge to the edge lists if i < j:",
"+ str(time_elapsed) return 0.0, 0.0 weights = np.zeros(num_of_samples, dtype=float) for i in range(num_of_samples):",
"p) estimate = (1.0 / float(num_of_samples)) * np.sum(weights) std = np.std(weights, ddof=1) #",
"in the candidate list J with probability proportional to its degree d_j degrees",
"than 0 i = np.where(r == np.amin(r[r > 0]))[0][-1] c *= factorial(r[i]) while",
"j) # Increase degrees by one (r[i], r[j]) = (r[i] + 1, r[j]",
"<gh_stars>0 from sacorg.utils import * from sacorg.algorithms.isgraphical import * def s(deg_seq): \"\"\" Generates",
"[] # list of edges N = len(r) # length of the sequence",
"= np.asarray([r[u] for u in J]) prob = degrees / float(np.sum(degrees)) j =",
"estimate = 0.0 # Get initial time time_start = time.clock() # If the",
"from 1 else: E.append([j + 1, i + 1]) # indices start from",
"is graphical if is_graphical(r): J = np.append(J, j) # Increase degrees by one",
"np.zeros(num_of_samples, dtype=float) for i in range(num_of_samples): (edges, p, c) = s(deg_seq) weights[i] =",
"str(time_elapsed) # Return the edges return edges def count(deg_seq, num_of_samples=1000, verbose=False): \"\"\" Estimates",
"starting from 1, probability of the generated graph and the number of edge",
"to candidate list J, if residual sequence is graphical if is_graphical(r): J =",
"of edge combinations \"\"\" # Copy the given degree sequence to use it",
"num_of_samples=1000, verbose=False): \"\"\" Estimates the number of graphs satisfying the degree sequence :param",
"= len(r) # length of the sequence adjacentVertices = [[] for _ in",
"np.arange(N) if (r[o] > 0 and o != i and (o not in",
"edges = [] for _ in range(num_of_samples): # Call the s function e,",
"sequences E.sort() return E, p, c def get_sample(deg_seq, num_of_samples, verbose=False): \"\"\" Generates graphs",
"= [[] for _ in range(N)] # stores the vertices which are adjacent",
"> 0 and o != i and (o not in adjacentVertices[i]))] for j",
"> 0]))[0][-1] c *= factorial(r[i]) while r[i] != 0: J = np.asarray([], dtype=np.int)",
"in order to not choose it again adjacentVertices[i].append(j) # Decrease degrees by 1",
"= 1.0 # probability of the generated graph c = 1 # the",
"the sequence adjacentVertices = [[] for _ in range(N)] # stores the vertices",
"+ str(time_elapsed) # Return the edges return edges def count(deg_seq, num_of_samples=1000, verbose=False): \"\"\"",
"is True: print \"Total computation time : \" + str(time_elapsed) # Return the",
"edge combinations for the same graph that can be generated by the algorithm",
"1 # the number of edge combinations for the same graph that can",
"Generates graphs realizing the degree sequence 'deg_seq' with vertex labels {1,...,len(deg_seq}} :param deg_seq:",
"becomes 0 vector while np.any(r != 0): # Get the index of vertex",
"by one (r[i], r[j]) = (r[i] + 1, r[j] + 1) # Pick",
"- 1, r[j] - 1) p *= prob[J == j][0] # Sort the",
"# Get the total computation time time_elapsed = (time.clock() - time_start) if verbose",
"= (time.clock() - time_start) if verbose is True: print \"Total computation time :",
"u in J]) prob = degrees / float(np.sum(degrees)) j = np.random.choice(J, p=prob, size=1)[0]",
"probability of the generated graph and the number of edge combinations \"\"\" #",
"computation time time_elapsed = (time.clock() - time_start) if verbose is True: print \"Total",
"'deg_seq' with vertex labels {1,...,len(deg_seq}} :param deg_seq: Degree sequence :param num_of_samples: Number of",
"True: print \"Total computation time : \" + str(time_elapsed) # Return the edges",
"the given degree sequence d and standard deviation \"\"\" estimate = 0.0 #",
"p, c def get_sample(deg_seq, num_of_samples, verbose=False): \"\"\" Generates graphs realizing the degree sequence",
"== j][0] # Sort the edge sequences E.sort() return E, p, c def",
"# Return the edges return edges def count(deg_seq, num_of_samples=1000, verbose=False): \"\"\" Estimates the",
"verbose=False): \"\"\" Generates graphs realizing the degree sequence 'deg_seq' with vertex labels {1,...,len(deg_seq}}",
"candidate list J, if residual sequence is graphical if is_graphical(r): J = np.append(J,",
"index of vertex having minimum degree greater than 0 i = np.where(r ==",
"# Get the total computation time time_elapsed = (time.clock() - time_start) print \"Total",
"adjacent # run until residual sequence completely becomes 0 vector while np.any(r !=",
"d :param deg_seq: Given degree sequence :return E, p, c: edges with vertex",
"sequence :return E, p, c: edges with vertex labels starting from 1, probability",
"\" + str(time_elapsed) # Return the edges return edges def count(deg_seq, num_of_samples=1000, verbose=False):",
"# Sort the edge sequences E.sort() return E, p, c def get_sample(deg_seq, num_of_samples,",
"# Add the chosen vertex to the list in order to not choose",
"[] edges = [] for _ in range(num_of_samples): # Call the s function",
"time.clock() # If the sequence is empty or is not graphical if len(deg_seq)",
"p, c: edges with vertex labels starting from 1, probability of the generated",
"1) # add the the vertex j to candidate list J, if residual",
"- 1) p *= prob[J == j][0] # Sort the edge sequences E.sort()",
"o != i and (o not in adjacentVertices[i]))] for j in possibleVertices: #",
"Add the chosen vertex to the list in order to not choose it",
"the degree sequence 'deg_seq' with vertex labels {1,...,len(deg_seq}} :param deg_seq: Degree sequence :param",
"== 0 or is_graphical(deg_seq) is False: if verbose is True: # Get the",
"\"Total computation time : \" + str(time_elapsed) # Return the edges return edges",
"function e, p, c = s(deg_seq) # Append the edges edges.append(e) # Get",
"of graphs satisfying the degree sequence :param deq_seq: Degree sequence :param num_of_samples: number",
"sequence to use it as residual sequence r = deg_seq.copy() p = 1.0",
"sample graph for a given degree sequence d :param deg_seq: Given degree sequence",
"# Pick a vertex j in the candidate list J with probability proportional",
"Estimates the number of graphs satisfying the degree sequence :param deq_seq: Degree sequence",
"realizing the degree sequence 'deg_seq' with vertex labels {1,...,len(deg_seq}} :param deg_seq: Degree sequence",
"# Increase degrees by one (r[i], r[j]) = (r[i] + 1, r[j] +",
"len(r) # length of the sequence adjacentVertices = [[] for _ in range(N)]",
"_ in range(N)] # stores the vertices which are adjacent # run until",
"Given degree sequence :return E, p, c: edges with vertex labels starting from",
"it again adjacentVertices[i].append(j) # Decrease degrees by 1 (r[i], r[j]) = (r[i] -",
"1 # Add the chosen vertex to the list in order to not",
"the generated graph c = 1 # the number of edge combinations for",
"is_graphical(deg_seq) is False: if verbose is True: # Get the total computation time",
"is True: # Get the total computation time time_elapsed = (time.clock() - time_start)",
"by 1 (r[i], r[j]) = (r[i] - 1, r[j] - 1) p *=",
"p *= prob[J == j][0] # Sort the edge sequences E.sort() return E,",
"= (r[i] - 1, r[j] - 1) p *= prob[J == j][0] #",
"Number of samples which will be generated :return: \"\"\" # Get the initial",
"the edge sequences E.sort() return E, p, c def get_sample(deg_seq, num_of_samples, verbose=False): \"\"\"",
"or is not graphical if len(deg_seq) == 0 or is_graphical(deg_seq) is False: if",
"i in range(num_of_samples): (edges, p, c) = s(deg_seq) weights[i] = 1.0 / float(c",
"a given degree sequence d :param deg_seq: Given degree sequence :return E, p,",
"the list in order to not choose it again adjacentVertices[i].append(j) # Decrease degrees",
":return E, p, c: edges with vertex labels starting from 1, probability of",
"vertex j in the candidate list J with probability proportional to its degree",
"sequence completely becomes 0 vector while np.any(r != 0): # Get the index",
"i and (o not in adjacentVertices[i]))] for j in possibleVertices: # Decrease degrees",
"vector while np.any(r != 0): # Get the index of vertex having minimum",
"verbose=False): \"\"\" Estimates the number of graphs satisfying the degree sequence :param deq_seq:",
"/ float(np.sum(degrees)) j = np.random.choice(J, p=prob, size=1)[0] # Add the found edge to",
"size=1)[0] # Add the found edge to the edge lists if i <",
"and standard deviation \"\"\" estimate = 0.0 # Get initial time time_start =",
"sequence d and standard deviation \"\"\" estimate = 0.0 # Get initial time",
"for j in possibleVertices: # Decrease degrees by one (r[i], r[j]) = (r[i]",
"adjacentVertices[i].append(j) # Decrease degrees by 1 (r[i], r[j]) = (r[i] - 1, r[j]",
"1, i + 1]) # indices start from 1 # Add the chosen",
"for _ in range(num_of_samples): # Call the s function e, p, c =",
"c) = s(deg_seq) weights[i] = 1.0 / float(c * p) estimate = (1.0",
"in range(num_of_samples): # Call the s function e, p, c = s(deg_seq) #",
"for a given degree sequence d :param deg_seq: Given degree sequence :return E,",
"prob = degrees / float(np.sum(degrees)) j = np.random.choice(J, p=prob, size=1)[0] # Add the",
"= s(deg_seq) weights[i] = 1.0 / float(c * p) estimate = (1.0 /",
"degree sequence to use it as residual sequence r = deg_seq.copy() p =",
"[[] for _ in range(N)] # stores the vertices which are adjacent #",
"else: E.append([j + 1, i + 1]) # indices start from 1 #",
":return: \"\"\" # Get the initial time time_start = time.clock() # If the",
"a sample graph for a given degree sequence d :param deg_seq: Given degree",
"ddof=1) # Get the total computation time time_elapsed = (time.clock() - time_start) if",
"1]) # indices start from 1 # Add the chosen vertex to the",
"False: if verbose is True: # Get the total computation time time_elapsed =",
"Call the s function e, p, c = s(deg_seq) # Append the edges",
":return estimation, std: Estimation for the number of graphs satisfying the given degree",
"!= 0: J = np.asarray([], dtype=np.int) # Construct candidate list J possibleVertices =",
"d and standard deviation \"\"\" estimate = 0.0 # Get initial time time_start",
"the vertices which are adjacent # run until residual sequence completely becomes 0",
"degree d_j degrees = np.asarray([r[u] for u in J]) prob = degrees /",
"str(time_elapsed) return 0.0, 0.0 weights = np.zeros(num_of_samples, dtype=float) for i in range(num_of_samples): (edges,",
"of graphs satisfying the given degree sequence d and standard deviation \"\"\" estimate",
"num_of_samples: number of samples used in estimation :return estimation, std: Estimation for the",
"sequence is graphical if is_graphical(r): J = np.append(J, j) # Increase degrees by",
"of the generated graph and the number of edge combinations \"\"\" # Copy",
"algorithm E = [] # list of edges N = len(r) # length",
"0 i = np.where(r == np.amin(r[r > 0]))[0][-1] c *= factorial(r[i]) while r[i]",
"# Decrease degrees by 1 (r[i], r[j]) = (r[i] - 1, r[j] -",
"degree sequence :param deq_seq: Degree sequence :param num_of_samples: number of samples used in",
"c: edges with vertex labels starting from 1, probability of the generated graph",
"[o for o in np.arange(N) if (r[o] > 0 and o != i",
"sequence :param num_of_samples: Number of samples which will be generated :return: \"\"\" #",
"sequence is empty or is not graphical if len(deg_seq) == 0 or is_graphical(deg_seq)",
"0.0 # Get initial time time_start = time.clock() # If the sequence is",
"s(deg_seq): \"\"\" Generates a sample graph for a given degree sequence d :param",
"J = np.asarray([], dtype=np.int) # Construct candidate list J possibleVertices = [o for",
"the same graph that can be generated by the algorithm E = []",
"0]))[0][-1] c *= factorial(r[i]) while r[i] != 0: J = np.asarray([], dtype=np.int) #",
"= 1 # the number of edge combinations for the same graph that",
"1]) # indices start from 1 else: E.append([j + 1, i + 1])",
"0 or is_graphical(deg_seq) is False: if verbose is True: # Get the total",
"True: # Get the total computation time time_elapsed = (time.clock() - time_start) print",
"not in adjacentVertices[i]))] for j in possibleVertices: # Decrease degrees by one (r[i],",
"\"\"\" # Copy the given degree sequence to use it as residual sequence",
"a vertex j in the candidate list J with probability proportional to its",
"E.append([j + 1, i + 1]) # indices start from 1 # Add",
"If the sequence is empty or is not graphical if len(deg_seq) == 0",
"the sequence is empty or is not graphical if len(deg_seq) == 0 or",
"the total computation time time_elapsed = (time.clock() - time_start) if verbose is True:",
"satisfying the given degree sequence d and standard deviation \"\"\" estimate = 0.0",
"dtype=float) for i in range(num_of_samples): (edges, p, c) = s(deg_seq) weights[i] = 1.0",
"it as residual sequence r = deg_seq.copy() p = 1.0 # probability of",
"J = np.append(J, j) # Increase degrees by one (r[i], r[j]) = (r[i]",
"deg_seq.copy() p = 1.0 # probability of the generated graph c = 1",
"r[j]) = (r[i] + 1, r[j] + 1) # Pick a vertex j"
] |
[
"Windows, builds of binutils based on Cygwin end lines with # \\n while",
"'--disassemble-all', '--disassemble-zeroes', '--insn-width=15', tmp.name], stdout=subprocess.PIPE, # On Windows, builds of binutils based on",
"be # found in the LICENSE file. import os import subprocess import sys",
"source code is governed by a BSD-style license that can be # found",
"of this source code is governed by a BSD-style license that can be",
"os import subprocess import sys import tempfile import objdump_parser import test_format class RdfaTestRunner(test_format.TestRunner):",
"rid of custom prefix once # https://code.google.com/p/nativeclient/issues/detail?id=3631 # is actually fixed. tmp =",
"stdout=subprocess.PIPE, # On Windows, builds of binutils based on Cygwin end lines with",
"TODO(shcherbina): get rid of custom prefix once # https://code.google.com/p/nativeclient/issues/detail?id=3631 # is actually fixed.",
"import test_format class RdfaTestRunner(test_format.TestRunner): SECTION_NAME = 'dis' def CommandLineOptions(self, parser): parser.add_option('--objdump', help='Path to",
"with # \\n while builds of binutils based on MinGW end lines with",
"# On Windows, builds of binutils based on Cygwin end lines with #",
"tmp = tempfile.NamedTemporaryFile( prefix='tmprdfa_', mode='wb', delete=False) try: tmp.write(data) tmp.close() objdump_proc = subprocess.Popen( [options.objdump,",
"import objdump_parser import test_format class RdfaTestRunner(test_format.TestRunner): SECTION_NAME = 'dis' def CommandLineOptions(self, parser): parser.add_option('--objdump',",
"import sys import tempfile import objdump_parser import test_format class RdfaTestRunner(test_format.TestRunner): SECTION_NAME = 'dis'",
"GetSectionContent(self, options, sections): arch = {32: '-Mi386', 64: '-Mx86-64'}[options.bits] data = ''.join(test_format.ParseHex(sections['hex'])) #",
"that can be # found in the LICENSE file. import os import subprocess",
"(c) 2013 The Native Client Authors. All rights reserved. # Use of this",
"2013 The Native Client Authors. All rights reserved. # Use of this source",
"help='Path to objdump') def GetSectionContent(self, options, sections): arch = {32: '-Mi386', 64: '-Mx86-64'}[options.bits]",
"this source code is governed by a BSD-style license that can be #",
"builds of binutils based on Cygwin end lines with # \\n while builds",
"builds of binutils based on MinGW end lines with \\r\\n. # The 'universal_newlines'",
"with either one. universal_newlines=True) result = ''.join(objdump_parser.SkipHeader(objdump_proc.stdout)) return_code = objdump_proc.wait() assert return_code ==",
"assert return_code == 0, 'error running objdump' finally: tmp.close() os.remove(tmp.name) return result def",
"arch, '--target=binary', '--disassemble-all', '--disassemble-zeroes', '--insn-width=15', tmp.name], stdout=subprocess.PIPE, # On Windows, builds of binutils",
"# Copyright (c) 2013 The Native Client Authors. All rights reserved. # Use",
"to objdump') def GetSectionContent(self, options, sections): arch = {32: '-Mi386', 64: '-Mx86-64'}[options.bits] data",
"with \\r\\n. # The 'universal_newlines' feature makes this work with either one. universal_newlines=True)",
"== 0, 'error running objdump' finally: tmp.close() os.remove(tmp.name) return result def main(argv): RdfaTestRunner().Run(argv)",
"tempfile.NamedTemporaryFile( prefix='tmprdfa_', mode='wb', delete=False) try: tmp.write(data) tmp.close() objdump_proc = subprocess.Popen( [options.objdump, '-mi386', arch,",
"\\n while builds of binutils based on MinGW end lines with \\r\\n. #",
"'universal_newlines' feature makes this work with either one. universal_newlines=True) result = ''.join(objdump_parser.SkipHeader(objdump_proc.stdout)) return_code",
"tempfile import objdump_parser import test_format class RdfaTestRunner(test_format.TestRunner): SECTION_NAME = 'dis' def CommandLineOptions(self, parser):",
"= 'dis' def CommandLineOptions(self, parser): parser.add_option('--objdump', help='Path to objdump') def GetSectionContent(self, options, sections):",
"0, 'error running objdump' finally: tmp.close() os.remove(tmp.name) return result def main(argv): RdfaTestRunner().Run(argv) if",
"def CommandLineOptions(self, parser): parser.add_option('--objdump', help='Path to objdump') def GetSectionContent(self, options, sections): arch =",
"# The 'universal_newlines' feature makes this work with either one. universal_newlines=True) result =",
"one. universal_newlines=True) result = ''.join(objdump_parser.SkipHeader(objdump_proc.stdout)) return_code = objdump_proc.wait() assert return_code == 0, 'error",
"the LICENSE file. import os import subprocess import sys import tempfile import objdump_parser",
"actually fixed. tmp = tempfile.NamedTemporaryFile( prefix='tmprdfa_', mode='wb', delete=False) try: tmp.write(data) tmp.close() objdump_proc =",
"'dis' def CommandLineOptions(self, parser): parser.add_option('--objdump', help='Path to objdump') def GetSectionContent(self, options, sections): arch",
"Cygwin end lines with # \\n while builds of binutils based on MinGW",
"can be # found in the LICENSE file. import os import subprocess import",
"# found in the LICENSE file. import os import subprocess import sys import",
"a BSD-style license that can be # found in the LICENSE file. import",
"MinGW end lines with \\r\\n. # The 'universal_newlines' feature makes this work with",
"lines with # \\n while builds of binutils based on MinGW end lines",
"import subprocess import sys import tempfile import objdump_parser import test_format class RdfaTestRunner(test_format.TestRunner): SECTION_NAME",
"'-mi386', arch, '--target=binary', '--disassemble-all', '--disassemble-zeroes', '--insn-width=15', tmp.name], stdout=subprocess.PIPE, # On Windows, builds of",
"[options.objdump, '-mi386', arch, '--target=binary', '--disassemble-all', '--disassemble-zeroes', '--insn-width=15', tmp.name], stdout=subprocess.PIPE, # On Windows, builds",
"binutils based on Cygwin end lines with # \\n while builds of binutils",
"# TODO(shcherbina): get rid of custom prefix once # https://code.google.com/p/nativeclient/issues/detail?id=3631 # is actually",
"<reponame>zipated/src #!/usr/bin/python # Copyright (c) 2013 The Native Client Authors. All rights reserved.",
"LICENSE file. import os import subprocess import sys import tempfile import objdump_parser import",
"custom prefix once # https://code.google.com/p/nativeclient/issues/detail?id=3631 # is actually fixed. tmp = tempfile.NamedTemporaryFile( prefix='tmprdfa_',",
"'-Mi386', 64: '-Mx86-64'}[options.bits] data = ''.join(test_format.ParseHex(sections['hex'])) # TODO(shcherbina): get rid of custom prefix",
"# is actually fixed. tmp = tempfile.NamedTemporaryFile( prefix='tmprdfa_', mode='wb', delete=False) try: tmp.write(data) tmp.close()",
"of binutils based on MinGW end lines with \\r\\n. # The 'universal_newlines' feature",
"return_code == 0, 'error running objdump' finally: tmp.close() os.remove(tmp.name) return result def main(argv):",
"Authors. All rights reserved. # Use of this source code is governed by",
"mode='wb', delete=False) try: tmp.write(data) tmp.close() objdump_proc = subprocess.Popen( [options.objdump, '-mi386', arch, '--target=binary', '--disassemble-all',",
"once # https://code.google.com/p/nativeclient/issues/detail?id=3631 # is actually fixed. tmp = tempfile.NamedTemporaryFile( prefix='tmprdfa_', mode='wb', delete=False)",
"Use of this source code is governed by a BSD-style license that can",
"= ''.join(test_format.ParseHex(sections['hex'])) # TODO(shcherbina): get rid of custom prefix once # https://code.google.com/p/nativeclient/issues/detail?id=3631 #",
"objdump' finally: tmp.close() os.remove(tmp.name) return result def main(argv): RdfaTestRunner().Run(argv) if __name__ == '__main__':",
"either one. universal_newlines=True) result = ''.join(objdump_parser.SkipHeader(objdump_proc.stdout)) return_code = objdump_proc.wait() assert return_code == 0,",
"binutils based on MinGW end lines with \\r\\n. # The 'universal_newlines' feature makes",
"BSD-style license that can be # found in the LICENSE file. import os",
"{32: '-Mi386', 64: '-Mx86-64'}[options.bits] data = ''.join(test_format.ParseHex(sections['hex'])) # TODO(shcherbina): get rid of custom",
"this work with either one. universal_newlines=True) result = ''.join(objdump_parser.SkipHeader(objdump_proc.stdout)) return_code = objdump_proc.wait() assert",
"= ''.join(objdump_parser.SkipHeader(objdump_proc.stdout)) return_code = objdump_proc.wait() assert return_code == 0, 'error running objdump' finally:",
"test_format class RdfaTestRunner(test_format.TestRunner): SECTION_NAME = 'dis' def CommandLineOptions(self, parser): parser.add_option('--objdump', help='Path to objdump')",
"tmp.close() objdump_proc = subprocess.Popen( [options.objdump, '-mi386', arch, '--target=binary', '--disassemble-all', '--disassemble-zeroes', '--insn-width=15', tmp.name], stdout=subprocess.PIPE,",
"'--insn-width=15', tmp.name], stdout=subprocess.PIPE, # On Windows, builds of binutils based on Cygwin end",
"in the LICENSE file. import os import subprocess import sys import tempfile import",
"'--disassemble-zeroes', '--insn-width=15', tmp.name], stdout=subprocess.PIPE, # On Windows, builds of binutils based on Cygwin",
"Native Client Authors. All rights reserved. # Use of this source code is",
"finally: tmp.close() os.remove(tmp.name) return result def main(argv): RdfaTestRunner().Run(argv) if __name__ == '__main__': main(sys.argv[1:])",
"code is governed by a BSD-style license that can be # found in",
"On Windows, builds of binutils based on Cygwin end lines with # \\n",
"on MinGW end lines with \\r\\n. # The 'universal_newlines' feature makes this work",
"result = ''.join(objdump_parser.SkipHeader(objdump_proc.stdout)) return_code = objdump_proc.wait() assert return_code == 0, 'error running objdump'",
"rights reserved. # Use of this source code is governed by a BSD-style",
"tmp.write(data) tmp.close() objdump_proc = subprocess.Popen( [options.objdump, '-mi386', arch, '--target=binary', '--disassemble-all', '--disassemble-zeroes', '--insn-width=15', tmp.name],",
"The 'universal_newlines' feature makes this work with either one. universal_newlines=True) result = ''.join(objdump_parser.SkipHeader(objdump_proc.stdout))",
"end lines with # \\n while builds of binutils based on MinGW end",
"objdump') def GetSectionContent(self, options, sections): arch = {32: '-Mi386', 64: '-Mx86-64'}[options.bits] data =",
"def GetSectionContent(self, options, sections): arch = {32: '-Mi386', 64: '-Mx86-64'}[options.bits] data = ''.join(test_format.ParseHex(sections['hex']))",
"= {32: '-Mi386', 64: '-Mx86-64'}[options.bits] data = ''.join(test_format.ParseHex(sections['hex'])) # TODO(shcherbina): get rid of",
"feature makes this work with either one. universal_newlines=True) result = ''.join(objdump_parser.SkipHeader(objdump_proc.stdout)) return_code =",
"get rid of custom prefix once # https://code.google.com/p/nativeclient/issues/detail?id=3631 # is actually fixed. tmp",
"Copyright (c) 2013 The Native Client Authors. All rights reserved. # Use of",
"parser.add_option('--objdump', help='Path to objdump') def GetSectionContent(self, options, sections): arch = {32: '-Mi386', 64:",
"# \\n while builds of binutils based on MinGW end lines with \\r\\n.",
"64: '-Mx86-64'}[options.bits] data = ''.join(test_format.ParseHex(sections['hex'])) # TODO(shcherbina): get rid of custom prefix once",
"All rights reserved. # Use of this source code is governed by a",
"by a BSD-style license that can be # found in the LICENSE file.",
"import tempfile import objdump_parser import test_format class RdfaTestRunner(test_format.TestRunner): SECTION_NAME = 'dis' def CommandLineOptions(self,",
"objdump_parser import test_format class RdfaTestRunner(test_format.TestRunner): SECTION_NAME = 'dis' def CommandLineOptions(self, parser): parser.add_option('--objdump', help='Path",
"#!/usr/bin/python # Copyright (c) 2013 The Native Client Authors. All rights reserved. #",
"= tempfile.NamedTemporaryFile( prefix='tmprdfa_', mode='wb', delete=False) try: tmp.write(data) tmp.close() objdump_proc = subprocess.Popen( [options.objdump, '-mi386',",
"is governed by a BSD-style license that can be # found in the",
"options, sections): arch = {32: '-Mi386', 64: '-Mx86-64'}[options.bits] data = ''.join(test_format.ParseHex(sections['hex'])) # TODO(shcherbina):",
"while builds of binutils based on MinGW end lines with \\r\\n. # The",
"sections): arch = {32: '-Mi386', 64: '-Mx86-64'}[options.bits] data = ''.join(test_format.ParseHex(sections['hex'])) # TODO(shcherbina): get",
"objdump_proc = subprocess.Popen( [options.objdump, '-mi386', arch, '--target=binary', '--disassemble-all', '--disassemble-zeroes', '--insn-width=15', tmp.name], stdout=subprocess.PIPE, #",
"on Cygwin end lines with # \\n while builds of binutils based on",
"governed by a BSD-style license that can be # found in the LICENSE",
"data = ''.join(test_format.ParseHex(sections['hex'])) # TODO(shcherbina): get rid of custom prefix once # https://code.google.com/p/nativeclient/issues/detail?id=3631",
"sys import tempfile import objdump_parser import test_format class RdfaTestRunner(test_format.TestRunner): SECTION_NAME = 'dis' def",
"parser): parser.add_option('--objdump', help='Path to objdump') def GetSectionContent(self, options, sections): arch = {32: '-Mi386',",
"= subprocess.Popen( [options.objdump, '-mi386', arch, '--target=binary', '--disassemble-all', '--disassemble-zeroes', '--insn-width=15', tmp.name], stdout=subprocess.PIPE, # On",
"reserved. # Use of this source code is governed by a BSD-style license",
"running objdump' finally: tmp.close() os.remove(tmp.name) return result def main(argv): RdfaTestRunner().Run(argv) if __name__ ==",
"delete=False) try: tmp.write(data) tmp.close() objdump_proc = subprocess.Popen( [options.objdump, '-mi386', arch, '--target=binary', '--disassemble-all', '--disassemble-zeroes',",
"of custom prefix once # https://code.google.com/p/nativeclient/issues/detail?id=3631 # is actually fixed. tmp = tempfile.NamedTemporaryFile(",
"# Use of this source code is governed by a BSD-style license that",
"class RdfaTestRunner(test_format.TestRunner): SECTION_NAME = 'dis' def CommandLineOptions(self, parser): parser.add_option('--objdump', help='Path to objdump') def",
"universal_newlines=True) result = ''.join(objdump_parser.SkipHeader(objdump_proc.stdout)) return_code = objdump_proc.wait() assert return_code == 0, 'error running",
"Client Authors. All rights reserved. # Use of this source code is governed",
"= objdump_proc.wait() assert return_code == 0, 'error running objdump' finally: tmp.close() os.remove(tmp.name) return",
"import os import subprocess import sys import tempfile import objdump_parser import test_format class",
"'-Mx86-64'}[options.bits] data = ''.join(test_format.ParseHex(sections['hex'])) # TODO(shcherbina): get rid of custom prefix once #",
"lines with \\r\\n. # The 'universal_newlines' feature makes this work with either one.",
"of binutils based on Cygwin end lines with # \\n while builds of",
"found in the LICENSE file. import os import subprocess import sys import tempfile",
"tmp.name], stdout=subprocess.PIPE, # On Windows, builds of binutils based on Cygwin end lines",
"# https://code.google.com/p/nativeclient/issues/detail?id=3631 # is actually fixed. tmp = tempfile.NamedTemporaryFile( prefix='tmprdfa_', mode='wb', delete=False) try:",
"RdfaTestRunner(test_format.TestRunner): SECTION_NAME = 'dis' def CommandLineOptions(self, parser): parser.add_option('--objdump', help='Path to objdump') def GetSectionContent(self,",
"''.join(objdump_parser.SkipHeader(objdump_proc.stdout)) return_code = objdump_proc.wait() assert return_code == 0, 'error running objdump' finally: tmp.close()",
"fixed. tmp = tempfile.NamedTemporaryFile( prefix='tmprdfa_', mode='wb', delete=False) try: tmp.write(data) tmp.close() objdump_proc = subprocess.Popen(",
"based on Cygwin end lines with # \\n while builds of binutils based",
"return_code = objdump_proc.wait() assert return_code == 0, 'error running objdump' finally: tmp.close() os.remove(tmp.name)",
"SECTION_NAME = 'dis' def CommandLineOptions(self, parser): parser.add_option('--objdump', help='Path to objdump') def GetSectionContent(self, options,",
"prefix='tmprdfa_', mode='wb', delete=False) try: tmp.write(data) tmp.close() objdump_proc = subprocess.Popen( [options.objdump, '-mi386', arch, '--target=binary',",
"prefix once # https://code.google.com/p/nativeclient/issues/detail?id=3631 # is actually fixed. tmp = tempfile.NamedTemporaryFile( prefix='tmprdfa_', mode='wb',",
"\\r\\n. # The 'universal_newlines' feature makes this work with either one. universal_newlines=True) result",
"subprocess import sys import tempfile import objdump_parser import test_format class RdfaTestRunner(test_format.TestRunner): SECTION_NAME =",
"https://code.google.com/p/nativeclient/issues/detail?id=3631 # is actually fixed. tmp = tempfile.NamedTemporaryFile( prefix='tmprdfa_', mode='wb', delete=False) try: tmp.write(data)",
"CommandLineOptions(self, parser): parser.add_option('--objdump', help='Path to objdump') def GetSectionContent(self, options, sections): arch = {32:",
"subprocess.Popen( [options.objdump, '-mi386', arch, '--target=binary', '--disassemble-all', '--disassemble-zeroes', '--insn-width=15', tmp.name], stdout=subprocess.PIPE, # On Windows,",
"license that can be # found in the LICENSE file. import os import",
"file. import os import subprocess import sys import tempfile import objdump_parser import test_format",
"try: tmp.write(data) tmp.close() objdump_proc = subprocess.Popen( [options.objdump, '-mi386', arch, '--target=binary', '--disassemble-all', '--disassemble-zeroes', '--insn-width=15',",
"based on MinGW end lines with \\r\\n. # The 'universal_newlines' feature makes this",
"'error running objdump' finally: tmp.close() os.remove(tmp.name) return result def main(argv): RdfaTestRunner().Run(argv) if __name__",
"The Native Client Authors. All rights reserved. # Use of this source code",
"objdump_proc.wait() assert return_code == 0, 'error running objdump' finally: tmp.close() os.remove(tmp.name) return result",
"'--target=binary', '--disassemble-all', '--disassemble-zeroes', '--insn-width=15', tmp.name], stdout=subprocess.PIPE, # On Windows, builds of binutils based",
"arch = {32: '-Mi386', 64: '-Mx86-64'}[options.bits] data = ''.join(test_format.ParseHex(sections['hex'])) # TODO(shcherbina): get rid",
"''.join(test_format.ParseHex(sections['hex'])) # TODO(shcherbina): get rid of custom prefix once # https://code.google.com/p/nativeclient/issues/detail?id=3631 # is",
"is actually fixed. tmp = tempfile.NamedTemporaryFile( prefix='tmprdfa_', mode='wb', delete=False) try: tmp.write(data) tmp.close() objdump_proc",
"end lines with \\r\\n. # The 'universal_newlines' feature makes this work with either",
"work with either one. universal_newlines=True) result = ''.join(objdump_parser.SkipHeader(objdump_proc.stdout)) return_code = objdump_proc.wait() assert return_code",
"makes this work with either one. universal_newlines=True) result = ''.join(objdump_parser.SkipHeader(objdump_proc.stdout)) return_code = objdump_proc.wait()"
] |
[
"if people < dogs: print(f'The world is dry') dogs += 5 if people",
"world is dry') dogs += 5 if people >= dogs: print(f'people are greater",
"if people > cats: print(f'Not many cats! The world is saved') if people",
"print(f'Too many Cats! The world is doomed!') if people > cats: print(f'Not many",
"dogs += 5 if people >= dogs: print(f'people are greater than or equal",
"saved') if people > dogs: print(f'The world is drooled on') if people <",
"+= 5 if people >= dogs: print(f'people are greater than or equal to",
"cats: print(f'Not many cats! The world is saved') if people > dogs: print(f'The",
"= 15 if people < cats: print(f'Too many Cats! The world is doomed!')",
"print(f'The world is drooled on') if people < dogs: print(f'The world is dry')",
"5 if people >= dogs: print(f'people are greater than or equal to dogs')",
"people = 20 cats = 30 dogs = 15 if people < cats:",
"many cats! The world is saved') if people > dogs: print(f'The world is",
"< dogs: print(f'The world is dry') dogs += 5 if people >= dogs:",
"people <= dogs: print(f'people are less than or equal to dogs') if people",
"The world is doomed!') if people > cats: print(f'Not many cats! The world",
"The world is saved') if people > dogs: print(f'The world is drooled on')",
"dogs: print(f'The world is drooled on') if people < dogs: print(f'The world is",
"> cats: print(f'Not many cats! The world is saved') if people > dogs:",
"dogs: print(f'The world is dry') dogs += 5 if people >= dogs: print(f'people",
"equal to dogs') if people <= dogs: print(f'people are less than or equal",
"less than or equal to dogs') if people == dogs: print(f'people are dogs.')",
"30 dogs = 15 if people < cats: print(f'Too many Cats! The world",
"dogs = 15 if people < cats: print(f'Too many Cats! The world is",
"< cats: print(f'Too many Cats! The world is doomed!') if people > cats:",
"<= dogs: print(f'people are less than or equal to dogs') if people ==",
"is dry') dogs += 5 if people >= dogs: print(f'people are greater than",
"world is saved') if people > dogs: print(f'The world is drooled on') if",
"are greater than or equal to dogs') if people <= dogs: print(f'people are",
"than or equal to dogs') if people <= dogs: print(f'people are less than",
"doomed!') if people > cats: print(f'Not many cats! The world is saved') if",
"15 if people < cats: print(f'Too many Cats! The world is doomed!') if",
"<gh_stars>1-10 people = 20 cats = 30 dogs = 15 if people <",
"if people >= dogs: print(f'people are greater than or equal to dogs') if",
"print(f'Not many cats! The world is saved') if people > dogs: print(f'The world",
"dogs') if people <= dogs: print(f'people are less than or equal to dogs')",
"if people <= dogs: print(f'people are less than or equal to dogs') if",
"people < cats: print(f'Too many Cats! The world is doomed!') if people >",
"print(f'people are less than or equal to dogs') if people == dogs: print(f'people",
"cats = 30 dogs = 15 if people < cats: print(f'Too many Cats!",
"if people > dogs: print(f'The world is drooled on') if people < dogs:",
"20 cats = 30 dogs = 15 if people < cats: print(f'Too many",
"> dogs: print(f'The world is drooled on') if people < dogs: print(f'The world",
"world is drooled on') if people < dogs: print(f'The world is dry') dogs",
"greater than or equal to dogs') if people <= dogs: print(f'people are less",
"is doomed!') if people > cats: print(f'Not many cats! The world is saved')",
"Cats! The world is doomed!') if people > cats: print(f'Not many cats! The",
"is drooled on') if people < dogs: print(f'The world is dry') dogs +=",
"cats: print(f'Too many Cats! The world is doomed!') if people > cats: print(f'Not",
"people >= dogs: print(f'people are greater than or equal to dogs') if people",
"people > dogs: print(f'The world is drooled on') if people < dogs: print(f'The",
"many Cats! The world is doomed!') if people > cats: print(f'Not many cats!",
"is saved') if people > dogs: print(f'The world is drooled on') if people",
"dogs: print(f'people are greater than or equal to dogs') if people <= dogs:",
"print(f'The world is dry') dogs += 5 if people >= dogs: print(f'people are",
">= dogs: print(f'people are greater than or equal to dogs') if people <=",
"print(f'people are greater than or equal to dogs') if people <= dogs: print(f'people",
"are less than or equal to dogs') if people == dogs: print(f'people are",
"= 20 cats = 30 dogs = 15 if people < cats: print(f'Too",
"= 30 dogs = 15 if people < cats: print(f'Too many Cats! The",
"people > cats: print(f'Not many cats! The world is saved') if people >",
"world is doomed!') if people > cats: print(f'Not many cats! The world is",
"on') if people < dogs: print(f'The world is dry') dogs += 5 if",
"dry') dogs += 5 if people >= dogs: print(f'people are greater than or",
"people < dogs: print(f'The world is dry') dogs += 5 if people >=",
"or equal to dogs') if people <= dogs: print(f'people are less than or",
"to dogs') if people <= dogs: print(f'people are less than or equal to",
"dogs: print(f'people are less than or equal to dogs') if people == dogs:",
"if people < cats: print(f'Too many Cats! The world is doomed!') if people",
"cats! The world is saved') if people > dogs: print(f'The world is drooled",
"drooled on') if people < dogs: print(f'The world is dry') dogs += 5"
] |
[
"options.config_path) elif options.task_name == TaskName.PC_Classify_Task: train_task.pc_classify_train(options.model, 0, options.config_path) print(\"process end!\") if __name__ ==",
"cfg_path) def pc_classify_train(self, cfg_path, gpu_id, config_path): pc_cls_train_task = PointCloudClassifyTrain(cfg_path, gpu_id, config_path) pc_cls_train_task.load_pretrain_model(self.pretrain_model_path) pc_cls_train_task.train(self.train_path,",
"__init__(self, train_path, val_path, pretrain_model_path, is_convert=False): self.train_path = train_path self.val_path = val_path self.pretrain_model_path =",
"== TaskName.Detect2d_Task: train_task.detect2d_train(options.model, 0, options.config_path) elif options.task_name == TaskName.Segment_Task: train_task.segment_train(options.model, 0, options.config_path) elif",
"image_model_convert(self, train_task, cfg_path): if self.is_convert: converter = ModelConverter(train_task.train_task_config.image_size) converter.model_convert(cfg_path, train_task.train_task_config.best_weights_file, train_task.train_task_config.snapshot_path) def main():",
"def __init__(self, train_path, val_path, pretrain_model_path, is_convert=False): self.train_path = train_path self.val_path = val_path self.pretrain_model_path",
"ClassifyTrain from easyai.tasks.det2d.detect2d_train import Detection2dTrain from easyai.tasks.seg.segment_train import SegmentionTrain from easyai.tasks.pc_cls.pc_classify_train import PointCloudClassifyTrain",
"easyai.tasks.pc_cls.pc_classify_train import PointCloudClassifyTrain from easyai.tools.model_to_onnx import ModelConverter from easyai.base_name.task_name import TaskName class TrainTask():",
"pc_cls_train_task = PointCloudClassifyTrain(cfg_path, gpu_id, config_path) pc_cls_train_task.load_pretrain_model(self.pretrain_model_path) pc_cls_train_task.train(self.train_path, self.val_path) def image_model_convert(self, train_task, cfg_path): if",
"= is_convert def classify_train(self, cfg_path, gpu_id, config_path): cls_train_task = ClassifyTrain(cfg_path, gpu_id, config_path) cls_train_task.load_pretrain_model(self.pretrain_model_path)",
"import ClassifyTrain from easyai.tasks.det2d.detect2d_train import Detection2dTrain from easyai.tasks.seg.segment_train import SegmentionTrain from easyai.tasks.pc_cls.pc_classify_train import",
"train_task, cfg_path): if self.is_convert: converter = ModelConverter(train_task.train_task_config.image_size) converter.model_convert(cfg_path, train_task.train_task_config.best_weights_file, train_task.train_task_config.snapshot_path) def main(): print(\"process",
"Detection2dTrain(cfg_path, gpu_id, config_path) det2d_train.load_pretrain_model(self.pretrain_model_path) det2d_train.train(self.train_path, self.val_path) self.image_model_convert(det2d_train, cfg_path) def segment_train(self, cfg_path, gpu_id, config_path):",
"= TaskArgumentsParse.train_input_parse() train_task = TrainTask(options.trainPath, options.valPath, options.pretrainModel) if options.task_name == TaskName.Classify_Task: train_task.classify_train(options.model, 0,",
"-*- # Author: from easyai.helper.arguments_parse import TaskArgumentsParse from easyai.tasks.cls.classify_train import ClassifyTrain from easyai.tasks.det2d.detect2d_train",
"gpu_id, config_path) det2d_train.load_pretrain_model(self.pretrain_model_path) det2d_train.train(self.train_path, self.val_path) self.image_model_convert(det2d_train, cfg_path) def segment_train(self, cfg_path, gpu_id, config_path): seg_train",
"self.train_path = train_path self.val_path = val_path self.pretrain_model_path = pretrain_model_path self.is_convert = is_convert def",
"config_path): det2d_train = Detection2dTrain(cfg_path, gpu_id, config_path) det2d_train.load_pretrain_model(self.pretrain_model_path) det2d_train.train(self.train_path, self.val_path) self.image_model_convert(det2d_train, cfg_path) def segment_train(self,",
"elif options.task_name == TaskName.Detect2d_Task: train_task.detect2d_train(options.model, 0, options.config_path) elif options.task_name == TaskName.Segment_Task: train_task.segment_train(options.model, 0,",
"elif options.task_name == TaskName.PC_Classify_Task: train_task.pc_classify_train(options.model, 0, options.config_path) print(\"process end!\") if __name__ == '__main__':",
"= ModelConverter(train_task.train_task_config.image_size) converter.model_convert(cfg_path, train_task.train_task_config.best_weights_file, train_task.train_task_config.snapshot_path) def main(): print(\"process start...\") options = TaskArgumentsParse.train_input_parse() train_task",
"= val_path self.pretrain_model_path = pretrain_model_path self.is_convert = is_convert def classify_train(self, cfg_path, gpu_id, config_path):",
"options.valPath, options.pretrainModel) if options.task_name == TaskName.Classify_Task: train_task.classify_train(options.model, 0, options.config_path) elif options.task_name == TaskName.Detect2d_Task:",
"TrainTask(): def __init__(self, train_path, val_path, pretrain_model_path, is_convert=False): self.train_path = train_path self.val_path = val_path",
"TaskArgumentsParse.train_input_parse() train_task = TrainTask(options.trainPath, options.valPath, options.pretrainModel) if options.task_name == TaskName.Classify_Task: train_task.classify_train(options.model, 0, options.config_path)",
"cls_train_task.train(self.train_path, self.val_path) self.image_model_convert(cls_train_task, cfg_path) def detect2d_train(self, cfg_path, gpu_id, config_path): det2d_train = Detection2dTrain(cfg_path, gpu_id,",
"det2d_train.train(self.train_path, self.val_path) self.image_model_convert(det2d_train, cfg_path) def segment_train(self, cfg_path, gpu_id, config_path): seg_train = SegmentionTrain(cfg_path, gpu_id,",
"= pretrain_model_path self.is_convert = is_convert def classify_train(self, cfg_path, gpu_id, config_path): cls_train_task = ClassifyTrain(cfg_path,",
"options.config_path) elif options.task_name == TaskName.Segment_Task: train_task.segment_train(options.model, 0, options.config_path) elif options.task_name == TaskName.PC_Classify_Task: train_task.pc_classify_train(options.model,",
"self.is_convert = is_convert def classify_train(self, cfg_path, gpu_id, config_path): cls_train_task = ClassifyTrain(cfg_path, gpu_id, config_path)",
"det2d_train = Detection2dTrain(cfg_path, gpu_id, config_path) det2d_train.load_pretrain_model(self.pretrain_model_path) det2d_train.train(self.train_path, self.val_path) self.image_model_convert(det2d_train, cfg_path) def segment_train(self, cfg_path,",
"def main(): print(\"process start...\") options = TaskArgumentsParse.train_input_parse() train_task = TrainTask(options.trainPath, options.valPath, options.pretrainModel) if",
"segment_train(self, cfg_path, gpu_id, config_path): seg_train = SegmentionTrain(cfg_path, gpu_id, config_path) seg_train.load_pretrain_model(self.pretrain_model_path) seg_train.train(self.train_path, self.val_path) self.image_model_convert(seg_train,",
"Author: from easyai.helper.arguments_parse import TaskArgumentsParse from easyai.tasks.cls.classify_train import ClassifyTrain from easyai.tasks.det2d.detect2d_train import Detection2dTrain",
"cfg_path, gpu_id, config_path): pc_cls_train_task = PointCloudClassifyTrain(cfg_path, gpu_id, config_path) pc_cls_train_task.load_pretrain_model(self.pretrain_model_path) pc_cls_train_task.train(self.train_path, self.val_path) def image_model_convert(self,",
"= train_path self.val_path = val_path self.pretrain_model_path = pretrain_model_path self.is_convert = is_convert def classify_train(self,",
"config_path): seg_train = SegmentionTrain(cfg_path, gpu_id, config_path) seg_train.load_pretrain_model(self.pretrain_model_path) seg_train.train(self.train_path, self.val_path) self.image_model_convert(seg_train, cfg_path) def pc_classify_train(self,",
"config_path) seg_train.load_pretrain_model(self.pretrain_model_path) seg_train.train(self.train_path, self.val_path) self.image_model_convert(seg_train, cfg_path) def pc_classify_train(self, cfg_path, gpu_id, config_path): pc_cls_train_task =",
"coding:utf-8 -*- # Author: from easyai.helper.arguments_parse import TaskArgumentsParse from easyai.tasks.cls.classify_train import ClassifyTrain from",
"<reponame>lpj0822/image_point_cloud_det<gh_stars>1-10 #!/usr/bin/env python # -*- coding:utf-8 -*- # Author: from easyai.helper.arguments_parse import TaskArgumentsParse",
"main(): print(\"process start...\") options = TaskArgumentsParse.train_input_parse() train_task = TrainTask(options.trainPath, options.valPath, options.pretrainModel) if options.task_name",
"cfg_path, gpu_id, config_path): det2d_train = Detection2dTrain(cfg_path, gpu_id, config_path) det2d_train.load_pretrain_model(self.pretrain_model_path) det2d_train.train(self.train_path, self.val_path) self.image_model_convert(det2d_train, cfg_path)",
"-*- coding:utf-8 -*- # Author: from easyai.helper.arguments_parse import TaskArgumentsParse from easyai.tasks.cls.classify_train import ClassifyTrain",
"== TaskName.Segment_Task: train_task.segment_train(options.model, 0, options.config_path) elif options.task_name == TaskName.PC_Classify_Task: train_task.pc_classify_train(options.model, 0, options.config_path) print(\"process",
"from easyai.tasks.det2d.detect2d_train import Detection2dTrain from easyai.tasks.seg.segment_train import SegmentionTrain from easyai.tasks.pc_cls.pc_classify_train import PointCloudClassifyTrain from",
"det2d_train.load_pretrain_model(self.pretrain_model_path) det2d_train.train(self.train_path, self.val_path) self.image_model_convert(det2d_train, cfg_path) def segment_train(self, cfg_path, gpu_id, config_path): seg_train = SegmentionTrain(cfg_path,",
"seg_train = SegmentionTrain(cfg_path, gpu_id, config_path) seg_train.load_pretrain_model(self.pretrain_model_path) seg_train.train(self.train_path, self.val_path) self.image_model_convert(seg_train, cfg_path) def pc_classify_train(self, cfg_path,",
"import Detection2dTrain from easyai.tasks.seg.segment_train import SegmentionTrain from easyai.tasks.pc_cls.pc_classify_train import PointCloudClassifyTrain from easyai.tools.model_to_onnx import",
"self.val_path) self.image_model_convert(seg_train, cfg_path) def pc_classify_train(self, cfg_path, gpu_id, config_path): pc_cls_train_task = PointCloudClassifyTrain(cfg_path, gpu_id, config_path)",
"def pc_classify_train(self, cfg_path, gpu_id, config_path): pc_cls_train_task = PointCloudClassifyTrain(cfg_path, gpu_id, config_path) pc_cls_train_task.load_pretrain_model(self.pretrain_model_path) pc_cls_train_task.train(self.train_path, self.val_path)",
"options.task_name == TaskName.Detect2d_Task: train_task.detect2d_train(options.model, 0, options.config_path) elif options.task_name == TaskName.Segment_Task: train_task.segment_train(options.model, 0, options.config_path)",
"converter.model_convert(cfg_path, train_task.train_task_config.best_weights_file, train_task.train_task_config.snapshot_path) def main(): print(\"process start...\") options = TaskArgumentsParse.train_input_parse() train_task = TrainTask(options.trainPath,",
"train_task = TrainTask(options.trainPath, options.valPath, options.pretrainModel) if options.task_name == TaskName.Classify_Task: train_task.classify_train(options.model, 0, options.config_path) elif",
"gpu_id, config_path): seg_train = SegmentionTrain(cfg_path, gpu_id, config_path) seg_train.load_pretrain_model(self.pretrain_model_path) seg_train.train(self.train_path, self.val_path) self.image_model_convert(seg_train, cfg_path) def",
"self.image_model_convert(seg_train, cfg_path) def pc_classify_train(self, cfg_path, gpu_id, config_path): pc_cls_train_task = PointCloudClassifyTrain(cfg_path, gpu_id, config_path) pc_cls_train_task.load_pretrain_model(self.pretrain_model_path)",
"easyai.base_name.task_name import TaskName class TrainTask(): def __init__(self, train_path, val_path, pretrain_model_path, is_convert=False): self.train_path =",
"from easyai.tasks.pc_cls.pc_classify_train import PointCloudClassifyTrain from easyai.tools.model_to_onnx import ModelConverter from easyai.base_name.task_name import TaskName class",
"def image_model_convert(self, train_task, cfg_path): if self.is_convert: converter = ModelConverter(train_task.train_task_config.image_size) converter.model_convert(cfg_path, train_task.train_task_config.best_weights_file, train_task.train_task_config.snapshot_path) def",
"easyai.tasks.det2d.detect2d_train import Detection2dTrain from easyai.tasks.seg.segment_train import SegmentionTrain from easyai.tasks.pc_cls.pc_classify_train import PointCloudClassifyTrain from easyai.tools.model_to_onnx",
"gpu_id, config_path) cls_train_task.load_pretrain_model(self.pretrain_model_path) cls_train_task.train(self.train_path, self.val_path) self.image_model_convert(cls_train_task, cfg_path) def detect2d_train(self, cfg_path, gpu_id, config_path): det2d_train",
"= TrainTask(options.trainPath, options.valPath, options.pretrainModel) if options.task_name == TaskName.Classify_Task: train_task.classify_train(options.model, 0, options.config_path) elif options.task_name",
"== TaskName.Classify_Task: train_task.classify_train(options.model, 0, options.config_path) elif options.task_name == TaskName.Detect2d_Task: train_task.detect2d_train(options.model, 0, options.config_path) elif",
"class TrainTask(): def __init__(self, train_path, val_path, pretrain_model_path, is_convert=False): self.train_path = train_path self.val_path =",
"if self.is_convert: converter = ModelConverter(train_task.train_task_config.image_size) converter.model_convert(cfg_path, train_task.train_task_config.best_weights_file, train_task.train_task_config.snapshot_path) def main(): print(\"process start...\") options",
"val_path self.pretrain_model_path = pretrain_model_path self.is_convert = is_convert def classify_train(self, cfg_path, gpu_id, config_path): cls_train_task",
"options.config_path) elif options.task_name == TaskName.Detect2d_Task: train_task.detect2d_train(options.model, 0, options.config_path) elif options.task_name == TaskName.Segment_Task: train_task.segment_train(options.model,",
"start...\") options = TaskArgumentsParse.train_input_parse() train_task = TrainTask(options.trainPath, options.valPath, options.pretrainModel) if options.task_name == TaskName.Classify_Task:",
"from easyai.base_name.task_name import TaskName class TrainTask(): def __init__(self, train_path, val_path, pretrain_model_path, is_convert=False): self.train_path",
"TaskName.Detect2d_Task: train_task.detect2d_train(options.model, 0, options.config_path) elif options.task_name == TaskName.Segment_Task: train_task.segment_train(options.model, 0, options.config_path) elif options.task_name",
"print(\"process start...\") options = TaskArgumentsParse.train_input_parse() train_task = TrainTask(options.trainPath, options.valPath, options.pretrainModel) if options.task_name ==",
"PointCloudClassifyTrain(cfg_path, gpu_id, config_path) pc_cls_train_task.load_pretrain_model(self.pretrain_model_path) pc_cls_train_task.train(self.train_path, self.val_path) def image_model_convert(self, train_task, cfg_path): if self.is_convert: converter",
"TrainTask(options.trainPath, options.valPath, options.pretrainModel) if options.task_name == TaskName.Classify_Task: train_task.classify_train(options.model, 0, options.config_path) elif options.task_name ==",
"easyai.helper.arguments_parse import TaskArgumentsParse from easyai.tasks.cls.classify_train import ClassifyTrain from easyai.tasks.det2d.detect2d_train import Detection2dTrain from easyai.tasks.seg.segment_train",
"TaskName.Segment_Task: train_task.segment_train(options.model, 0, options.config_path) elif options.task_name == TaskName.PC_Classify_Task: train_task.pc_classify_train(options.model, 0, options.config_path) print(\"process end!\")",
"TaskName class TrainTask(): def __init__(self, train_path, val_path, pretrain_model_path, is_convert=False): self.train_path = train_path self.val_path",
"self.val_path) self.image_model_convert(det2d_train, cfg_path) def segment_train(self, cfg_path, gpu_id, config_path): seg_train = SegmentionTrain(cfg_path, gpu_id, config_path)",
"cfg_path) def segment_train(self, cfg_path, gpu_id, config_path): seg_train = SegmentionTrain(cfg_path, gpu_id, config_path) seg_train.load_pretrain_model(self.pretrain_model_path) seg_train.train(self.train_path,",
"TaskName.Classify_Task: train_task.classify_train(options.model, 0, options.config_path) elif options.task_name == TaskName.Detect2d_Task: train_task.detect2d_train(options.model, 0, options.config_path) elif options.task_name",
"if options.task_name == TaskName.Classify_Task: train_task.classify_train(options.model, 0, options.config_path) elif options.task_name == TaskName.Detect2d_Task: train_task.detect2d_train(options.model, 0,",
"import SegmentionTrain from easyai.tasks.pc_cls.pc_classify_train import PointCloudClassifyTrain from easyai.tools.model_to_onnx import ModelConverter from easyai.base_name.task_name import",
"elif options.task_name == TaskName.Segment_Task: train_task.segment_train(options.model, 0, options.config_path) elif options.task_name == TaskName.PC_Classify_Task: train_task.pc_classify_train(options.model, 0,",
"train_path self.val_path = val_path self.pretrain_model_path = pretrain_model_path self.is_convert = is_convert def classify_train(self, cfg_path,",
"= Detection2dTrain(cfg_path, gpu_id, config_path) det2d_train.load_pretrain_model(self.pretrain_model_path) det2d_train.train(self.train_path, self.val_path) self.image_model_convert(det2d_train, cfg_path) def segment_train(self, cfg_path, gpu_id,",
"train_task.segment_train(options.model, 0, options.config_path) elif options.task_name == TaskName.PC_Classify_Task: train_task.pc_classify_train(options.model, 0, options.config_path) print(\"process end!\") if",
"train_path, val_path, pretrain_model_path, is_convert=False): self.train_path = train_path self.val_path = val_path self.pretrain_model_path = pretrain_model_path",
"train_task.train_task_config.best_weights_file, train_task.train_task_config.snapshot_path) def main(): print(\"process start...\") options = TaskArgumentsParse.train_input_parse() train_task = TrainTask(options.trainPath, options.valPath,",
"def segment_train(self, cfg_path, gpu_id, config_path): seg_train = SegmentionTrain(cfg_path, gpu_id, config_path) seg_train.load_pretrain_model(self.pretrain_model_path) seg_train.train(self.train_path, self.val_path)",
"cfg_path, gpu_id, config_path): cls_train_task = ClassifyTrain(cfg_path, gpu_id, config_path) cls_train_task.load_pretrain_model(self.pretrain_model_path) cls_train_task.train(self.train_path, self.val_path) self.image_model_convert(cls_train_task, cfg_path)",
"ModelConverter(train_task.train_task_config.image_size) converter.model_convert(cfg_path, train_task.train_task_config.best_weights_file, train_task.train_task_config.snapshot_path) def main(): print(\"process start...\") options = TaskArgumentsParse.train_input_parse() train_task =",
"python # -*- coding:utf-8 -*- # Author: from easyai.helper.arguments_parse import TaskArgumentsParse from easyai.tasks.cls.classify_train",
"pc_classify_train(self, cfg_path, gpu_id, config_path): pc_cls_train_task = PointCloudClassifyTrain(cfg_path, gpu_id, config_path) pc_cls_train_task.load_pretrain_model(self.pretrain_model_path) pc_cls_train_task.train(self.train_path, self.val_path) def",
"easyai.tools.model_to_onnx import ModelConverter from easyai.base_name.task_name import TaskName class TrainTask(): def __init__(self, train_path, val_path,",
"seg_train.load_pretrain_model(self.pretrain_model_path) seg_train.train(self.train_path, self.val_path) self.image_model_convert(seg_train, cfg_path) def pc_classify_train(self, cfg_path, gpu_id, config_path): pc_cls_train_task = PointCloudClassifyTrain(cfg_path,",
"0, options.config_path) elif options.task_name == TaskName.Segment_Task: train_task.segment_train(options.model, 0, options.config_path) elif options.task_name == TaskName.PC_Classify_Task:",
"options.task_name == TaskName.PC_Classify_Task: train_task.pc_classify_train(options.model, 0, options.config_path) print(\"process end!\") if __name__ == '__main__': main()",
"def classify_train(self, cfg_path, gpu_id, config_path): cls_train_task = ClassifyTrain(cfg_path, gpu_id, config_path) cls_train_task.load_pretrain_model(self.pretrain_model_path) cls_train_task.train(self.train_path, self.val_path)",
"cfg_path, gpu_id, config_path): seg_train = SegmentionTrain(cfg_path, gpu_id, config_path) seg_train.load_pretrain_model(self.pretrain_model_path) seg_train.train(self.train_path, self.val_path) self.image_model_convert(seg_train, cfg_path)",
"options.task_name == TaskName.Segment_Task: train_task.segment_train(options.model, 0, options.config_path) elif options.task_name == TaskName.PC_Classify_Task: train_task.pc_classify_train(options.model, 0, options.config_path)",
"seg_train.train(self.train_path, self.val_path) self.image_model_convert(seg_train, cfg_path) def pc_classify_train(self, cfg_path, gpu_id, config_path): pc_cls_train_task = PointCloudClassifyTrain(cfg_path, gpu_id,",
"# -*- coding:utf-8 -*- # Author: from easyai.helper.arguments_parse import TaskArgumentsParse from easyai.tasks.cls.classify_train import",
"self.pretrain_model_path = pretrain_model_path self.is_convert = is_convert def classify_train(self, cfg_path, gpu_id, config_path): cls_train_task =",
"config_path): pc_cls_train_task = PointCloudClassifyTrain(cfg_path, gpu_id, config_path) pc_cls_train_task.load_pretrain_model(self.pretrain_model_path) pc_cls_train_task.train(self.train_path, self.val_path) def image_model_convert(self, train_task, cfg_path):",
"from easyai.helper.arguments_parse import TaskArgumentsParse from easyai.tasks.cls.classify_train import ClassifyTrain from easyai.tasks.det2d.detect2d_train import Detection2dTrain from",
"config_path) det2d_train.load_pretrain_model(self.pretrain_model_path) det2d_train.train(self.train_path, self.val_path) self.image_model_convert(det2d_train, cfg_path) def segment_train(self, cfg_path, gpu_id, config_path): seg_train =",
"cfg_path) def detect2d_train(self, cfg_path, gpu_id, config_path): det2d_train = Detection2dTrain(cfg_path, gpu_id, config_path) det2d_train.load_pretrain_model(self.pretrain_model_path) det2d_train.train(self.train_path,",
"config_path) pc_cls_train_task.load_pretrain_model(self.pretrain_model_path) pc_cls_train_task.train(self.train_path, self.val_path) def image_model_convert(self, train_task, cfg_path): if self.is_convert: converter = ModelConverter(train_task.train_task_config.image_size)",
"import TaskArgumentsParse from easyai.tasks.cls.classify_train import ClassifyTrain from easyai.tasks.det2d.detect2d_train import Detection2dTrain from easyai.tasks.seg.segment_train import",
"SegmentionTrain from easyai.tasks.pc_cls.pc_classify_train import PointCloudClassifyTrain from easyai.tools.model_to_onnx import ModelConverter from easyai.base_name.task_name import TaskName",
"classify_train(self, cfg_path, gpu_id, config_path): cls_train_task = ClassifyTrain(cfg_path, gpu_id, config_path) cls_train_task.load_pretrain_model(self.pretrain_model_path) cls_train_task.train(self.train_path, self.val_path) self.image_model_convert(cls_train_task,",
"pc_cls_train_task.train(self.train_path, self.val_path) def image_model_convert(self, train_task, cfg_path): if self.is_convert: converter = ModelConverter(train_task.train_task_config.image_size) converter.model_convert(cfg_path, train_task.train_task_config.best_weights_file,",
"options.task_name == TaskName.Classify_Task: train_task.classify_train(options.model, 0, options.config_path) elif options.task_name == TaskName.Detect2d_Task: train_task.detect2d_train(options.model, 0, options.config_path)",
"import PointCloudClassifyTrain from easyai.tools.model_to_onnx import ModelConverter from easyai.base_name.task_name import TaskName class TrainTask(): def",
"options = TaskArgumentsParse.train_input_parse() train_task = TrainTask(options.trainPath, options.valPath, options.pretrainModel) if options.task_name == TaskName.Classify_Task: train_task.classify_train(options.model,",
"import TaskName class TrainTask(): def __init__(self, train_path, val_path, pretrain_model_path, is_convert=False): self.train_path = train_path",
"= PointCloudClassifyTrain(cfg_path, gpu_id, config_path) pc_cls_train_task.load_pretrain_model(self.pretrain_model_path) pc_cls_train_task.train(self.train_path, self.val_path) def image_model_convert(self, train_task, cfg_path): if self.is_convert:",
"cls_train_task = ClassifyTrain(cfg_path, gpu_id, config_path) cls_train_task.load_pretrain_model(self.pretrain_model_path) cls_train_task.train(self.train_path, self.val_path) self.image_model_convert(cls_train_task, cfg_path) def detect2d_train(self, cfg_path,",
"config_path): cls_train_task = ClassifyTrain(cfg_path, gpu_id, config_path) cls_train_task.load_pretrain_model(self.pretrain_model_path) cls_train_task.train(self.train_path, self.val_path) self.image_model_convert(cls_train_task, cfg_path) def detect2d_train(self,",
"val_path, pretrain_model_path, is_convert=False): self.train_path = train_path self.val_path = val_path self.pretrain_model_path = pretrain_model_path self.is_convert",
"pretrain_model_path, is_convert=False): self.train_path = train_path self.val_path = val_path self.pretrain_model_path = pretrain_model_path self.is_convert =",
"0, options.config_path) elif options.task_name == TaskName.Detect2d_Task: train_task.detect2d_train(options.model, 0, options.config_path) elif options.task_name == TaskName.Segment_Task:",
"0, options.config_path) elif options.task_name == TaskName.PC_Classify_Task: train_task.pc_classify_train(options.model, 0, options.config_path) print(\"process end!\") if __name__",
"from easyai.tools.model_to_onnx import ModelConverter from easyai.base_name.task_name import TaskName class TrainTask(): def __init__(self, train_path,",
"self.image_model_convert(cls_train_task, cfg_path) def detect2d_train(self, cfg_path, gpu_id, config_path): det2d_train = Detection2dTrain(cfg_path, gpu_id, config_path) det2d_train.load_pretrain_model(self.pretrain_model_path)",
"self.image_model_convert(det2d_train, cfg_path) def segment_train(self, cfg_path, gpu_id, config_path): seg_train = SegmentionTrain(cfg_path, gpu_id, config_path) seg_train.load_pretrain_model(self.pretrain_model_path)",
"self.is_convert: converter = ModelConverter(train_task.train_task_config.image_size) converter.model_convert(cfg_path, train_task.train_task_config.best_weights_file, train_task.train_task_config.snapshot_path) def main(): print(\"process start...\") options =",
"TaskArgumentsParse from easyai.tasks.cls.classify_train import ClassifyTrain from easyai.tasks.det2d.detect2d_train import Detection2dTrain from easyai.tasks.seg.segment_train import SegmentionTrain",
"pc_cls_train_task.load_pretrain_model(self.pretrain_model_path) pc_cls_train_task.train(self.train_path, self.val_path) def image_model_convert(self, train_task, cfg_path): if self.is_convert: converter = ModelConverter(train_task.train_task_config.image_size) converter.model_convert(cfg_path,",
"train_task.classify_train(options.model, 0, options.config_path) elif options.task_name == TaskName.Detect2d_Task: train_task.detect2d_train(options.model, 0, options.config_path) elif options.task_name ==",
"from easyai.tasks.seg.segment_train import SegmentionTrain from easyai.tasks.pc_cls.pc_classify_train import PointCloudClassifyTrain from easyai.tools.model_to_onnx import ModelConverter from",
"gpu_id, config_path) seg_train.load_pretrain_model(self.pretrain_model_path) seg_train.train(self.train_path, self.val_path) self.image_model_convert(seg_train, cfg_path) def pc_classify_train(self, cfg_path, gpu_id, config_path): pc_cls_train_task",
"gpu_id, config_path): cls_train_task = ClassifyTrain(cfg_path, gpu_id, config_path) cls_train_task.load_pretrain_model(self.pretrain_model_path) cls_train_task.train(self.train_path, self.val_path) self.image_model_convert(cls_train_task, cfg_path) def",
"config_path) cls_train_task.load_pretrain_model(self.pretrain_model_path) cls_train_task.train(self.train_path, self.val_path) self.image_model_convert(cls_train_task, cfg_path) def detect2d_train(self, cfg_path, gpu_id, config_path): det2d_train =",
"is_convert=False): self.train_path = train_path self.val_path = val_path self.pretrain_model_path = pretrain_model_path self.is_convert = is_convert",
"pretrain_model_path self.is_convert = is_convert def classify_train(self, cfg_path, gpu_id, config_path): cls_train_task = ClassifyTrain(cfg_path, gpu_id,",
"gpu_id, config_path): det2d_train = Detection2dTrain(cfg_path, gpu_id, config_path) det2d_train.load_pretrain_model(self.pretrain_model_path) det2d_train.train(self.train_path, self.val_path) self.image_model_convert(det2d_train, cfg_path) def",
"self.val_path) def image_model_convert(self, train_task, cfg_path): if self.is_convert: converter = ModelConverter(train_task.train_task_config.image_size) converter.model_convert(cfg_path, train_task.train_task_config.best_weights_file, train_task.train_task_config.snapshot_path)",
"easyai.tasks.cls.classify_train import ClassifyTrain from easyai.tasks.det2d.detect2d_train import Detection2dTrain from easyai.tasks.seg.segment_train import SegmentionTrain from easyai.tasks.pc_cls.pc_classify_train",
"#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: from easyai.helper.arguments_parse import TaskArgumentsParse from",
"self.val_path = val_path self.pretrain_model_path = pretrain_model_path self.is_convert = is_convert def classify_train(self, cfg_path, gpu_id,",
"easyai.tasks.seg.segment_train import SegmentionTrain from easyai.tasks.pc_cls.pc_classify_train import PointCloudClassifyTrain from easyai.tools.model_to_onnx import ModelConverter from easyai.base_name.task_name",
"# Author: from easyai.helper.arguments_parse import TaskArgumentsParse from easyai.tasks.cls.classify_train import ClassifyTrain from easyai.tasks.det2d.detect2d_train import",
"SegmentionTrain(cfg_path, gpu_id, config_path) seg_train.load_pretrain_model(self.pretrain_model_path) seg_train.train(self.train_path, self.val_path) self.image_model_convert(seg_train, cfg_path) def pc_classify_train(self, cfg_path, gpu_id, config_path):",
"ModelConverter from easyai.base_name.task_name import TaskName class TrainTask(): def __init__(self, train_path, val_path, pretrain_model_path, is_convert=False):",
"= ClassifyTrain(cfg_path, gpu_id, config_path) cls_train_task.load_pretrain_model(self.pretrain_model_path) cls_train_task.train(self.train_path, self.val_path) self.image_model_convert(cls_train_task, cfg_path) def detect2d_train(self, cfg_path, gpu_id,",
"options.pretrainModel) if options.task_name == TaskName.Classify_Task: train_task.classify_train(options.model, 0, options.config_path) elif options.task_name == TaskName.Detect2d_Task: train_task.detect2d_train(options.model,",
"converter = ModelConverter(train_task.train_task_config.image_size) converter.model_convert(cfg_path, train_task.train_task_config.best_weights_file, train_task.train_task_config.snapshot_path) def main(): print(\"process start...\") options = TaskArgumentsParse.train_input_parse()",
"from easyai.tasks.cls.classify_train import ClassifyTrain from easyai.tasks.det2d.detect2d_train import Detection2dTrain from easyai.tasks.seg.segment_train import SegmentionTrain from",
"self.val_path) self.image_model_convert(cls_train_task, cfg_path) def detect2d_train(self, cfg_path, gpu_id, config_path): det2d_train = Detection2dTrain(cfg_path, gpu_id, config_path)",
"PointCloudClassifyTrain from easyai.tools.model_to_onnx import ModelConverter from easyai.base_name.task_name import TaskName class TrainTask(): def __init__(self,",
"train_task.train_task_config.snapshot_path) def main(): print(\"process start...\") options = TaskArgumentsParse.train_input_parse() train_task = TrainTask(options.trainPath, options.valPath, options.pretrainModel)",
"cfg_path): if self.is_convert: converter = ModelConverter(train_task.train_task_config.image_size) converter.model_convert(cfg_path, train_task.train_task_config.best_weights_file, train_task.train_task_config.snapshot_path) def main(): print(\"process start...\")",
"detect2d_train(self, cfg_path, gpu_id, config_path): det2d_train = Detection2dTrain(cfg_path, gpu_id, config_path) det2d_train.load_pretrain_model(self.pretrain_model_path) det2d_train.train(self.train_path, self.val_path) self.image_model_convert(det2d_train,",
"ClassifyTrain(cfg_path, gpu_id, config_path) cls_train_task.load_pretrain_model(self.pretrain_model_path) cls_train_task.train(self.train_path, self.val_path) self.image_model_convert(cls_train_task, cfg_path) def detect2d_train(self, cfg_path, gpu_id, config_path):",
"train_task.detect2d_train(options.model, 0, options.config_path) elif options.task_name == TaskName.Segment_Task: train_task.segment_train(options.model, 0, options.config_path) elif options.task_name ==",
"import ModelConverter from easyai.base_name.task_name import TaskName class TrainTask(): def __init__(self, train_path, val_path, pretrain_model_path,",
"cls_train_task.load_pretrain_model(self.pretrain_model_path) cls_train_task.train(self.train_path, self.val_path) self.image_model_convert(cls_train_task, cfg_path) def detect2d_train(self, cfg_path, gpu_id, config_path): det2d_train = Detection2dTrain(cfg_path,",
"gpu_id, config_path): pc_cls_train_task = PointCloudClassifyTrain(cfg_path, gpu_id, config_path) pc_cls_train_task.load_pretrain_model(self.pretrain_model_path) pc_cls_train_task.train(self.train_path, self.val_path) def image_model_convert(self, train_task,",
"is_convert def classify_train(self, cfg_path, gpu_id, config_path): cls_train_task = ClassifyTrain(cfg_path, gpu_id, config_path) cls_train_task.load_pretrain_model(self.pretrain_model_path) cls_train_task.train(self.train_path,",
"gpu_id, config_path) pc_cls_train_task.load_pretrain_model(self.pretrain_model_path) pc_cls_train_task.train(self.train_path, self.val_path) def image_model_convert(self, train_task, cfg_path): if self.is_convert: converter =",
"def detect2d_train(self, cfg_path, gpu_id, config_path): det2d_train = Detection2dTrain(cfg_path, gpu_id, config_path) det2d_train.load_pretrain_model(self.pretrain_model_path) det2d_train.train(self.train_path, self.val_path)",
"= SegmentionTrain(cfg_path, gpu_id, config_path) seg_train.load_pretrain_model(self.pretrain_model_path) seg_train.train(self.train_path, self.val_path) self.image_model_convert(seg_train, cfg_path) def pc_classify_train(self, cfg_path, gpu_id,",
"Detection2dTrain from easyai.tasks.seg.segment_train import SegmentionTrain from easyai.tasks.pc_cls.pc_classify_train import PointCloudClassifyTrain from easyai.tools.model_to_onnx import ModelConverter"
] |
[
"} else: ro_env = { 'gui_parent': gui_parent, 'app': gui_parent.app_manager, } ro_setup = 'from",
"import guisupport import qdarkstyle from rayoptics.gui.appmanager import ModelInfo from rayoptics.util import colors default_template",
"if is_dark: ipy_console.setStyleSheet( qdarkstyle.load_stylesheet(qt_api='pyqt5')) # color_defs = {**styles.get_colors('solarized-dark'), # **prompt_style } else: ipy_console.setStyleSheet('')",
"Jupyter console widget \"\"\" self.kernel_manager.kernel.shell.push(variableDict) def clear(self): \"\"\" Clears the terminal \"\"\" self._control.clear()",
"orig_y = gui_parent.initial_window_offset() sub_window.setGeometry(orig_x, orig_y, view_width, view_ht) sub_window.show() class ConsoleWidget(RichJupyterWidget): def __init__(self, customBanner=None,",
"-*- # Copyright © 2018 <NAME> \"\"\" Support creation of an iPython console,",
".in-prompt-number { font-weight: bold; } .out-prompt { color: %(o_color)s; } .out-prompt-number { font-weight:",
"console with a rayoptics environment \"\"\" def create_light_or_dark_callback(ipy_console): # if not hasattr(ipy_console, 'background'):",
"prompt_style = { 'i_color': accent['cyan'], 'o_color': accent['orange'], } if is_dark: ipy_console.setStyleSheet( qdarkstyle.load_stylesheet(qt_api='pyqt5')) #",
"def create_ipython_console(gui_parent, opt_model, title, view_width, view_ht): \"\"\" create a iPython console with a",
"self._append_plain_text(text) def execute_command(self, command): \"\"\" Execute a command in the frame of the",
"%(fgcolor)s; selection-background-color: %(select)s; } .inverted { background-color: %(fgcolor)s; color: %(bgcolor)s; } .error {",
"orig_x, orig_y = gui_parent.initial_window_offset() sub_window.setGeometry(orig_x, orig_y, view_width, view_ht) sub_window.show() class ConsoleWidget(RichJupyterWidget): def __init__(self,",
"rayoptics.util import colors default_template = '''\\ QPlainTextEdit, QTextEdit { background-color: %(bgcolor)s; background-clip: padding;",
"the Jupyter console widget \"\"\" self.kernel_manager.kernel.shell.push(variableDict) def clear(self): \"\"\" Clears the terminal \"\"\"",
"construct the top level widget ipy_console = ConsoleWidget() # load the environment ipy_console.execute_command(ro_setup)",
"an iPython console, with rayoptics environment .. Created on Wed Nov 21 21:48:02",
"pairs, push those variables to the Jupyter console widget \"\"\" self.kernel_manager.kernel.shell.push(variableDict) def clear(self):",
"ipy_console.style_sheet = default_template%color_defs # ipy_console._style_sheet_changed() return l_or_d if opt_model: ro_env = { 'gui_parent':",
"creation of an iPython console, with rayoptics environment .. Created on Wed Nov",
"class ConsoleWidget(RichJupyterWidget): def __init__(self, customBanner=None, *args, **kwargs): super().__init__(*args, **kwargs) if customBanner is not",
"'gui_parent': gui_parent, 'app': gui_parent.app_manager, 'opm': opt_model, 'sm': opt_model.seq_model, 'osp': opt_model.optical_spec, 'pm': opt_model.parax_model, 'em':",
"top level widget ipy_console = ConsoleWidget() # load the environment ipy_console.execute_command(ro_setup) ipy_console.push_vars(ro_env) mi",
"**kwargs): super().__init__(*args, **kwargs) if customBanner is not None: self.banner = customBanner self.font_size =",
"variables to the Jupyter console widget \"\"\" self.kernel_manager.kernel.shell.push(variableDict) def clear(self): \"\"\" Clears the",
"color: %(fgcolor)s; selection-background-color: %(select)s; } .inverted { background-color: %(fgcolor)s; color: %(bgcolor)s; } .error",
"from PyQt5.QtGui import QColor from qtconsole.rich_jupyter_widget import RichJupyterWidget from qtconsole.inprocess import QtInProcessKernelManager from",
"%(o_color)s; } .out-prompt-number { font-weight: bold; } ''' def create_ipython_console(gui_parent, opt_model, title, view_width,",
"from IPython.lib import guisupport import qdarkstyle from rayoptics.gui.appmanager import ModelInfo from rayoptics.util import",
"styles from IPython.lib import guisupport import qdarkstyle from rayoptics.gui.appmanager import ModelInfo from rayoptics.util",
"background-clip: padding; color: %(fgcolor)s; selection-background-color: %(select)s; } .inverted { background-color: %(fgcolor)s; color: %(bgcolor)s;",
"kernel_client = self.kernel_manager.client() kernel_client.start_channels() def stop(): kernel_client.stop_channels() kernel_manager.shutdown_kernel() guisupport.get_app_qt().exit() self.exit_requested.connect(stop) def push_vars(self, variableDict):",
"__init__(self, customBanner=None, *args, **kwargs): super().__init__(*args, **kwargs) if customBanner is not None: self.banner =",
"= 'from rayoptics.environment import *' # construct the top level widget ipy_console =",
"the top level widget ipy_console = ConsoleWidget() # load the environment ipy_console.execute_command(ro_setup) ipy_console.push_vars(ro_env)",
"a rayoptics environment \"\"\" def create_light_or_dark_callback(ipy_console): # if not hasattr(ipy_console, 'background'): # ipy_console.background",
"opt_model, title, view_width, view_ht): \"\"\" create a iPython console with a rayoptics environment",
"return l_or_d if opt_model: ro_env = { 'gui_parent': gui_parent, 'app': gui_parent.app_manager, 'opm': opt_model,",
"'from rayoptics.environment import *' # construct the top level widget ipy_console = ConsoleWidget()",
"kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel(show_banner=False) kernel_manager.kernel.gui = 'qt' self.kernel_client = kernel_client = self.kernel_manager.client() kernel_client.start_channels()",
"QtInProcessKernelManager from qtconsole import styles from IPython.lib import guisupport import qdarkstyle from rayoptics.gui.appmanager",
"selection-background-color: %(select)s; } .inverted { background-color: %(fgcolor)s; color: %(bgcolor)s; } .error { color:",
"some plain text to the console \"\"\" self._append_plain_text(text) def execute_command(self, command): \"\"\" Execute",
"ipy_console._style_sheet_changed() return l_or_d if opt_model: ro_env = { 'gui_parent': gui_parent, 'app': gui_parent.app_manager, 'opm':",
"else: ipy_console.setStyleSheet('') # color_defs = {**styles.get_colors('solarized-light'), # **prompt_style } # ipy_console.style_sheet = default_template%color_defs",
"'sm': opt_model.seq_model, 'osp': opt_model.optical_spec, 'pm': opt_model.parax_model, 'em': opt_model.ele_model, 'pt': opt_model.part_tree, } else: ro_env",
"name / value pairs, push those variables to the Jupyter console widget \"\"\"",
"Nov 21 21:48:02 2018 .. codeauthor: <NAME> \"\"\" from PyQt5.QtGui import QColor from",
"def clear(self): \"\"\" Clears the terminal \"\"\" self._control.clear() # self.kernel_manager def print_text(self, text):",
"colors.accent_colors(is_dark) prompt_style = { 'i_color': accent['cyan'], 'o_color': accent['orange'], } if is_dark: ipy_console.setStyleSheet( qdarkstyle.load_stylesheet(qt_api='pyqt5'))",
"utf-8 -*- # Copyright © 2018 <NAME> \"\"\" Support creation of an iPython",
"gui_parent.add_subwindow(ipy_console, mi) sub_window.setWindowTitle(title) sub_window.sync_light_or_dark = create_light_or_dark_callback(ipy_console) orig_x, orig_y = gui_parent.initial_window_offset() sub_window.setGeometry(orig_x, orig_y, view_width,",
"%(bgcolor)s; } .error { color: red; } .in-prompt { color: %(i_color)s; } .in-prompt-number",
"to the Jupyter console widget \"\"\" self.kernel_manager.kernel.shell.push(variableDict) def clear(self): \"\"\" Clears the terminal",
"rayoptics.gui.appmanager import ModelInfo from rayoptics.util import colors default_template = '''\\ QPlainTextEdit, QTextEdit {",
"{**styles.get_colors('solarized-light'), # **prompt_style } # ipy_console.style_sheet = default_template%color_defs # ipy_console._style_sheet_changed() return l_or_d if",
"guisupport import qdarkstyle from rayoptics.gui.appmanager import ModelInfo from rayoptics.util import colors default_template =",
"default_template = '''\\ QPlainTextEdit, QTextEdit { background-color: %(bgcolor)s; background-clip: padding; color: %(fgcolor)s; selection-background-color:",
"on Wed Nov 21 21:48:02 2018 .. codeauthor: <NAME> \"\"\" from PyQt5.QtGui import",
"color: %(bgcolor)s; } .error { color: red; } .in-prompt { color: %(i_color)s; }",
"**prompt_style } # ipy_console.style_sheet = default_template%color_defs # ipy_console._style_sheet_changed() return l_or_d if opt_model: ro_env",
"kernel_manager.kernel.gui = 'qt' self.kernel_client = kernel_client = self.kernel_manager.client() kernel_client.start_channels() def stop(): kernel_client.stop_channels() kernel_manager.shutdown_kernel()",
"# **prompt_style } # ipy_console.style_sheet = default_template%color_defs # ipy_console._style_sheet_changed() return l_or_d if opt_model:",
"= default_template%color_defs # ipy_console._style_sheet_changed() return l_or_d if opt_model: ro_env = { 'gui_parent': gui_parent,",
"if not hasattr(ipy_console, 'background'): # ipy_console.background = ipy_console.background() def l_or_d(is_dark): accent = colors.accent_colors(is_dark)",
"} # ipy_console.style_sheet = default_template%color_defs # ipy_console._style_sheet_changed() return l_or_d if opt_model: ro_env =",
"# -*- coding: utf-8 -*- # Copyright © 2018 <NAME> \"\"\" Support creation",
"rayoptics environment \"\"\" def create_light_or_dark_callback(ipy_console): # if not hasattr(ipy_console, 'background'): # ipy_console.background =",
"ConsoleWidget() # load the environment ipy_console.execute_command(ro_setup) ipy_console.push_vars(ro_env) mi = ModelInfo(opt_model) sub_window = gui_parent.add_subwindow(ipy_console,",
"Given a dictionary containing name / value pairs, push those variables to the",
"# load the environment ipy_console.execute_command(ro_setup) ipy_console.push_vars(ro_env) mi = ModelInfo(opt_model) sub_window = gui_parent.add_subwindow(ipy_console, mi)",
"sub_window.setWindowTitle(title) sub_window.sync_light_or_dark = create_light_or_dark_callback(ipy_console) orig_x, orig_y = gui_parent.initial_window_offset() sub_window.setGeometry(orig_x, orig_y, view_width, view_ht) sub_window.show()",
"widget \"\"\" self.kernel_manager.kernel.shell.push(variableDict) def clear(self): \"\"\" Clears the terminal \"\"\" self._control.clear() # self.kernel_manager",
"push_vars(self, variableDict): \"\"\" Given a dictionary containing name / value pairs, push those",
"{ 'gui_parent': gui_parent, 'app': gui_parent.app_manager, } ro_setup = 'from rayoptics.environment import *' #",
"import RichJupyterWidget from qtconsole.inprocess import QtInProcessKernelManager from qtconsole import styles from IPython.lib import",
"qtconsole.rich_jupyter_widget import RichJupyterWidget from qtconsole.inprocess import QtInProcessKernelManager from qtconsole import styles from IPython.lib",
"'o_color': accent['orange'], } if is_dark: ipy_console.setStyleSheet( qdarkstyle.load_stylesheet(qt_api='pyqt5')) # color_defs = {**styles.get_colors('solarized-dark'), # **prompt_style",
"clear(self): \"\"\" Clears the terminal \"\"\" self._control.clear() # self.kernel_manager def print_text(self, text): \"\"\"",
"self.kernel_manager def print_text(self, text): \"\"\" Prints some plain text to the console \"\"\"",
"def execute_command(self, command): \"\"\" Execute a command in the frame of the console",
"QPlainTextEdit, QTextEdit { background-color: %(bgcolor)s; background-clip: padding; color: %(fgcolor)s; selection-background-color: %(select)s; } .inverted",
"} ''' def create_ipython_console(gui_parent, opt_model, title, view_width, view_ht): \"\"\" create a iPython console",
"l_or_d(is_dark): accent = colors.accent_colors(is_dark) prompt_style = { 'i_color': accent['cyan'], 'o_color': accent['orange'], } if",
"super().__init__(*args, **kwargs) if customBanner is not None: self.banner = customBanner self.font_size = 6",
"ModelInfo from rayoptics.util import colors default_template = '''\\ QPlainTextEdit, QTextEdit { background-color: %(bgcolor)s;",
"= customBanner self.font_size = 6 self.kernel_manager = kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel(show_banner=False) kernel_manager.kernel.gui =",
"title, view_width, view_ht): \"\"\" create a iPython console with a rayoptics environment \"\"\"",
"python3 # -*- coding: utf-8 -*- # Copyright © 2018 <NAME> \"\"\" Support",
"# color_defs = {**styles.get_colors('solarized-dark'), # **prompt_style } else: ipy_console.setStyleSheet('') # color_defs = {**styles.get_colors('solarized-light'),",
"from qtconsole.rich_jupyter_widget import RichJupyterWidget from qtconsole.inprocess import QtInProcessKernelManager from qtconsole import styles from",
"Clears the terminal \"\"\" self._control.clear() # self.kernel_manager def print_text(self, text): \"\"\" Prints some",
"sub_window.setGeometry(orig_x, orig_y, view_width, view_ht) sub_window.show() class ConsoleWidget(RichJupyterWidget): def __init__(self, customBanner=None, *args, **kwargs): super().__init__(*args,",
"ipy_console.setStyleSheet( qdarkstyle.load_stylesheet(qt_api='pyqt5')) # color_defs = {**styles.get_colors('solarized-dark'), # **prompt_style } else: ipy_console.setStyleSheet('') # color_defs",
"\"\"\" Support creation of an iPython console, with rayoptics environment .. Created on",
"QTextEdit { background-color: %(bgcolor)s; background-clip: padding; color: %(fgcolor)s; selection-background-color: %(select)s; } .inverted {",
"\"\"\" self._append_plain_text(text) def execute_command(self, command): \"\"\" Execute a command in the frame of",
"# **prompt_style } else: ipy_console.setStyleSheet('') # color_defs = {**styles.get_colors('solarized-light'), # **prompt_style } #",
"%(select)s; } .inverted { background-color: %(fgcolor)s; color: %(bgcolor)s; } .error { color: red;",
"= 'qt' self.kernel_client = kernel_client = self.kernel_manager.client() kernel_client.start_channels() def stop(): kernel_client.stop_channels() kernel_manager.shutdown_kernel() guisupport.get_app_qt().exit()",
"color_defs = {**styles.get_colors('solarized-light'), # **prompt_style } # ipy_console.style_sheet = default_template%color_defs # ipy_console._style_sheet_changed() return",
"{ color: %(i_color)s; } .in-prompt-number { font-weight: bold; } .out-prompt { color: %(o_color)s;",
"create_light_or_dark_callback(ipy_console): # if not hasattr(ipy_console, 'background'): # ipy_console.background = ipy_console.background() def l_or_d(is_dark): accent",
"21:48:02 2018 .. codeauthor: <NAME> \"\"\" from PyQt5.QtGui import QColor from qtconsole.rich_jupyter_widget import",
"def push_vars(self, variableDict): \"\"\" Given a dictionary containing name / value pairs, push",
"ipy_console.background = ipy_console.background() def l_or_d(is_dark): accent = colors.accent_colors(is_dark) prompt_style = { 'i_color': accent['cyan'],",
"= kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel(show_banner=False) kernel_manager.kernel.gui = 'qt' self.kernel_client = kernel_client = self.kernel_manager.client()",
"{ color: %(o_color)s; } .out-prompt-number { font-weight: bold; } ''' def create_ipython_console(gui_parent, opt_model,",
"coding: utf-8 -*- # Copyright © 2018 <NAME> \"\"\" Support creation of an",
"#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright © 2018 <NAME> \"\"\"",
"widget ipy_console = ConsoleWidget() # load the environment ipy_console.execute_command(ro_setup) ipy_console.push_vars(ro_env) mi = ModelInfo(opt_model)",
"environment .. Created on Wed Nov 21 21:48:02 2018 .. codeauthor: <NAME> \"\"\"",
"# construct the top level widget ipy_console = ConsoleWidget() # load the environment",
"load the environment ipy_console.execute_command(ro_setup) ipy_console.push_vars(ro_env) mi = ModelInfo(opt_model) sub_window = gui_parent.add_subwindow(ipy_console, mi) sub_window.setWindowTitle(title)",
"the environment ipy_console.execute_command(ro_setup) ipy_console.push_vars(ro_env) mi = ModelInfo(opt_model) sub_window = gui_parent.add_subwindow(ipy_console, mi) sub_window.setWindowTitle(title) sub_window.sync_light_or_dark",
"PyQt5.QtGui import QColor from qtconsole.rich_jupyter_widget import RichJupyterWidget from qtconsole.inprocess import QtInProcessKernelManager from qtconsole",
"push those variables to the Jupyter console widget \"\"\" self.kernel_manager.kernel.shell.push(variableDict) def clear(self): \"\"\"",
"import styles from IPython.lib import guisupport import qdarkstyle from rayoptics.gui.appmanager import ModelInfo from",
"\"\"\" from PyQt5.QtGui import QColor from qtconsole.rich_jupyter_widget import RichJupyterWidget from qtconsole.inprocess import QtInProcessKernelManager",
"gui_parent.initial_window_offset() sub_window.setGeometry(orig_x, orig_y, view_width, view_ht) sub_window.show() class ConsoleWidget(RichJupyterWidget): def __init__(self, customBanner=None, *args, **kwargs):",
"Wed Nov 21 21:48:02 2018 .. codeauthor: <NAME> \"\"\" from PyQt5.QtGui import QColor",
"with a rayoptics environment \"\"\" def create_light_or_dark_callback(ipy_console): # if not hasattr(ipy_console, 'background'): #",
"Execute a command in the frame of the console widget \"\"\" self._execute(command, False)",
"rayoptics environment .. Created on Wed Nov 21 21:48:02 2018 .. codeauthor: <NAME>",
"2018 .. codeauthor: <NAME> \"\"\" from PyQt5.QtGui import QColor from qtconsole.rich_jupyter_widget import RichJupyterWidget",
"def __init__(self, customBanner=None, *args, **kwargs): super().__init__(*args, **kwargs) if customBanner is not None: self.banner",
"customBanner self.font_size = 6 self.kernel_manager = kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel(show_banner=False) kernel_manager.kernel.gui = 'qt'",
"ro_env = { 'gui_parent': gui_parent, 'app': gui_parent.app_manager, 'opm': opt_model, 'sm': opt_model.seq_model, 'osp': opt_model.optical_spec,",
"view_ht): \"\"\" create a iPython console with a rayoptics environment \"\"\" def create_light_or_dark_callback(ipy_console):",
"console, with rayoptics environment .. Created on Wed Nov 21 21:48:02 2018 ..",
"if customBanner is not None: self.banner = customBanner self.font_size = 6 self.kernel_manager =",
"def create_light_or_dark_callback(ipy_console): # if not hasattr(ipy_console, 'background'): # ipy_console.background = ipy_console.background() def l_or_d(is_dark):",
"create_light_or_dark_callback(ipy_console) orig_x, orig_y = gui_parent.initial_window_offset() sub_window.setGeometry(orig_x, orig_y, view_width, view_ht) sub_window.show() class ConsoleWidget(RichJupyterWidget): def",
"containing name / value pairs, push those variables to the Jupyter console widget",
"\"\"\" Clears the terminal \"\"\" self._control.clear() # self.kernel_manager def print_text(self, text): \"\"\" Prints",
"font-weight: bold; } ''' def create_ipython_console(gui_parent, opt_model, title, view_width, view_ht): \"\"\" create a",
"'app': gui_parent.app_manager, 'opm': opt_model, 'sm': opt_model.seq_model, 'osp': opt_model.optical_spec, 'pm': opt_model.parax_model, 'em': opt_model.ele_model, 'pt':",
"those variables to the Jupyter console widget \"\"\" self.kernel_manager.kernel.shell.push(variableDict) def clear(self): \"\"\" Clears",
"= {**styles.get_colors('solarized-light'), # **prompt_style } # ipy_console.style_sheet = default_template%color_defs # ipy_console._style_sheet_changed() return l_or_d",
"'pm': opt_model.parax_model, 'em': opt_model.ele_model, 'pt': opt_model.part_tree, } else: ro_env = { 'gui_parent': gui_parent,",
"def l_or_d(is_dark): accent = colors.accent_colors(is_dark) prompt_style = { 'i_color': accent['cyan'], 'o_color': accent['orange'], }",
"text): \"\"\" Prints some plain text to the console \"\"\" self._append_plain_text(text) def execute_command(self,",
"create_ipython_console(gui_parent, opt_model, title, view_width, view_ht): \"\"\" create a iPython console with a rayoptics",
"print_text(self, text): \"\"\" Prints some plain text to the console \"\"\" self._append_plain_text(text) def",
"{ background-color: %(fgcolor)s; color: %(bgcolor)s; } .error { color: red; } .in-prompt {",
"console \"\"\" self._append_plain_text(text) def execute_command(self, command): \"\"\" Execute a command in the frame",
"view_width, view_ht): \"\"\" create a iPython console with a rayoptics environment \"\"\" def",
"= ipy_console.background() def l_or_d(is_dark): accent = colors.accent_colors(is_dark) prompt_style = { 'i_color': accent['cyan'], 'o_color':",
".. Created on Wed Nov 21 21:48:02 2018 .. codeauthor: <NAME> \"\"\" from",
".. codeauthor: <NAME> \"\"\" from PyQt5.QtGui import QColor from qtconsole.rich_jupyter_widget import RichJupyterWidget from",
"Prints some plain text to the console \"\"\" self._append_plain_text(text) def execute_command(self, command): \"\"\"",
"21 21:48:02 2018 .. codeauthor: <NAME> \"\"\" from PyQt5.QtGui import QColor from qtconsole.rich_jupyter_widget",
"level widget ipy_console = ConsoleWidget() # load the environment ipy_console.execute_command(ro_setup) ipy_console.push_vars(ro_env) mi =",
"bold; } ''' def create_ipython_console(gui_parent, opt_model, title, view_width, view_ht): \"\"\" create a iPython",
"padding; color: %(fgcolor)s; selection-background-color: %(select)s; } .inverted { background-color: %(fgcolor)s; color: %(bgcolor)s; }",
"view_ht) sub_window.show() class ConsoleWidget(RichJupyterWidget): def __init__(self, customBanner=None, *args, **kwargs): super().__init__(*args, **kwargs) if customBanner",
"\"\"\" Execute a command in the frame of the console widget \"\"\" self._execute(command,",
"QColor from qtconsole.rich_jupyter_widget import RichJupyterWidget from qtconsole.inprocess import QtInProcessKernelManager from qtconsole import styles",
"= { 'gui_parent': gui_parent, 'app': gui_parent.app_manager, 'opm': opt_model, 'sm': opt_model.seq_model, 'osp': opt_model.optical_spec, 'pm':",
"orig_y, view_width, view_ht) sub_window.show() class ConsoleWidget(RichJupyterWidget): def __init__(self, customBanner=None, *args, **kwargs): super().__init__(*args, **kwargs)",
"'opm': opt_model, 'sm': opt_model.seq_model, 'osp': opt_model.optical_spec, 'pm': opt_model.parax_model, 'em': opt_model.ele_model, 'pt': opt_model.part_tree, }",
"is not None: self.banner = customBanner self.font_size = 6 self.kernel_manager = kernel_manager =",
"self.kernel_manager = kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel(show_banner=False) kernel_manager.kernel.gui = 'qt' self.kernel_client = kernel_client =",
"rayoptics.environment import *' # construct the top level widget ipy_console = ConsoleWidget() #",
"qdarkstyle from rayoptics.gui.appmanager import ModelInfo from rayoptics.util import colors default_template = '''\\ QPlainTextEdit,",
"else: ro_env = { 'gui_parent': gui_parent, 'app': gui_parent.app_manager, } ro_setup = 'from rayoptics.environment",
"gui_parent.app_manager, 'opm': opt_model, 'sm': opt_model.seq_model, 'osp': opt_model.optical_spec, 'pm': opt_model.parax_model, 'em': opt_model.ele_model, 'pt': opt_model.part_tree,",
"IPython.lib import guisupport import qdarkstyle from rayoptics.gui.appmanager import ModelInfo from rayoptics.util import colors",
"ipy_console.push_vars(ro_env) mi = ModelInfo(opt_model) sub_window = gui_parent.add_subwindow(ipy_console, mi) sub_window.setWindowTitle(title) sub_window.sync_light_or_dark = create_light_or_dark_callback(ipy_console) orig_x,",
"ipy_console.execute_command(ro_setup) ipy_console.push_vars(ro_env) mi = ModelInfo(opt_model) sub_window = gui_parent.add_subwindow(ipy_console, mi) sub_window.setWindowTitle(title) sub_window.sync_light_or_dark = create_light_or_dark_callback(ipy_console)",
"{ color: red; } .in-prompt { color: %(i_color)s; } .in-prompt-number { font-weight: bold;",
"is_dark: ipy_console.setStyleSheet( qdarkstyle.load_stylesheet(qt_api='pyqt5')) # color_defs = {**styles.get_colors('solarized-dark'), # **prompt_style } else: ipy_console.setStyleSheet('') #",
"None: self.banner = customBanner self.font_size = 6 self.kernel_manager = kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel(show_banner=False)",
"= gui_parent.initial_window_offset() sub_window.setGeometry(orig_x, orig_y, view_width, view_ht) sub_window.show() class ConsoleWidget(RichJupyterWidget): def __init__(self, customBanner=None, *args,",
"} .in-prompt-number { font-weight: bold; } .out-prompt { color: %(o_color)s; } .out-prompt-number {",
"''' def create_ipython_console(gui_parent, opt_model, title, view_width, view_ht): \"\"\" create a iPython console with",
"qtconsole import styles from IPython.lib import guisupport import qdarkstyle from rayoptics.gui.appmanager import ModelInfo",
".in-prompt { color: %(i_color)s; } .in-prompt-number { font-weight: bold; } .out-prompt { color:",
"the terminal \"\"\" self._control.clear() # self.kernel_manager def print_text(self, text): \"\"\" Prints some plain",
"/ value pairs, push those variables to the Jupyter console widget \"\"\" self.kernel_manager.kernel.shell.push(variableDict)",
"**prompt_style } else: ipy_console.setStyleSheet('') # color_defs = {**styles.get_colors('solarized-light'), # **prompt_style } # ipy_console.style_sheet",
"not hasattr(ipy_console, 'background'): # ipy_console.background = ipy_console.background() def l_or_d(is_dark): accent = colors.accent_colors(is_dark) prompt_style",
"create a iPython console with a rayoptics environment \"\"\" def create_light_or_dark_callback(ipy_console): # if",
"ipy_console.background() def l_or_d(is_dark): accent = colors.accent_colors(is_dark) prompt_style = { 'i_color': accent['cyan'], 'o_color': accent['orange'],",
"%(bgcolor)s; background-clip: padding; color: %(fgcolor)s; selection-background-color: %(select)s; } .inverted { background-color: %(fgcolor)s; color:",
"{ font-weight: bold; } .out-prompt { color: %(o_color)s; } .out-prompt-number { font-weight: bold;",
"accent['orange'], } if is_dark: ipy_console.setStyleSheet( qdarkstyle.load_stylesheet(qt_api='pyqt5')) # color_defs = {**styles.get_colors('solarized-dark'), # **prompt_style }",
"self.banner = customBanner self.font_size = 6 self.kernel_manager = kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel(show_banner=False) kernel_manager.kernel.gui",
"Support creation of an iPython console, with rayoptics environment .. Created on Wed",
"mi) sub_window.setWindowTitle(title) sub_window.sync_light_or_dark = create_light_or_dark_callback(ipy_console) orig_x, orig_y = gui_parent.initial_window_offset() sub_window.setGeometry(orig_x, orig_y, view_width, view_ht)",
"ro_env = { 'gui_parent': gui_parent, 'app': gui_parent.app_manager, } ro_setup = 'from rayoptics.environment import",
"variableDict): \"\"\" Given a dictionary containing name / value pairs, push those variables",
"import qdarkstyle from rayoptics.gui.appmanager import ModelInfo from rayoptics.util import colors default_template = '''\\",
"'i_color': accent['cyan'], 'o_color': accent['orange'], } if is_dark: ipy_console.setStyleSheet( qdarkstyle.load_stylesheet(qt_api='pyqt5')) # color_defs = {**styles.get_colors('solarized-dark'),",
"= QtInProcessKernelManager() kernel_manager.start_kernel(show_banner=False) kernel_manager.kernel.gui = 'qt' self.kernel_client = kernel_client = self.kernel_manager.client() kernel_client.start_channels() def",
"iPython console with a rayoptics environment \"\"\" def create_light_or_dark_callback(ipy_console): # if not hasattr(ipy_console,",
"# ipy_console.style_sheet = default_template%color_defs # ipy_console._style_sheet_changed() return l_or_d if opt_model: ro_env = {",
"def print_text(self, text): \"\"\" Prints some plain text to the console \"\"\" self._append_plain_text(text)",
"# if not hasattr(ipy_console, 'background'): # ipy_console.background = ipy_console.background() def l_or_d(is_dark): accent =",
"'app': gui_parent.app_manager, } ro_setup = 'from rayoptics.environment import *' # construct the top",
"} .inverted { background-color: %(fgcolor)s; color: %(bgcolor)s; } .error { color: red; }",
"*args, **kwargs): super().__init__(*args, **kwargs) if customBanner is not None: self.banner = customBanner self.font_size",
"self.kernel_manager.client() kernel_client.start_channels() def stop(): kernel_client.stop_channels() kernel_manager.shutdown_kernel() guisupport.get_app_qt().exit() self.exit_requested.connect(stop) def push_vars(self, variableDict): \"\"\" Given",
"Copyright © 2018 <NAME> \"\"\" Support creation of an iPython console, with rayoptics",
"gui_parent, 'app': gui_parent.app_manager, } ro_setup = 'from rayoptics.environment import *' # construct the",
"gui_parent.app_manager, } ro_setup = 'from rayoptics.environment import *' # construct the top level",
"customBanner=None, *args, **kwargs): super().__init__(*args, **kwargs) if customBanner is not None: self.banner = customBanner",
"plain text to the console \"\"\" self._append_plain_text(text) def execute_command(self, command): \"\"\" Execute a",
"\"\"\" def create_light_or_dark_callback(ipy_console): # if not hasattr(ipy_console, 'background'): # ipy_console.background = ipy_console.background() def",
"%(i_color)s; } .in-prompt-number { font-weight: bold; } .out-prompt { color: %(o_color)s; } .out-prompt-number",
"sub_window = gui_parent.add_subwindow(ipy_console, mi) sub_window.setWindowTitle(title) sub_window.sync_light_or_dark = create_light_or_dark_callback(ipy_console) orig_x, orig_y = gui_parent.initial_window_offset() sub_window.setGeometry(orig_x,",
"# ipy_console._style_sheet_changed() return l_or_d if opt_model: ro_env = { 'gui_parent': gui_parent, 'app': gui_parent.app_manager,",
"color_defs = {**styles.get_colors('solarized-dark'), # **prompt_style } else: ipy_console.setStyleSheet('') # color_defs = {**styles.get_colors('solarized-light'), #",
"opt_model.seq_model, 'osp': opt_model.optical_spec, 'pm': opt_model.parax_model, 'em': opt_model.ele_model, 'pt': opt_model.part_tree, } else: ro_env =",
"<NAME> \"\"\" Support creation of an iPython console, with rayoptics environment .. Created",
"import *' # construct the top level widget ipy_console = ConsoleWidget() # load",
"the console \"\"\" self._append_plain_text(text) def execute_command(self, command): \"\"\" Execute a command in the",
"= { 'gui_parent': gui_parent, 'app': gui_parent.app_manager, } ro_setup = 'from rayoptics.environment import *'",
".out-prompt { color: %(o_color)s; } .out-prompt-number { font-weight: bold; } ''' def create_ipython_console(gui_parent,",
"terminal \"\"\" self._control.clear() # self.kernel_manager def print_text(self, text): \"\"\" Prints some plain text",
"with rayoptics environment .. Created on Wed Nov 21 21:48:02 2018 .. codeauthor:",
"= {**styles.get_colors('solarized-dark'), # **prompt_style } else: ipy_console.setStyleSheet('') # color_defs = {**styles.get_colors('solarized-light'), # **prompt_style",
"} .in-prompt { color: %(i_color)s; } .in-prompt-number { font-weight: bold; } .out-prompt {",
"\"\"\" Prints some plain text to the console \"\"\" self._append_plain_text(text) def execute_command(self, command):",
"qdarkstyle.load_stylesheet(qt_api='pyqt5')) # color_defs = {**styles.get_colors('solarized-dark'), # **prompt_style } else: ipy_console.setStyleSheet('') # color_defs =",
"def stop(): kernel_client.stop_channels() kernel_manager.shutdown_kernel() guisupport.get_app_qt().exit() self.exit_requested.connect(stop) def push_vars(self, variableDict): \"\"\" Given a dictionary",
"Created on Wed Nov 21 21:48:02 2018 .. codeauthor: <NAME> \"\"\" from PyQt5.QtGui",
"{ background-color: %(bgcolor)s; background-clip: padding; color: %(fgcolor)s; selection-background-color: %(select)s; } .inverted { background-color:",
"= ModelInfo(opt_model) sub_window = gui_parent.add_subwindow(ipy_console, mi) sub_window.setWindowTitle(title) sub_window.sync_light_or_dark = create_light_or_dark_callback(ipy_console) orig_x, orig_y =",
"self.kernel_manager.kernel.shell.push(variableDict) def clear(self): \"\"\" Clears the terminal \"\"\" self._control.clear() # self.kernel_manager def print_text(self,",
"\"\"\" create a iPython console with a rayoptics environment \"\"\" def create_light_or_dark_callback(ipy_console): #",
"'em': opt_model.ele_model, 'pt': opt_model.part_tree, } else: ro_env = { 'gui_parent': gui_parent, 'app': gui_parent.app_manager,",
"from qtconsole.inprocess import QtInProcessKernelManager from qtconsole import styles from IPython.lib import guisupport import",
"} .out-prompt-number { font-weight: bold; } ''' def create_ipython_console(gui_parent, opt_model, title, view_width, view_ht):",
"6 self.kernel_manager = kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel(show_banner=False) kernel_manager.kernel.gui = 'qt' self.kernel_client = kernel_client",
"# ipy_console.background = ipy_console.background() def l_or_d(is_dark): accent = colors.accent_colors(is_dark) prompt_style = { 'i_color':",
"'background'): # ipy_console.background = ipy_console.background() def l_or_d(is_dark): accent = colors.accent_colors(is_dark) prompt_style = {",
"customBanner is not None: self.banner = customBanner self.font_size = 6 self.kernel_manager = kernel_manager",
"**kwargs) if customBanner is not None: self.banner = customBanner self.font_size = 6 self.kernel_manager",
"= self.kernel_manager.client() kernel_client.start_channels() def stop(): kernel_client.stop_channels() kernel_manager.shutdown_kernel() guisupport.get_app_qt().exit() self.exit_requested.connect(stop) def push_vars(self, variableDict): \"\"\"",
"self.kernel_client = kernel_client = self.kernel_manager.client() kernel_client.start_channels() def stop(): kernel_client.stop_channels() kernel_manager.shutdown_kernel() guisupport.get_app_qt().exit() self.exit_requested.connect(stop) def",
"color: %(i_color)s; } .in-prompt-number { font-weight: bold; } .out-prompt { color: %(o_color)s; }",
"accent = colors.accent_colors(is_dark) prompt_style = { 'i_color': accent['cyan'], 'o_color': accent['orange'], } if is_dark:",
"of an iPython console, with rayoptics environment .. Created on Wed Nov 21",
"text to the console \"\"\" self._append_plain_text(text) def execute_command(self, command): \"\"\" Execute a command",
"stop(): kernel_client.stop_channels() kernel_manager.shutdown_kernel() guisupport.get_app_qt().exit() self.exit_requested.connect(stop) def push_vars(self, variableDict): \"\"\" Given a dictionary containing",
"self.exit_requested.connect(stop) def push_vars(self, variableDict): \"\"\" Given a dictionary containing name / value pairs,",
"hasattr(ipy_console, 'background'): # ipy_console.background = ipy_console.background() def l_or_d(is_dark): accent = colors.accent_colors(is_dark) prompt_style =",
"'qt' self.kernel_client = kernel_client = self.kernel_manager.client() kernel_client.start_channels() def stop(): kernel_client.stop_channels() kernel_manager.shutdown_kernel() guisupport.get_app_qt().exit() self.exit_requested.connect(stop)",
"{ 'gui_parent': gui_parent, 'app': gui_parent.app_manager, 'opm': opt_model, 'sm': opt_model.seq_model, 'osp': opt_model.optical_spec, 'pm': opt_model.parax_model,",
"import ModelInfo from rayoptics.util import colors default_template = '''\\ QPlainTextEdit, QTextEdit { background-color:",
"accent['cyan'], 'o_color': accent['orange'], } if is_dark: ipy_console.setStyleSheet( qdarkstyle.load_stylesheet(qt_api='pyqt5')) # color_defs = {**styles.get_colors('solarized-dark'), #",
"from rayoptics.util import colors default_template = '''\\ QPlainTextEdit, QTextEdit { background-color: %(bgcolor)s; background-clip:",
"{ font-weight: bold; } ''' def create_ipython_console(gui_parent, opt_model, title, view_width, view_ht): \"\"\" create",
".error { color: red; } .in-prompt { color: %(i_color)s; } .in-prompt-number { font-weight:",
"= 6 self.kernel_manager = kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel(show_banner=False) kernel_manager.kernel.gui = 'qt' self.kernel_client =",
"# self.kernel_manager def print_text(self, text): \"\"\" Prints some plain text to the console",
"# color_defs = {**styles.get_colors('solarized-light'), # **prompt_style } # ipy_console.style_sheet = default_template%color_defs # ipy_console._style_sheet_changed()",
"*' # construct the top level widget ipy_console = ConsoleWidget() # load the",
"<NAME> \"\"\" from PyQt5.QtGui import QColor from qtconsole.rich_jupyter_widget import RichJupyterWidget from qtconsole.inprocess import",
"not None: self.banner = customBanner self.font_size = 6 self.kernel_manager = kernel_manager = QtInProcessKernelManager()",
"} .error { color: red; } .in-prompt { color: %(i_color)s; } .in-prompt-number {",
"{ 'i_color': accent['cyan'], 'o_color': accent['orange'], } if is_dark: ipy_console.setStyleSheet( qdarkstyle.load_stylesheet(qt_api='pyqt5')) # color_defs =",
"= gui_parent.add_subwindow(ipy_console, mi) sub_window.setWindowTitle(title) sub_window.sync_light_or_dark = create_light_or_dark_callback(ipy_console) orig_x, orig_y = gui_parent.initial_window_offset() sub_window.setGeometry(orig_x, orig_y,",
".out-prompt-number { font-weight: bold; } ''' def create_ipython_console(gui_parent, opt_model, title, view_width, view_ht): \"\"\"",
"\"\"\" Given a dictionary containing name / value pairs, push those variables to",
"ipy_console.setStyleSheet('') # color_defs = {**styles.get_colors('solarized-light'), # **prompt_style } # ipy_console.style_sheet = default_template%color_defs #",
"} ro_setup = 'from rayoptics.environment import *' # construct the top level widget",
"opt_model: ro_env = { 'gui_parent': gui_parent, 'app': gui_parent.app_manager, 'opm': opt_model, 'sm': opt_model.seq_model, 'osp':",
"%(fgcolor)s; color: %(bgcolor)s; } .error { color: red; } .in-prompt { color: %(i_color)s;",
"value pairs, push those variables to the Jupyter console widget \"\"\" self.kernel_manager.kernel.shell.push(variableDict) def",
"'pt': opt_model.part_tree, } else: ro_env = { 'gui_parent': gui_parent, 'app': gui_parent.app_manager, } ro_setup",
"= '''\\ QPlainTextEdit, QTextEdit { background-color: %(bgcolor)s; background-clip: padding; color: %(fgcolor)s; selection-background-color: %(select)s;",
"from rayoptics.gui.appmanager import ModelInfo from rayoptics.util import colors default_template = '''\\ QPlainTextEdit, QTextEdit",
"\"\"\" self.kernel_manager.kernel.shell.push(variableDict) def clear(self): \"\"\" Clears the terminal \"\"\" self._control.clear() # self.kernel_manager def",
"qtconsole.inprocess import QtInProcessKernelManager from qtconsole import styles from IPython.lib import guisupport import qdarkstyle",
"sub_window.sync_light_or_dark = create_light_or_dark_callback(ipy_console) orig_x, orig_y = gui_parent.initial_window_offset() sub_window.setGeometry(orig_x, orig_y, view_width, view_ht) sub_window.show() class",
"QtInProcessKernelManager() kernel_manager.start_kernel(show_banner=False) kernel_manager.kernel.gui = 'qt' self.kernel_client = kernel_client = self.kernel_manager.client() kernel_client.start_channels() def stop():",
"view_width, view_ht) sub_window.show() class ConsoleWidget(RichJupyterWidget): def __init__(self, customBanner=None, *args, **kwargs): super().__init__(*args, **kwargs) if",
"kernel_manager.shutdown_kernel() guisupport.get_app_qt().exit() self.exit_requested.connect(stop) def push_vars(self, variableDict): \"\"\" Given a dictionary containing name /",
"to the console \"\"\" self._append_plain_text(text) def execute_command(self, command): \"\"\" Execute a command in",
"= kernel_client = self.kernel_manager.client() kernel_client.start_channels() def stop(): kernel_client.stop_channels() kernel_manager.shutdown_kernel() guisupport.get_app_qt().exit() self.exit_requested.connect(stop) def push_vars(self,",
"ModelInfo(opt_model) sub_window = gui_parent.add_subwindow(ipy_console, mi) sub_window.setWindowTitle(title) sub_window.sync_light_or_dark = create_light_or_dark_callback(ipy_console) orig_x, orig_y = gui_parent.initial_window_offset()",
"a dictionary containing name / value pairs, push those variables to the Jupyter",
"'osp': opt_model.optical_spec, 'pm': opt_model.parax_model, 'em': opt_model.ele_model, 'pt': opt_model.part_tree, } else: ro_env = {",
"sub_window.show() class ConsoleWidget(RichJupyterWidget): def __init__(self, customBanner=None, *args, **kwargs): super().__init__(*args, **kwargs) if customBanner is",
"ConsoleWidget(RichJupyterWidget): def __init__(self, customBanner=None, *args, **kwargs): super().__init__(*args, **kwargs) if customBanner is not None:",
"= colors.accent_colors(is_dark) prompt_style = { 'i_color': accent['cyan'], 'o_color': accent['orange'], } if is_dark: ipy_console.setStyleSheet(",
"guisupport.get_app_qt().exit() self.exit_requested.connect(stop) def push_vars(self, variableDict): \"\"\" Given a dictionary containing name / value",
"# Copyright © 2018 <NAME> \"\"\" Support creation of an iPython console, with",
"background-color: %(fgcolor)s; color: %(bgcolor)s; } .error { color: red; } .in-prompt { color:",
"'''\\ QPlainTextEdit, QTextEdit { background-color: %(bgcolor)s; background-clip: padding; color: %(fgcolor)s; selection-background-color: %(select)s; }",
"default_template%color_defs # ipy_console._style_sheet_changed() return l_or_d if opt_model: ro_env = { 'gui_parent': gui_parent, 'app':",
"color: red; } .in-prompt { color: %(i_color)s; } .in-prompt-number { font-weight: bold; }",
"bold; } .out-prompt { color: %(o_color)s; } .out-prompt-number { font-weight: bold; } '''",
"ro_setup = 'from rayoptics.environment import *' # construct the top level widget ipy_console",
"mi = ModelInfo(opt_model) sub_window = gui_parent.add_subwindow(ipy_console, mi) sub_window.setWindowTitle(title) sub_window.sync_light_or_dark = create_light_or_dark_callback(ipy_console) orig_x, orig_y",
"'gui_parent': gui_parent, 'app': gui_parent.app_manager, } ro_setup = 'from rayoptics.environment import *' # construct",
"} if is_dark: ipy_console.setStyleSheet( qdarkstyle.load_stylesheet(qt_api='pyqt5')) # color_defs = {**styles.get_colors('solarized-dark'), # **prompt_style } else:",
"kernel_client.start_channels() def stop(): kernel_client.stop_channels() kernel_manager.shutdown_kernel() guisupport.get_app_qt().exit() self.exit_requested.connect(stop) def push_vars(self, variableDict): \"\"\" Given a",
"} else: ipy_console.setStyleSheet('') # color_defs = {**styles.get_colors('solarized-light'), # **prompt_style } # ipy_console.style_sheet =",
"self._control.clear() # self.kernel_manager def print_text(self, text): \"\"\" Prints some plain text to the",
"= { 'i_color': accent['cyan'], 'o_color': accent['orange'], } if is_dark: ipy_console.setStyleSheet( qdarkstyle.load_stylesheet(qt_api='pyqt5')) # color_defs",
"color: %(o_color)s; } .out-prompt-number { font-weight: bold; } ''' def create_ipython_console(gui_parent, opt_model, title,",
"opt_model.optical_spec, 'pm': opt_model.parax_model, 'em': opt_model.ele_model, 'pt': opt_model.part_tree, } else: ro_env = { 'gui_parent':",
"environment ipy_console.execute_command(ro_setup) ipy_console.push_vars(ro_env) mi = ModelInfo(opt_model) sub_window = gui_parent.add_subwindow(ipy_console, mi) sub_window.setWindowTitle(title) sub_window.sync_light_or_dark =",
"© 2018 <NAME> \"\"\" Support creation of an iPython console, with rayoptics environment",
"font-weight: bold; } .out-prompt { color: %(o_color)s; } .out-prompt-number { font-weight: bold; }",
"ipy_console = ConsoleWidget() # load the environment ipy_console.execute_command(ro_setup) ipy_console.push_vars(ro_env) mi = ModelInfo(opt_model) sub_window",
"= create_light_or_dark_callback(ipy_console) orig_x, orig_y = gui_parent.initial_window_offset() sub_window.setGeometry(orig_x, orig_y, view_width, view_ht) sub_window.show() class ConsoleWidget(RichJupyterWidget):",
"background-color: %(bgcolor)s; background-clip: padding; color: %(fgcolor)s; selection-background-color: %(select)s; } .inverted { background-color: %(fgcolor)s;",
"l_or_d if opt_model: ro_env = { 'gui_parent': gui_parent, 'app': gui_parent.app_manager, 'opm': opt_model, 'sm':",
"RichJupyterWidget from qtconsole.inprocess import QtInProcessKernelManager from qtconsole import styles from IPython.lib import guisupport",
"} .out-prompt { color: %(o_color)s; } .out-prompt-number { font-weight: bold; } ''' def",
"codeauthor: <NAME> \"\"\" from PyQt5.QtGui import QColor from qtconsole.rich_jupyter_widget import RichJupyterWidget from qtconsole.inprocess",
"2018 <NAME> \"\"\" Support creation of an iPython console, with rayoptics environment ..",
"dictionary containing name / value pairs, push those variables to the Jupyter console",
"execute_command(self, command): \"\"\" Execute a command in the frame of the console widget",
"command): \"\"\" Execute a command in the frame of the console widget \"\"\"",
".inverted { background-color: %(fgcolor)s; color: %(bgcolor)s; } .error { color: red; } .in-prompt",
"red; } .in-prompt { color: %(i_color)s; } .in-prompt-number { font-weight: bold; } .out-prompt",
"opt_model.ele_model, 'pt': opt_model.part_tree, } else: ro_env = { 'gui_parent': gui_parent, 'app': gui_parent.app_manager, }",
"iPython console, with rayoptics environment .. Created on Wed Nov 21 21:48:02 2018",
"-*- coding: utf-8 -*- # Copyright © 2018 <NAME> \"\"\" Support creation of",
"import colors default_template = '''\\ QPlainTextEdit, QTextEdit { background-color: %(bgcolor)s; background-clip: padding; color:",
"import QtInProcessKernelManager from qtconsole import styles from IPython.lib import guisupport import qdarkstyle from",
"kernel_client.stop_channels() kernel_manager.shutdown_kernel() guisupport.get_app_qt().exit() self.exit_requested.connect(stop) def push_vars(self, variableDict): \"\"\" Given a dictionary containing name",
"colors default_template = '''\\ QPlainTextEdit, QTextEdit { background-color: %(bgcolor)s; background-clip: padding; color: %(fgcolor)s;",
"\"\"\" self._control.clear() # self.kernel_manager def print_text(self, text): \"\"\" Prints some plain text to",
"self.font_size = 6 self.kernel_manager = kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel(show_banner=False) kernel_manager.kernel.gui = 'qt' self.kernel_client",
"import QColor from qtconsole.rich_jupyter_widget import RichJupyterWidget from qtconsole.inprocess import QtInProcessKernelManager from qtconsole import",
"from qtconsole import styles from IPython.lib import guisupport import qdarkstyle from rayoptics.gui.appmanager import",
"{**styles.get_colors('solarized-dark'), # **prompt_style } else: ipy_console.setStyleSheet('') # color_defs = {**styles.get_colors('solarized-light'), # **prompt_style }",
"= ConsoleWidget() # load the environment ipy_console.execute_command(ro_setup) ipy_console.push_vars(ro_env) mi = ModelInfo(opt_model) sub_window =",
"environment \"\"\" def create_light_or_dark_callback(ipy_console): # if not hasattr(ipy_console, 'background'): # ipy_console.background = ipy_console.background()",
"gui_parent, 'app': gui_parent.app_manager, 'opm': opt_model, 'sm': opt_model.seq_model, 'osp': opt_model.optical_spec, 'pm': opt_model.parax_model, 'em': opt_model.ele_model,",
"opt_model, 'sm': opt_model.seq_model, 'osp': opt_model.optical_spec, 'pm': opt_model.parax_model, 'em': opt_model.ele_model, 'pt': opt_model.part_tree, } else:",
"kernel_manager.start_kernel(show_banner=False) kernel_manager.kernel.gui = 'qt' self.kernel_client = kernel_client = self.kernel_manager.client() kernel_client.start_channels() def stop(): kernel_client.stop_channels()",
"if opt_model: ro_env = { 'gui_parent': gui_parent, 'app': gui_parent.app_manager, 'opm': opt_model, 'sm': opt_model.seq_model,",
"console widget \"\"\" self.kernel_manager.kernel.shell.push(variableDict) def clear(self): \"\"\" Clears the terminal \"\"\" self._control.clear() #",
"opt_model.parax_model, 'em': opt_model.ele_model, 'pt': opt_model.part_tree, } else: ro_env = { 'gui_parent': gui_parent, 'app':",
"opt_model.part_tree, } else: ro_env = { 'gui_parent': gui_parent, 'app': gui_parent.app_manager, } ro_setup =",
"a iPython console with a rayoptics environment \"\"\" def create_light_or_dark_callback(ipy_console): # if not"
] |
[
"\" + str(web_url.getcode())) # read the data from the URL and print it",
"code and print it print (\"result code: \" + str(web_url.getcode())) # read the",
"code: \" + str(web_url.getcode())) # read the data from the URL and print",
"for retrieving data from the internet # import urllib.request def main(): # open",
"and print it data = web_url.read() print (data) if __name__ == \"__main__\": main()",
"# get the result code and print it print (\"result code: \" +",
"urllib2 web_url = urllib.request.urlopen(\"http://www.google.com\") # get the result code and print it print",
"it print (\"result code: \" + str(web_url.getcode())) # read the data from the",
"open a connection to a URL using urllib2 web_url = urllib.request.urlopen(\"http://www.google.com\") # get",
"a URL using urllib2 web_url = urllib.request.urlopen(\"http://www.google.com\") # get the result code and",
"web_url = urllib.request.urlopen(\"http://www.google.com\") # get the result code and print it print (\"result",
"data from the URL and print it data = web_url.read() print (data) if",
"data from the internet # import urllib.request def main(): # open a connection",
"URL and print it data = web_url.read() print (data) if __name__ == \"__main__\":",
"retrieving data from the internet # import urllib.request def main(): # open a",
"urllib.request def main(): # open a connection to a URL using urllib2 web_url",
"urllib.request.urlopen(\"http://www.google.com\") # get the result code and print it print (\"result code: \"",
"result code and print it print (\"result code: \" + str(web_url.getcode())) # read",
"import urllib.request def main(): # open a connection to a URL using urllib2",
"get the result code and print it print (\"result code: \" + str(web_url.getcode()))",
"(\"result code: \" + str(web_url.getcode())) # read the data from the URL and",
"def main(): # open a connection to a URL using urllib2 web_url =",
"using urllib2 web_url = urllib.request.urlopen(\"http://www.google.com\") # get the result code and print it",
"the data from the URL and print it data = web_url.read() print (data)",
"URL using urllib2 web_url = urllib.request.urlopen(\"http://www.google.com\") # get the result code and print",
"connection to a URL using urllib2 web_url = urllib.request.urlopen(\"http://www.google.com\") # get the result",
"a connection to a URL using urllib2 web_url = urllib.request.urlopen(\"http://www.google.com\") # get the",
"str(web_url.getcode())) # read the data from the URL and print it data =",
"read the data from the URL and print it data = web_url.read() print",
"+ str(web_url.getcode())) # read the data from the URL and print it data",
"# read the data from the URL and print it data = web_url.read()",
"the URL and print it data = web_url.read() print (data) if __name__ ==",
"the internet # import urllib.request def main(): # open a connection to a",
"# import urllib.request def main(): # open a connection to a URL using",
"Example file for retrieving data from the internet # import urllib.request def main():",
"internet # import urllib.request def main(): # open a connection to a URL",
"print it print (\"result code: \" + str(web_url.getcode())) # read the data from",
"the result code and print it print (\"result code: \" + str(web_url.getcode())) #",
"file for retrieving data from the internet # import urllib.request def main(): #",
"main(): # open a connection to a URL using urllib2 web_url = urllib.request.urlopen(\"http://www.google.com\")",
"and print it print (\"result code: \" + str(web_url.getcode())) # read the data",
"from the URL and print it data = web_url.read() print (data) if __name__",
"# Example file for retrieving data from the internet # import urllib.request def",
"print (\"result code: \" + str(web_url.getcode())) # read the data from the URL",
"= urllib.request.urlopen(\"http://www.google.com\") # get the result code and print it print (\"result code:",
"from the internet # import urllib.request def main(): # open a connection to",
"# open a connection to a URL using urllib2 web_url = urllib.request.urlopen(\"http://www.google.com\") #",
"# # Example file for retrieving data from the internet # import urllib.request",
"to a URL using urllib2 web_url = urllib.request.urlopen(\"http://www.google.com\") # get the result code"
] |
[
"return cls._instances[api_key] def __init__(self, *, api_key: str = \"\"): self.api_key: str = api_key",
"crafting(self, *, data, ids: list = None): \"\"\" Fetch daily craftable items by",
"async def worldbosses(self, *, data, ids: list = None): \"\"\" Fetch daily world",
"= None): \"\"\" Fetch daily hero's choice chests by ID(s). None returns all",
"str = \"\"): self.api_key: str = api_key @endpoint(\"/v2/dailycrafting\", has_ids=True) async def crafting(self, *,",
"items by ID(s). None returns all time-gated crafting items. :param data: :param ids:",
"returns all time-gated crafting items. :param data: :param ids: :return: \"\"\" if ids",
"async def crafting(self, *, data, ids: list = None): \"\"\" Fetch daily craftable",
"is None: return data return object_parse(data, DailyCrafting) @endpoint(\"/v2/mapchests\", has_ids=True) async def mapchests(self, *,",
"list = None): \"\"\" Fetch daily world bosses by ID(s). None returns all",
"not in cls._instances: cls._instances[api_key] = super().__new__(cls, *args, **kwargs) return cls._instances[api_key] def __init__(self, *,",
"chests by ID(s). None returns all time-gated hero's choice chests. :param data: :param",
"= {} def __new__(cls, *args, api_key: str = \"\", **kwargs): if api_key not",
"ids is None: return data return object_parse(data, DailyMapChest) @endpoint(\"/v2/worldbosses\", has_ids=True) async def worldbosses(self,",
"*, data, ids: list = None): \"\"\" Fetch daily world bosses by ID(s).",
"data, ids: list = None): \"\"\" Fetch daily craftable items by ID(s). None",
"has_ids=True) async def mapchests(self, *, data, ids: list = None): \"\"\" Fetch daily",
"from ..utils import endpoint, object_parse class DailyApi: _instances = {} def __new__(cls, *args,",
"str = api_key @endpoint(\"/v2/dailycrafting\", has_ids=True) async def crafting(self, *, data, ids: list =",
"= None): \"\"\" Fetch daily craftable items by ID(s). None returns all time-gated",
":return: \"\"\" if ids is None: return data return object_parse(data, DailyCrafting) @endpoint(\"/v2/mapchests\", has_ids=True)",
"Fetch daily craftable items by ID(s). None returns all time-gated crafting items. :param",
"None): \"\"\" Fetch daily world bosses by ID(s). None returns all world bosses.",
"str = \"\", **kwargs): if api_key not in cls._instances: cls._instances[api_key] = super().__new__(cls, *args,",
"bosses. :param data: :param ids: :return: \"\"\" if ids is None: return data",
"def worldbosses(self, *, data, ids: list = None): \"\"\" Fetch daily world bosses",
"= \"\"): self.api_key: str = api_key @endpoint(\"/v2/dailycrafting\", has_ids=True) async def crafting(self, *, data,",
"\"\"\" Fetch daily craftable items by ID(s). None returns all time-gated crafting items.",
"None returns all world bosses. :param data: :param ids: :return: \"\"\" if ids",
"DailyCrafting, DailyMapChest, DailyWorldBoss from ..utils import endpoint, object_parse class DailyApi: _instances = {}",
"items. :param data: :param ids: :return: \"\"\" if ids is None: return data",
"\"\"): self.api_key: str = api_key @endpoint(\"/v2/dailycrafting\", has_ids=True) async def crafting(self, *, data, ids:",
"all world bosses. :param data: :param ids: :return: \"\"\" if ids is None:",
"Fetch daily hero's choice chests by ID(s). None returns all time-gated hero's choice",
"cls._instances[api_key] def __init__(self, *, api_key: str = \"\"): self.api_key: str = api_key @endpoint(\"/v2/dailycrafting\",",
"ID(s). None returns all world bosses. :param data: :param ids: :return: \"\"\" if",
"list = None): \"\"\" Fetch daily hero's choice chests by ID(s). None returns",
"def __init__(self, *, api_key: str = \"\"): self.api_key: str = api_key @endpoint(\"/v2/dailycrafting\", has_ids=True)",
"\"\"\" if ids is None: return data return object_parse(data, DailyCrafting) @endpoint(\"/v2/mapchests\", has_ids=True) async",
"return data return object_parse(data, DailyMapChest) @endpoint(\"/v2/worldbosses\", has_ids=True) async def worldbosses(self, *, data, ids:",
":param ids: :return: \"\"\" if ids is None: return data return object_parse(data, DailyMapChest)",
"None: return data return object_parse(data, DailyCrafting) @endpoint(\"/v2/mapchests\", has_ids=True) async def mapchests(self, *, data,",
"DailyCrafting) @endpoint(\"/v2/mapchests\", has_ids=True) async def mapchests(self, *, data, ids: list = None): \"\"\"",
"DailyApi: _instances = {} def __new__(cls, *args, api_key: str = \"\", **kwargs): if",
"choice chests by ID(s). None returns all time-gated hero's choice chests. :param data:",
"ids: :return: \"\"\" if ids is None: return data return object_parse(data, DailyCrafting) @endpoint(\"/v2/mapchests\",",
"is None: return data return object_parse(data, DailyMapChest) @endpoint(\"/v2/worldbosses\", has_ids=True) async def worldbosses(self, *,",
"super().__new__(cls, *args, **kwargs) return cls._instances[api_key] def __init__(self, *, api_key: str = \"\"): self.api_key:",
"all time-gated crafting items. :param data: :param ids: :return: \"\"\" if ids is",
"list = None): \"\"\" Fetch daily craftable items by ID(s). None returns all",
"ids is None: return data return object_parse(data, DailyCrafting) @endpoint(\"/v2/mapchests\", has_ids=True) async def mapchests(self,",
"__new__(cls, *args, api_key: str = \"\", **kwargs): if api_key not in cls._instances: cls._instances[api_key]",
"cls._instances[api_key] = super().__new__(cls, *args, **kwargs) return cls._instances[api_key] def __init__(self, *, api_key: str =",
"= api_key @endpoint(\"/v2/dailycrafting\", has_ids=True) async def crafting(self, *, data, ids: list = None):",
"None returns all time-gated hero's choice chests. :param data: :param ids: :return: \"\"\"",
"craftable items by ID(s). None returns all time-gated crafting items. :param data: :param",
"<filename>pygw2/api/daily.py from ..core.models.general import DailyCrafting, DailyMapChest, DailyWorldBoss from ..utils import endpoint, object_parse class",
"worldbosses(self, *, data, ids: list = None): \"\"\" Fetch daily world bosses by",
"mapchests(self, *, data, ids: list = None): \"\"\" Fetch daily hero's choice chests",
":return: \"\"\" if ids is None: return data return object_parse(data, DailyMapChest) @endpoint(\"/v2/worldbosses\", has_ids=True)",
"object_parse class DailyApi: _instances = {} def __new__(cls, *args, api_key: str = \"\",",
"return object_parse(data, DailyCrafting) @endpoint(\"/v2/mapchests\", has_ids=True) async def mapchests(self, *, data, ids: list =",
"daily world bosses by ID(s). None returns all world bosses. :param data: :param",
"api_key: str = \"\", **kwargs): if api_key not in cls._instances: cls._instances[api_key] = super().__new__(cls,",
"**kwargs) return cls._instances[api_key] def __init__(self, *, api_key: str = \"\"): self.api_key: str =",
"*args, api_key: str = \"\", **kwargs): if api_key not in cls._instances: cls._instances[api_key] =",
"in cls._instances: cls._instances[api_key] = super().__new__(cls, *args, **kwargs) return cls._instances[api_key] def __init__(self, *, api_key:",
"ids: :return: \"\"\" if ids is None: return data return object_parse(data, DailyMapChest) @endpoint(\"/v2/worldbosses\",",
"object_parse(data, DailyCrafting) @endpoint(\"/v2/mapchests\", has_ids=True) async def mapchests(self, *, data, ids: list = None):",
"if ids is None: return data return object_parse(data, DailyMapChest) @endpoint(\"/v2/worldbosses\", has_ids=True) async def",
"by ID(s). None returns all time-gated hero's choice chests. :param data: :param ids:",
"None returns all time-gated crafting items. :param data: :param ids: :return: \"\"\" if",
"= super().__new__(cls, *args, **kwargs) return cls._instances[api_key] def __init__(self, *, api_key: str = \"\"):",
"hero's choice chests. :param data: :param ids: :return: \"\"\" if ids is None:",
"*, api_key: str = \"\"): self.api_key: str = api_key @endpoint(\"/v2/dailycrafting\", has_ids=True) async def",
"hero's choice chests by ID(s). None returns all time-gated hero's choice chests. :param",
"\"\", **kwargs): if api_key not in cls._instances: cls._instances[api_key] = super().__new__(cls, *args, **kwargs) return",
"data, ids: list = None): \"\"\" Fetch daily world bosses by ID(s). None",
"DailyWorldBoss from ..utils import endpoint, object_parse class DailyApi: _instances = {} def __new__(cls,",
"data, ids: list = None): \"\"\" Fetch daily hero's choice chests by ID(s).",
":param data: :param ids: :return: \"\"\" if ids is None: return data return",
"time-gated crafting items. :param data: :param ids: :return: \"\"\" if ids is None:",
"ids: list = None): \"\"\" Fetch daily craftable items by ID(s). None returns",
"DailyMapChest) @endpoint(\"/v2/worldbosses\", has_ids=True) async def worldbosses(self, *, data, ids: list = None): \"\"\"",
"data: :param ids: :return: \"\"\" if ids is None: return data return object_parse(data,",
"object_parse(data, DailyMapChest) @endpoint(\"/v2/worldbosses\", has_ids=True) async def worldbosses(self, *, data, ids: list = None):",
"ID(s). None returns all time-gated crafting items. :param data: :param ids: :return: \"\"\"",
"api_key: str = \"\"): self.api_key: str = api_key @endpoint(\"/v2/dailycrafting\", has_ids=True) async def crafting(self,",
"@endpoint(\"/v2/worldbosses\", has_ids=True) async def worldbosses(self, *, data, ids: list = None): \"\"\" Fetch",
"world bosses by ID(s). None returns all world bosses. :param data: :param ids:",
":param ids: :return: \"\"\" if ids is None: return data return object_parse(data, DailyCrafting)",
"ID(s). None returns all time-gated hero's choice chests. :param data: :param ids: :return:",
"**kwargs): if api_key not in cls._instances: cls._instances[api_key] = super().__new__(cls, *args, **kwargs) return cls._instances[api_key]",
"return data return object_parse(data, DailyCrafting) @endpoint(\"/v2/mapchests\", has_ids=True) async def mapchests(self, *, data, ids:",
"time-gated hero's choice chests. :param data: :param ids: :return: \"\"\" if ids is",
"by ID(s). None returns all world bosses. :param data: :param ids: :return: \"\"\"",
"\"\"\" Fetch daily world bosses by ID(s). None returns all world bosses. :param",
"world bosses. :param data: :param ids: :return: \"\"\" if ids is None: return",
"daily hero's choice chests by ID(s). None returns all time-gated hero's choice chests.",
"def mapchests(self, *, data, ids: list = None): \"\"\" Fetch daily hero's choice",
"crafting items. :param data: :param ids: :return: \"\"\" if ids is None: return",
"= \"\", **kwargs): if api_key not in cls._instances: cls._instances[api_key] = super().__new__(cls, *args, **kwargs)",
"choice chests. :param data: :param ids: :return: \"\"\" if ids is None: return",
"daily craftable items by ID(s). None returns all time-gated crafting items. :param data:",
"_instances = {} def __new__(cls, *args, api_key: str = \"\", **kwargs): if api_key",
"return object_parse(data, DailyMapChest) @endpoint(\"/v2/worldbosses\", has_ids=True) async def worldbosses(self, *, data, ids: list =",
"api_key not in cls._instances: cls._instances[api_key] = super().__new__(cls, *args, **kwargs) return cls._instances[api_key] def __init__(self,",
"returns all time-gated hero's choice chests. :param data: :param ids: :return: \"\"\" if",
"Fetch daily world bosses by ID(s). None returns all world bosses. :param data:",
"bosses by ID(s). None returns all world bosses. :param data: :param ids: :return:",
"data return object_parse(data, DailyCrafting) @endpoint(\"/v2/mapchests\", has_ids=True) async def mapchests(self, *, data, ids: list",
"returns all world bosses. :param data: :param ids: :return: \"\"\" if ids is",
"if api_key not in cls._instances: cls._instances[api_key] = super().__new__(cls, *args, **kwargs) return cls._instances[api_key] def",
"*, data, ids: list = None): \"\"\" Fetch daily craftable items by ID(s).",
"import endpoint, object_parse class DailyApi: _instances = {} def __new__(cls, *args, api_key: str",
"\"\"\" if ids is None: return data return object_parse(data, DailyMapChest) @endpoint(\"/v2/worldbosses\", has_ids=True) async",
"has_ids=True) async def crafting(self, *, data, ids: list = None): \"\"\" Fetch daily",
"..utils import endpoint, object_parse class DailyApi: _instances = {} def __new__(cls, *args, api_key:",
":param ids: :return: \"\"\" if ids is None: return data return object_parse(data, DailyWorldBoss)",
"self.api_key: str = api_key @endpoint(\"/v2/dailycrafting\", has_ids=True) async def crafting(self, *, data, ids: list",
"endpoint, object_parse class DailyApi: _instances = {} def __new__(cls, *args, api_key: str =",
"..core.models.general import DailyCrafting, DailyMapChest, DailyWorldBoss from ..utils import endpoint, object_parse class DailyApi: _instances",
"class DailyApi: _instances = {} def __new__(cls, *args, api_key: str = \"\", **kwargs):",
"*args, **kwargs) return cls._instances[api_key] def __init__(self, *, api_key: str = \"\"): self.api_key: str",
"async def mapchests(self, *, data, ids: list = None): \"\"\" Fetch daily hero's",
"ids: list = None): \"\"\" Fetch daily world bosses by ID(s). None returns",
"import DailyCrafting, DailyMapChest, DailyWorldBoss from ..utils import endpoint, object_parse class DailyApi: _instances =",
"@endpoint(\"/v2/mapchests\", has_ids=True) async def mapchests(self, *, data, ids: list = None): \"\"\" Fetch",
"None: return data return object_parse(data, DailyMapChest) @endpoint(\"/v2/worldbosses\", has_ids=True) async def worldbosses(self, *, data,",
"\"\"\" Fetch daily hero's choice chests by ID(s). None returns all time-gated hero's",
"{} def __new__(cls, *args, api_key: str = \"\", **kwargs): if api_key not in",
"api_key @endpoint(\"/v2/dailycrafting\", has_ids=True) async def crafting(self, *, data, ids: list = None): \"\"\"",
"chests. :param data: :param ids: :return: \"\"\" if ids is None: return data",
"data return object_parse(data, DailyMapChest) @endpoint(\"/v2/worldbosses\", has_ids=True) async def worldbosses(self, *, data, ids: list",
"from ..core.models.general import DailyCrafting, DailyMapChest, DailyWorldBoss from ..utils import endpoint, object_parse class DailyApi:",
"None): \"\"\" Fetch daily hero's choice chests by ID(s). None returns all time-gated",
"@endpoint(\"/v2/dailycrafting\", has_ids=True) async def crafting(self, *, data, ids: list = None): \"\"\" Fetch",
"cls._instances: cls._instances[api_key] = super().__new__(cls, *args, **kwargs) return cls._instances[api_key] def __init__(self, *, api_key: str",
"ids: list = None): \"\"\" Fetch daily hero's choice chests by ID(s). None",
"def crafting(self, *, data, ids: list = None): \"\"\" Fetch daily craftable items",
"if ids is None: return data return object_parse(data, DailyCrafting) @endpoint(\"/v2/mapchests\", has_ids=True) async def",
"has_ids=True) async def worldbosses(self, *, data, ids: list = None): \"\"\" Fetch daily",
"None): \"\"\" Fetch daily craftable items by ID(s). None returns all time-gated crafting",
"*, data, ids: list = None): \"\"\" Fetch daily hero's choice chests by",
"by ID(s). None returns all time-gated crafting items. :param data: :param ids: :return:",
"all time-gated hero's choice chests. :param data: :param ids: :return: \"\"\" if ids",
"def __new__(cls, *args, api_key: str = \"\", **kwargs): if api_key not in cls._instances:",
"= None): \"\"\" Fetch daily world bosses by ID(s). None returns all world",
"DailyMapChest, DailyWorldBoss from ..utils import endpoint, object_parse class DailyApi: _instances = {} def",
"__init__(self, *, api_key: str = \"\"): self.api_key: str = api_key @endpoint(\"/v2/dailycrafting\", has_ids=True) async"
] |
[
"self.values def __str__(self): return str(self.values) def FindSolvables(self, potentials): potentials: set return potentials.intersection(set(self.values.keys())) def",
"return potentials.intersection(set(self.values.keys())) def SolveWith(self, other): other: (int, DictionaryVector) if other[0] not in self.values:",
"otv.values: if e not in self.values: self.values[e] = 0 newvalue = self.values[e] -",
"for e in values: v = values[e] if v != 0: self.values[e] =",
"if len(self.values)==0: print(\"Colinearity found!\") return None minvalue = min(self.values.keys()) factor = self.values.pop(minvalue) for",
"return str(self.values) def FindSolvables(self, potentials): potentials: set return potentials.intersection(set(self.values.keys())) def SolveWith(self, other): other:",
"= dict() self.values: dict = dict() for e in values: v = values[e]",
"newvalue return def ConvertToCanon(self): if len(self.values)==0: print(\"Colinearity found!\") return None minvalue = min(self.values.keys())",
"= 0 newvalue = self.values[e] - otv.values[e] * factor if newvalue == 0:",
"return self.values def __str__(self): return str(self.values) def FindSolvables(self, potentials): potentials: set return potentials.intersection(set(self.values.keys()))",
"DictionaryVector = other[1] for e in otv.values: if e not in self.values: self.values[e]",
"minvalue = min(self.values.keys()) factor = self.values.pop(minvalue) for e in self.values: self.values[e] /= factor",
"for e in otv.values: if e not in self.values: self.values[e] = 0 newvalue",
"FindSolvables(self, potentials): potentials: set return potentials.intersection(set(self.values.keys())) def SolveWith(self, other): other: (int, DictionaryVector) if",
"factor return minvalue if __name__ == \"__main__\": A = DictionaryVector({3: 2}) B =",
"print(\"Colinearity found!\") return None minvalue = min(self.values.keys()) factor = self.values.pop(minvalue) for e in",
"ConvertToCanon(self): if len(self.values)==0: print(\"Colinearity found!\") return None minvalue = min(self.values.keys()) factor = self.values.pop(minvalue)",
"= self.values.pop(minvalue) for e in self.values: self.values[e] /= factor return minvalue if __name__",
"0: self.values.pop(e) else: self.values[e] = newvalue return def ConvertToCanon(self): if len(self.values)==0: print(\"Colinearity found!\")",
"e in self.values: self.values[e] /= factor return minvalue if __name__ == \"__main__\": A",
"return None minvalue = min(self.values.keys()) factor = self.values.pop(minvalue) for e in self.values: self.values[e]",
"= self.values[e] - otv.values[e] * factor if newvalue == 0: self.values.pop(e) else: self.values[e]",
"__str__(self): return str(self.values) def FindSolvables(self, potentials): potentials: set return potentials.intersection(set(self.values.keys())) def SolveWith(self, other):",
"def ConvertToCanon(self): if len(self.values)==0: print(\"Colinearity found!\") return None minvalue = min(self.values.keys()) factor =",
"0 newvalue = self.values[e] - otv.values[e] * factor if newvalue == 0: self.values.pop(e)",
"in self.values: return factor = self.values.pop(other[0]) otv: DictionaryVector = other[1] for e in",
"self.values: self.values[e] = 0 newvalue = self.values[e] - otv.values[e] * factor if newvalue",
"newvalue = self.values[e] - otv.values[e] * factor if newvalue == 0: self.values.pop(e) else:",
"found!\") return None minvalue = min(self.values.keys()) factor = self.values.pop(minvalue) for e in self.values:",
"self.values.pop(minvalue) for e in self.values: self.values[e] /= factor return minvalue if __name__ ==",
"/= factor return minvalue if __name__ == \"__main__\": A = DictionaryVector({3: 2}) B",
"= values[e] if v != 0: self.values[e] = v return def __repr__(self): return",
"factor = self.values.pop(other[0]) otv: DictionaryVector = other[1] for e in otv.values: if e",
"* factor if newvalue == 0: self.values.pop(e) else: self.values[e] = newvalue return def",
"in self.values: self.values[e] = 0 newvalue = self.values[e] - otv.values[e] * factor if",
"A = DictionaryVector({3: 2}) B = DictionaryVector({1:2, 2: 2, 3: 2}) B.SolveWith((1,A)) print(\"Done!\")",
"min(self.values.keys()) factor = self.values.pop(minvalue) for e in self.values: self.values[e] /= factor return minvalue",
"self.values[e] /= factor return minvalue if __name__ == \"__main__\": A = DictionaryVector({3: 2})",
"return minvalue if __name__ == \"__main__\": A = DictionaryVector({3: 2}) B = DictionaryVector({1:2,",
"= min(self.values.keys()) factor = self.values.pop(minvalue) for e in self.values: self.values[e] /= factor return",
"= self.values.pop(other[0]) otv: DictionaryVector = other[1] for e in otv.values: if e not",
"otv: DictionaryVector = other[1] for e in otv.values: if e not in self.values:",
"else: self.values[e] = newvalue return def ConvertToCanon(self): if len(self.values)==0: print(\"Colinearity found!\") return None",
"for e in self.values: self.values[e] /= factor return minvalue if __name__ == \"__main__\":",
"def __init__(self, values=None): if values is None: values = dict() self.values: dict =",
"other: (int, DictionaryVector) if other[0] not in self.values: return factor = self.values.pop(other[0]) otv:",
"newvalue == 0: self.values.pop(e) else: self.values[e] = newvalue return def ConvertToCanon(self): if len(self.values)==0:",
"values[e] if v != 0: self.values[e] = v return def __repr__(self): return self.values",
"DictionaryVector) if other[0] not in self.values: return factor = self.values.pop(other[0]) otv: DictionaryVector =",
"= dict() for e in values: v = values[e] if v != 0:",
"if other[0] not in self.values: return factor = self.values.pop(other[0]) otv: DictionaryVector = other[1]",
"def FindSolvables(self, potentials): potentials: set return potentials.intersection(set(self.values.keys())) def SolveWith(self, other): other: (int, DictionaryVector)",
"values is None: values = dict() self.values: dict = dict() for e in",
"self.values[e] = 0 newvalue = self.values[e] - otv.values[e] * factor if newvalue ==",
"dict = dict() for e in values: v = values[e] if v !=",
"= newvalue return def ConvertToCanon(self): if len(self.values)==0: print(\"Colinearity found!\") return None minvalue =",
"self.values: dict = dict() for e in values: v = values[e] if v",
"factor if newvalue == 0: self.values.pop(e) else: self.values[e] = newvalue return def ConvertToCanon(self):",
"src.VectorAbstract import VectorAbstract class DictionaryVector(VectorAbstract): def __init__(self, values=None): if values is None: values",
"self.values: return factor = self.values.pop(other[0]) otv: DictionaryVector = other[1] for e in otv.values:",
"in self.values: self.values[e] /= factor return minvalue if __name__ == \"__main__\": A =",
"self.values: self.values[e] /= factor return minvalue if __name__ == \"__main__\": A = DictionaryVector({3:",
"if e not in self.values: self.values[e] = 0 newvalue = self.values[e] - otv.values[e]",
"from src.VectorAbstract import VectorAbstract class DictionaryVector(VectorAbstract): def __init__(self, values=None): if values is None:",
"== 0: self.values.pop(e) else: self.values[e] = newvalue return def ConvertToCanon(self): if len(self.values)==0: print(\"Colinearity",
"dict() self.values: dict = dict() for e in values: v = values[e] if",
"self.values.pop(e) else: self.values[e] = newvalue return def ConvertToCanon(self): if len(self.values)==0: print(\"Colinearity found!\") return",
"str(self.values) def FindSolvables(self, potentials): potentials: set return potentials.intersection(set(self.values.keys())) def SolveWith(self, other): other: (int,",
"return def ConvertToCanon(self): if len(self.values)==0: print(\"Colinearity found!\") return None minvalue = min(self.values.keys()) factor",
"minvalue if __name__ == \"__main__\": A = DictionaryVector({3: 2}) B = DictionaryVector({1:2, 2:",
"if v != 0: self.values[e] = v return def __repr__(self): return self.values def",
"return def __repr__(self): return self.values def __str__(self): return str(self.values) def FindSolvables(self, potentials): potentials:",
"!= 0: self.values[e] = v return def __repr__(self): return self.values def __str__(self): return",
"other[1] for e in otv.values: if e not in self.values: self.values[e] = 0",
"v != 0: self.values[e] = v return def __repr__(self): return self.values def __str__(self):",
"= other[1] for e in otv.values: if e not in self.values: self.values[e] =",
"self.values[e] = v return def __repr__(self): return self.values def __str__(self): return str(self.values) def",
"None: values = dict() self.values: dict = dict() for e in values: v",
"e not in self.values: self.values[e] = 0 newvalue = self.values[e] - otv.values[e] *",
"<reponame>Dorijan-Cirkveni/AutoSolvingMatrix from src.VectorAbstract import VectorAbstract class DictionaryVector(VectorAbstract): def __init__(self, values=None): if values is",
"(int, DictionaryVector) if other[0] not in self.values: return factor = self.values.pop(other[0]) otv: DictionaryVector",
"import VectorAbstract class DictionaryVector(VectorAbstract): def __init__(self, values=None): if values is None: values =",
"factor = self.values.pop(minvalue) for e in self.values: self.values[e] /= factor return minvalue if",
"def SolveWith(self, other): other: (int, DictionaryVector) if other[0] not in self.values: return factor",
"in otv.values: if e not in self.values: self.values[e] = 0 newvalue = self.values[e]",
"other): other: (int, DictionaryVector) if other[0] not in self.values: return factor = self.values.pop(other[0])",
"not in self.values: self.values[e] = 0 newvalue = self.values[e] - otv.values[e] * factor",
"values = dict() self.values: dict = dict() for e in values: v =",
"def __str__(self): return str(self.values) def FindSolvables(self, potentials): potentials: set return potentials.intersection(set(self.values.keys())) def SolveWith(self,",
"- otv.values[e] * factor if newvalue == 0: self.values.pop(e) else: self.values[e] = newvalue",
"__init__(self, values=None): if values is None: values = dict() self.values: dict = dict()",
"len(self.values)==0: print(\"Colinearity found!\") return None minvalue = min(self.values.keys()) factor = self.values.pop(minvalue) for e",
"VectorAbstract class DictionaryVector(VectorAbstract): def __init__(self, values=None): if values is None: values = dict()",
"otv.values[e] * factor if newvalue == 0: self.values.pop(e) else: self.values[e] = newvalue return",
"v return def __repr__(self): return self.values def __str__(self): return str(self.values) def FindSolvables(self, potentials):",
"potentials.intersection(set(self.values.keys())) def SolveWith(self, other): other: (int, DictionaryVector) if other[0] not in self.values: return",
"is None: values = dict() self.values: dict = dict() for e in values:",
"__name__ == \"__main__\": A = DictionaryVector({3: 2}) B = DictionaryVector({1:2, 2: 2, 3:",
"values=None): if values is None: values = dict() self.values: dict = dict() for",
"if newvalue == 0: self.values.pop(e) else: self.values[e] = newvalue return def ConvertToCanon(self): if",
"SolveWith(self, other): other: (int, DictionaryVector) if other[0] not in self.values: return factor =",
"0: self.values[e] = v return def __repr__(self): return self.values def __str__(self): return str(self.values)",
"__repr__(self): return self.values def __str__(self): return str(self.values) def FindSolvables(self, potentials): potentials: set return",
"potentials): potentials: set return potentials.intersection(set(self.values.keys())) def SolveWith(self, other): other: (int, DictionaryVector) if other[0]",
"\"__main__\": A = DictionaryVector({3: 2}) B = DictionaryVector({1:2, 2: 2, 3: 2}) B.SolveWith((1,A))",
"e in values: v = values[e] if v != 0: self.values[e] = v",
"not in self.values: return factor = self.values.pop(other[0]) otv: DictionaryVector = other[1] for e",
"self.values[e] = newvalue return def ConvertToCanon(self): if len(self.values)==0: print(\"Colinearity found!\") return None minvalue",
"e in otv.values: if e not in self.values: self.values[e] = 0 newvalue =",
"if __name__ == \"__main__\": A = DictionaryVector({3: 2}) B = DictionaryVector({1:2, 2: 2,",
"self.values.pop(other[0]) otv: DictionaryVector = other[1] for e in otv.values: if e not in",
"def __repr__(self): return self.values def __str__(self): return str(self.values) def FindSolvables(self, potentials): potentials: set",
"set return potentials.intersection(set(self.values.keys())) def SolveWith(self, other): other: (int, DictionaryVector) if other[0] not in",
"other[0] not in self.values: return factor = self.values.pop(other[0]) otv: DictionaryVector = other[1] for",
"self.values[e] - otv.values[e] * factor if newvalue == 0: self.values.pop(e) else: self.values[e] =",
"v = values[e] if v != 0: self.values[e] = v return def __repr__(self):",
"dict() for e in values: v = values[e] if v != 0: self.values[e]",
"potentials: set return potentials.intersection(set(self.values.keys())) def SolveWith(self, other): other: (int, DictionaryVector) if other[0] not",
"values: v = values[e] if v != 0: self.values[e] = v return def",
"in values: v = values[e] if v != 0: self.values[e] = v return",
"return factor = self.values.pop(other[0]) otv: DictionaryVector = other[1] for e in otv.values: if",
"class DictionaryVector(VectorAbstract): def __init__(self, values=None): if values is None: values = dict() self.values:",
"== \"__main__\": A = DictionaryVector({3: 2}) B = DictionaryVector({1:2, 2: 2, 3: 2})",
"None minvalue = min(self.values.keys()) factor = self.values.pop(minvalue) for e in self.values: self.values[e] /=",
"DictionaryVector(VectorAbstract): def __init__(self, values=None): if values is None: values = dict() self.values: dict",
"= v return def __repr__(self): return self.values def __str__(self): return str(self.values) def FindSolvables(self,",
"if values is None: values = dict() self.values: dict = dict() for e"
] |
[
"from Question import Question from Arrow_Model import Arrow_Model from Model import Model class",
"'ArrowSelection' ).error( '[APPLICATION] Arm_Length does not exists' ) def set_height(self, user_data): try: self._model.height",
"Model import Model class Application(object): def __init__(self): # Load the rules self._myIntellect =",
") self.set_target_distance( user_data ) self._question = Question() self._arrow_model = Arrow_Model() self._myIntellect.learn( self._model )",
"on a json json_map = { 'question' : self._question.number, 'model' : self._arrow_model.get_model_name() }",
"AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Arm_Length does not exists' ) def set_height(self, user_data):",
"def set_height(self, user_data): try: self._model.height = int(user_data.altura) except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION]",
"'ArrowSelection' ).error( '[APPLICATION] Poundage does not exists' ) def set_temperature(self, user_data): try: self._model.temperature",
"'[APPLICATION] Poundage does not exists' ) def set_temperature(self, user_data): try: self._model.temperature = int(user_data.temperatura)",
"self._model.temperature = int(user_data.temperatura) except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Temperature does not exists'",
"self._model = Model() self._myIntellect.initialize() self.set_length( user_data ) self.set_height( user_data ) self.set_poundage( user_data )",
"intellect.Intellect import Intellect from MyIntellect import MyIntellect from Question import Question from Arrow_Model",
"not exists' ) def set_temperature(self, user_data): try: self._model.temperature = int(user_data.temperatura) except AttributeError: logging.getLogger(",
"MyIntellect from Question import Question from Arrow_Model import Arrow_Model from Model import Model",
"self._model.height = int(user_data.altura) except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Height does not exists'",
"self.set_temperature( user_data ) self.set_target_distance( user_data ) self._question = Question() self._arrow_model = Arrow_Model() self._myIntellect.learn(",
"try: self._model.arm_length = int(user_data.longitud) except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Arm_Length does not",
"except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Height does not exists' ) def set_poundage(self,",
"the data from the browser and create # the objects used by the",
"try: self._model.target_distance = int(user_data.distancia) except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Target Distance does",
"int(user_data.longitud) except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Arm_Length does not exists' ) def",
"self._arrow_model.value = self._model.arrow_model # Send the results to the browser on a json",
"json json_map = { 'question' : self._question.number, 'model' : self._arrow_model.get_model_name() } return json.dumps(",
"import web import json from intellect.Intellect import Intellect from MyIntellect import MyIntellect from",
"Poundage does not exists' ) def set_temperature(self, user_data): try: self._model.temperature = int(user_data.temperatura) except",
"create # the objects used by the policies user_data = web.input() self._model =",
"rules self._myIntellect = MyIntellect() self._myIntellect.learn( self._myIntellect.local_file_uri('./rulesets/secondRuleSet.policy')) def GET(self): # Habilitate the cross-domain communication",
"and create # the objects used by the policies user_data = web.input() self._model",
"try: self._model.poundage = int(user_data.libraje) except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Poundage does not",
"self.set_poundage( user_data ) self.set_temperature( user_data ) self.set_target_distance( user_data ) self._question = Question() self._arrow_model",
"does not exists' ) def set_temperature(self, user_data): try: self._model.temperature = int(user_data.temperatura) except AttributeError:",
"not exists' ) def set_target_distance(self, user_data): try: self._model.target_distance = int(user_data.distancia) except AttributeError: logging.getLogger(",
"= web.input() self._model = Model() self._myIntellect.initialize() self.set_length( user_data ) self.set_height( user_data ) self.set_poundage(",
"from Model import Model class Application(object): def __init__(self): # Load the rules self._myIntellect",
"Arm_Length does not exists' ) def set_height(self, user_data): try: self._model.height = int(user_data.altura) except",
"try: self._model.height = int(user_data.altura) except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Height does not",
"= MyIntellect() self._myIntellect.learn( self._myIntellect.local_file_uri('./rulesets/secondRuleSet.policy')) def GET(self): # Habilitate the cross-domain communication web.header('Access-Control-Allow-Origin', '*')",
"set_poundage(self, user_data): try: self._model.poundage = int(user_data.libraje) except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Poundage",
"to the browser on a json json_map = { 'question' : self._question.number, 'model'",
"= Model() self._myIntellect.initialize() self.set_length( user_data ) self.set_height( user_data ) self.set_poundage( user_data ) self.set_temperature(",
"= int(user_data.libraje) except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Poundage does not exists' )",
"import sys, logging, time, random import web import json from intellect.Intellect import Intellect",
"from MyIntellect import MyIntellect from Question import Question from Arrow_Model import Arrow_Model from",
"json_map = { 'question' : self._question.number, 'model' : self._arrow_model.get_model_name() } return json.dumps( json_map",
"int(user_data.distancia) except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Target Distance does not exists' )",
"Arrow_Model from Model import Model class Application(object): def __init__(self): # Load the rules",
"Send the results to the browser on a json json_map = { 'question'",
"'question' : self._question.number, 'model' : self._arrow_model.get_model_name() } return json.dumps( json_map ) def set_length(self,",
"logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Height does not exists' ) def set_poundage(self, user_data): try:",
": self._question.number, 'model' : self._arrow_model.get_model_name() } return json.dumps( json_map ) def set_length(self, user_data):",
"Load the rules self._myIntellect = MyIntellect() self._myIntellect.learn( self._myIntellect.local_file_uri('./rulesets/secondRuleSet.policy')) def GET(self): # Habilitate the",
"except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Arm_Length does not exists' ) def set_height(self,",
"set_height(self, user_data): try: self._model.height = int(user_data.altura) except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Height",
"web import json from intellect.Intellect import Intellect from MyIntellect import MyIntellect from Question",
"import json from intellect.Intellect import Intellect from MyIntellect import MyIntellect from Question import",
"Model class Application(object): def __init__(self): # Load the rules self._myIntellect = MyIntellect() self._myIntellect.learn(",
"Model() self._myIntellect.initialize() self.set_length( user_data ) self.set_height( user_data ) self.set_poundage( user_data ) self.set_temperature( user_data",
"logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Temperature does not exists' ) def set_target_distance(self, user_data): try:",
") def set_temperature(self, user_data): try: self._model.temperature = int(user_data.temperatura) except AttributeError: logging.getLogger( 'ArrowSelection' ).error(",
"set_temperature(self, user_data): try: self._model.temperature = int(user_data.temperatura) except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Temperature",
"from Arrow_Model import Arrow_Model from Model import Model class Application(object): def __init__(self): #",
"the objects used by the policies user_data = web.input() self._model = Model() self._myIntellect.initialize()",
"browser on a json json_map = { 'question' : self._question.number, 'model' : self._arrow_model.get_model_name()",
"'true') # Receive the data from the browser and create # the objects",
"exists' ) def set_height(self, user_data): try: self._model.height = int(user_data.altura) except AttributeError: logging.getLogger( 'ArrowSelection'",
") def set_target_distance(self, user_data): try: self._model.target_distance = int(user_data.distancia) except AttributeError: logging.getLogger( 'ArrowSelection' ).error(",
"self._question.number = self._model.question self._arrow_model.value = self._model.arrow_model # Send the results to the browser",
"self._myIntellect = MyIntellect() self._myIntellect.learn( self._myIntellect.local_file_uri('./rulesets/secondRuleSet.policy')) def GET(self): # Habilitate the cross-domain communication web.header('Access-Control-Allow-Origin',",
"self.set_height( user_data ) self.set_poundage( user_data ) self.set_temperature( user_data ) self.set_target_distance( user_data ) self._question",
"def __init__(self): # Load the rules self._myIntellect = MyIntellect() self._myIntellect.learn( self._myIntellect.local_file_uri('./rulesets/secondRuleSet.policy')) def GET(self):",
"user_data ) self.set_temperature( user_data ) self.set_target_distance( user_data ) self._question = Question() self._arrow_model =",
"user_data ) self._question = Question() self._arrow_model = Arrow_Model() self._myIntellect.learn( self._model ) self._myIntellect.reason() self._question.number",
"user_data): try: self._model.poundage = int(user_data.libraje) except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Poundage does",
"logging, time, random import web import json from intellect.Intellect import Intellect from MyIntellect",
"Question() self._arrow_model = Arrow_Model() self._myIntellect.learn( self._model ) self._myIntellect.reason() self._question.number = self._model.question self._arrow_model.value =",
"MyIntellect() self._myIntellect.learn( self._myIntellect.local_file_uri('./rulesets/secondRuleSet.policy')) def GET(self): # Habilitate the cross-domain communication web.header('Access-Control-Allow-Origin', '*') web.header('Access-Control-Allow-Credentials',",
"self._myIntellect.initialize() self.set_length( user_data ) self.set_height( user_data ) self.set_poundage( user_data ) self.set_temperature( user_data )",
") self.set_height( user_data ) self.set_poundage( user_data ) self.set_temperature( user_data ) self.set_target_distance( user_data )",
"self._model.target_distance = int(user_data.distancia) except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Target Distance does not",
"the browser and create # the objects used by the policies user_data =",
"import Question from Arrow_Model import Arrow_Model from Model import Model class Application(object): def",
"self._myIntellect.local_file_uri('./rulesets/secondRuleSet.policy')) def GET(self): # Habilitate the cross-domain communication web.header('Access-Control-Allow-Origin', '*') web.header('Access-Control-Allow-Credentials', 'true') #",
"= Arrow_Model() self._myIntellect.learn( self._model ) self._myIntellect.reason() self._question.number = self._model.question self._arrow_model.value = self._model.arrow_model #",
"= self._model.question self._arrow_model.value = self._model.arrow_model # Send the results to the browser on",
"Habilitate the cross-domain communication web.header('Access-Control-Allow-Origin', '*') web.header('Access-Control-Allow-Credentials', 'true') # Receive the data from",
"sys, logging, time, random import web import json from intellect.Intellect import Intellect from",
") def set_height(self, user_data): try: self._model.height = int(user_data.altura) except AttributeError: logging.getLogger( 'ArrowSelection' ).error(",
"logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Poundage does not exists' ) def set_temperature(self, user_data): try:",
"'[APPLICATION] Height does not exists' ) def set_poundage(self, user_data): try: self._model.poundage = int(user_data.libraje)",
"cross-domain communication web.header('Access-Control-Allow-Origin', '*') web.header('Access-Control-Allow-Credentials', 'true') # Receive the data from the browser",
"used by the policies user_data = web.input() self._model = Model() self._myIntellect.initialize() self.set_length( user_data",
"by the policies user_data = web.input() self._model = Model() self._myIntellect.initialize() self.set_length( user_data )",
"user_data ) self.set_height( user_data ) self.set_poundage( user_data ) self.set_temperature( user_data ) self.set_target_distance( user_data",
"except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Temperature does not exists' ) def set_target_distance(self,",
") self.set_temperature( user_data ) self.set_target_distance( user_data ) self._question = Question() self._arrow_model = Arrow_Model()",
"not exists' ) def set_poundage(self, user_data): try: self._model.poundage = int(user_data.libraje) except AttributeError: logging.getLogger(",
"except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Poundage does not exists' ) def set_temperature(self,",
"def GET(self): # Habilitate the cross-domain communication web.header('Access-Control-Allow-Origin', '*') web.header('Access-Control-Allow-Credentials', 'true') # Receive",
").error( '[APPLICATION] Height does not exists' ) def set_poundage(self, user_data): try: self._model.poundage =",
"Height does not exists' ) def set_poundage(self, user_data): try: self._model.poundage = int(user_data.libraje) except",
"the browser on a json json_map = { 'question' : self._question.number, 'model' :",
"'model' : self._arrow_model.get_model_name() } return json.dumps( json_map ) def set_length(self, user_data): try: self._model.arm_length",
"AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Height does not exists' ) def set_poundage(self, user_data):",
"# Habilitate the cross-domain communication web.header('Access-Control-Allow-Origin', '*') web.header('Access-Control-Allow-Credentials', 'true') # Receive the data",
"json_map ) def set_length(self, user_data): try: self._model.arm_length = int(user_data.longitud) except AttributeError: logging.getLogger( 'ArrowSelection'",
"json from intellect.Intellect import Intellect from MyIntellect import MyIntellect from Question import Question",
"Temperature does not exists' ) def set_target_distance(self, user_data): try: self._model.target_distance = int(user_data.distancia) except",
"data from the browser and create # the objects used by the policies",
"import Model class Application(object): def __init__(self): # Load the rules self._myIntellect = MyIntellect()",
"json.dumps( json_map ) def set_length(self, user_data): try: self._model.arm_length = int(user_data.longitud) except AttributeError: logging.getLogger(",
"'ArrowSelection' ).error( '[APPLICATION] Height does not exists' ) def set_poundage(self, user_data): try: self._model.poundage",
"objects used by the policies user_data = web.input() self._model = Model() self._myIntellect.initialize() self.set_length(",
"'[APPLICATION] Arm_Length does not exists' ) def set_height(self, user_data): try: self._model.height = int(user_data.altura)",
"web.input() self._model = Model() self._myIntellect.initialize() self.set_length( user_data ) self.set_height( user_data ) self.set_poundage( user_data",
"the rules self._myIntellect = MyIntellect() self._myIntellect.learn( self._myIntellect.local_file_uri('./rulesets/secondRuleSet.policy')) def GET(self): # Habilitate the cross-domain",
") self.set_poundage( user_data ) self.set_temperature( user_data ) self.set_target_distance( user_data ) self._question = Question()",
"'[APPLICATION] Temperature does not exists' ) def set_target_distance(self, user_data): try: self._model.target_distance = int(user_data.distancia)",
"self._model.arm_length = int(user_data.longitud) except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Arm_Length does not exists'",
"user_data ) self.set_target_distance( user_data ) self._question = Question() self._arrow_model = Arrow_Model() self._myIntellect.learn( self._model",
"exists' ) def set_poundage(self, user_data): try: self._model.poundage = int(user_data.libraje) except AttributeError: logging.getLogger( 'ArrowSelection'",
"self._question = Question() self._arrow_model = Arrow_Model() self._myIntellect.learn( self._model ) self._myIntellect.reason() self._question.number = self._model.question",
"import MyIntellect from Question import Question from Arrow_Model import Arrow_Model from Model import",
"self._myIntellect.learn( self._myIntellect.local_file_uri('./rulesets/secondRuleSet.policy')) def GET(self): # Habilitate the cross-domain communication web.header('Access-Control-Allow-Origin', '*') web.header('Access-Control-Allow-Credentials', 'true')",
"self.set_target_distance( user_data ) self._question = Question() self._arrow_model = Arrow_Model() self._myIntellect.learn( self._model ) self._myIntellect.reason()",
"int(user_data.altura) except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Height does not exists' ) def",
"random import web import json from intellect.Intellect import Intellect from MyIntellect import MyIntellect",
"Application(object): def __init__(self): # Load the rules self._myIntellect = MyIntellect() self._myIntellect.learn( self._myIntellect.local_file_uri('./rulesets/secondRuleSet.policy')) def",
"'*') web.header('Access-Control-Allow-Credentials', 'true') # Receive the data from the browser and create #",
").error( '[APPLICATION] Temperature does not exists' ) def set_target_distance(self, user_data): try: self._model.target_distance =",
"browser and create # the objects used by the policies user_data = web.input()",
").error( '[APPLICATION] Arm_Length does not exists' ) def set_height(self, user_data): try: self._model.height =",
"self._myIntellect.learn( self._model ) self._myIntellect.reason() self._question.number = self._model.question self._arrow_model.value = self._model.arrow_model # Send the",
"web.header('Access-Control-Allow-Credentials', 'true') # Receive the data from the browser and create # the",
"user_data = web.input() self._model = Model() self._myIntellect.initialize() self.set_length( user_data ) self.set_height( user_data )",
"self._question.number, 'model' : self._arrow_model.get_model_name() } return json.dumps( json_map ) def set_length(self, user_data): try:",
"= int(user_data.altura) except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Height does not exists' )",
"does not exists' ) def set_target_distance(self, user_data): try: self._model.target_distance = int(user_data.distancia) except AttributeError:",
"= int(user_data.distancia) except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Target Distance does not exists'",
"not exists' ) def set_height(self, user_data): try: self._model.height = int(user_data.altura) except AttributeError: logging.getLogger(",
"set_target_distance(self, user_data): try: self._model.target_distance = int(user_data.distancia) except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Target",
"= int(user_data.longitud) except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Arm_Length does not exists' )",
"= Question() self._arrow_model = Arrow_Model() self._myIntellect.learn( self._model ) self._myIntellect.reason() self._question.number = self._model.question self._arrow_model.value",
"class Application(object): def __init__(self): # Load the rules self._myIntellect = MyIntellect() self._myIntellect.learn( self._myIntellect.local_file_uri('./rulesets/secondRuleSet.policy'))",
"GET(self): # Habilitate the cross-domain communication web.header('Access-Control-Allow-Origin', '*') web.header('Access-Control-Allow-Credentials', 'true') # Receive the",
"web.header('Access-Control-Allow-Origin', '*') web.header('Access-Control-Allow-Credentials', 'true') # Receive the data from the browser and create",
"a json json_map = { 'question' : self._question.number, 'model' : self._arrow_model.get_model_name() } return",
"logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Arm_Length does not exists' ) def set_height(self, user_data): try:",
").error( '[APPLICATION] Poundage does not exists' ) def set_temperature(self, user_data): try: self._model.temperature =",
"# Load the rules self._myIntellect = MyIntellect() self._myIntellect.learn( self._myIntellect.local_file_uri('./rulesets/secondRuleSet.policy')) def GET(self): # Habilitate",
"self._model.arrow_model # Send the results to the browser on a json json_map =",
"set_length(self, user_data): try: self._model.arm_length = int(user_data.longitud) except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Arm_Length",
"# Send the results to the browser on a json json_map = {",
"self._model.question self._arrow_model.value = self._model.arrow_model # Send the results to the browser on a",
"= { 'question' : self._question.number, 'model' : self._arrow_model.get_model_name() } return json.dumps( json_map )",
"import Intellect from MyIntellect import MyIntellect from Question import Question from Arrow_Model import",
"return json.dumps( json_map ) def set_length(self, user_data): try: self._model.arm_length = int(user_data.longitud) except AttributeError:",
"user_data ) self.set_poundage( user_data ) self.set_temperature( user_data ) self.set_target_distance( user_data ) self._question =",
"Intellect from MyIntellect import MyIntellect from Question import Question from Arrow_Model import Arrow_Model",
") self._question = Question() self._arrow_model = Arrow_Model() self._myIntellect.learn( self._model ) self._myIntellect.reason() self._question.number =",
"{ 'question' : self._question.number, 'model' : self._arrow_model.get_model_name() } return json.dumps( json_map ) def",
"from the browser and create # the objects used by the policies user_data",
"AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Temperature does not exists' ) def set_target_distance(self, user_data):",
"= int(user_data.temperatura) except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Temperature does not exists' )",
"does not exists' ) def set_height(self, user_data): try: self._model.height = int(user_data.altura) except AttributeError:",
"self._model.poundage = int(user_data.libraje) except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Poundage does not exists'",
"def set_length(self, user_data): try: self._model.arm_length = int(user_data.longitud) except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION]",
"self.set_length( user_data ) self.set_height( user_data ) self.set_poundage( user_data ) self.set_temperature( user_data ) self.set_target_distance(",
"# Receive the data from the browser and create # the objects used",
"self._model ) self._myIntellect.reason() self._question.number = self._model.question self._arrow_model.value = self._model.arrow_model # Send the results",
"Arrow_Model() self._myIntellect.learn( self._model ) self._myIntellect.reason() self._question.number = self._model.question self._arrow_model.value = self._model.arrow_model # Send",
"the cross-domain communication web.header('Access-Control-Allow-Origin', '*') web.header('Access-Control-Allow-Credentials', 'true') # Receive the data from the",
"} return json.dumps( json_map ) def set_length(self, user_data): try: self._model.arm_length = int(user_data.longitud) except",
"exists' ) def set_target_distance(self, user_data): try: self._model.target_distance = int(user_data.distancia) except AttributeError: logging.getLogger( 'ArrowSelection'",
"__init__(self): # Load the rules self._myIntellect = MyIntellect() self._myIntellect.learn( self._myIntellect.local_file_uri('./rulesets/secondRuleSet.policy')) def GET(self): #",
"results to the browser on a json json_map = { 'question' : self._question.number,",
"import Arrow_Model from Model import Model class Application(object): def __init__(self): # Load the",
"Receive the data from the browser and create # the objects used by",
"the results to the browser on a json json_map = { 'question' :",
"user_data): try: self._model.arm_length = int(user_data.longitud) except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Arm_Length does",
") self._myIntellect.reason() self._question.number = self._model.question self._arrow_model.value = self._model.arrow_model # Send the results to",
"communication web.header('Access-Control-Allow-Origin', '*') web.header('Access-Control-Allow-Credentials', 'true') # Receive the data from the browser and",
"exists' ) def set_temperature(self, user_data): try: self._model.temperature = int(user_data.temperatura) except AttributeError: logging.getLogger( 'ArrowSelection'",
"Question from Arrow_Model import Arrow_Model from Model import Model class Application(object): def __init__(self):",
"self._arrow_model.get_model_name() } return json.dumps( json_map ) def set_length(self, user_data): try: self._model.arm_length = int(user_data.longitud)",
"'ArrowSelection' ).error( '[APPLICATION] Temperature does not exists' ) def set_target_distance(self, user_data): try: self._model.target_distance",
"def set_poundage(self, user_data): try: self._model.poundage = int(user_data.libraje) except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION]",
"= self._model.arrow_model # Send the results to the browser on a json json_map",
"Arrow_Model import Arrow_Model from Model import Model class Application(object): def __init__(self): # Load",
"def set_target_distance(self, user_data): try: self._model.target_distance = int(user_data.distancia) except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION]",
"the policies user_data = web.input() self._model = Model() self._myIntellect.initialize() self.set_length( user_data ) self.set_height(",
"policies user_data = web.input() self._model = Model() self._myIntellect.initialize() self.set_length( user_data ) self.set_height( user_data",
"def set_temperature(self, user_data): try: self._model.temperature = int(user_data.temperatura) except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION]",
"user_data): try: self._model.target_distance = int(user_data.distancia) except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Target Distance",
"self._myIntellect.reason() self._question.number = self._model.question self._arrow_model.value = self._model.arrow_model # Send the results to the",
": self._arrow_model.get_model_name() } return json.dumps( json_map ) def set_length(self, user_data): try: self._model.arm_length =",
"AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Poundage does not exists' ) def set_temperature(self, user_data):",
"int(user_data.libraje) except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Poundage does not exists' ) def",
"try: self._model.temperature = int(user_data.temperatura) except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Temperature does not",
"from intellect.Intellect import Intellect from MyIntellect import MyIntellect from Question import Question from",
"time, random import web import json from intellect.Intellect import Intellect from MyIntellect import",
") def set_length(self, user_data): try: self._model.arm_length = int(user_data.longitud) except AttributeError: logging.getLogger( 'ArrowSelection' ).error(",
"user_data): try: self._model.temperature = int(user_data.temperatura) except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Temperature does",
"self._arrow_model = Arrow_Model() self._myIntellect.learn( self._model ) self._myIntellect.reason() self._question.number = self._model.question self._arrow_model.value = self._model.arrow_model",
"Question import Question from Arrow_Model import Arrow_Model from Model import Model class Application(object):",
") def set_poundage(self, user_data): try: self._model.poundage = int(user_data.libraje) except AttributeError: logging.getLogger( 'ArrowSelection' ).error(",
"user_data): try: self._model.height = int(user_data.altura) except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Height does",
"MyIntellect import MyIntellect from Question import Question from Arrow_Model import Arrow_Model from Model",
"# the objects used by the policies user_data = web.input() self._model = Model()",
"does not exists' ) def set_poundage(self, user_data): try: self._model.poundage = int(user_data.libraje) except AttributeError:",
"int(user_data.temperatura) except AttributeError: logging.getLogger( 'ArrowSelection' ).error( '[APPLICATION] Temperature does not exists' ) def"
] |
[
"/> <probability> <probabilityItem probability=\"0.5\"> <ride busStop=\"2\" modes=\"public\" /> <probability> <probabilityItem probability=\"0.5\"> <stop busStop=\"2\"",
"Basically, you can have: .. code-block:: xml <personRoute id=\"route\"> <walk from=\"edge1\" busStop=\"1\"> <probability>",
"default is 1 - route : the id of the route that the",
"<ride /> <stop /> </personFlow> will generate person elements having the same children",
"\"\"\" super().__init__(xml_element) self.routes = routes self.attributes = {item[0]: item[1] for item in self.xml_element.items()}",
"id=\"route\"> <walk from=\"edge1\" busStop=\"1\"> <probability> <probabilityItem probability=\"0.5\"> <ride busStop=\"2\" modes=\"public\" /> </probabilityItem> <probabilityItem",
"if __name__ == \"__main__\": # Parses the command line arguments parser = argparse.ArgumentParser()",
"is not modified :param elements: A list containing xml elements and PersonGenerationElement objects.",
"attribute probability between 0 and 1\") if sum([child[0] for child in self.possibilities]) !=",
"id_attribute_key = \"id\" begin_attribute_key = \"begin\" end_attribute_key = \"end\" period_attribute_key = \"period\" number_attribute_key",
"50% chance they'll stay there during 10 ticks. The route followed by the",
"appropriate tag (the one defined in get_xml_tag) with an object of the current",
"p_id = 0 elements = list() while begin <= self.end: for i in",
"by converting an xml file (usually having the ``.pflow.xml`` extension) to a sumo",
"are taken into account & used to generate an alternative \"\"\" return self.generate_multiple(self.children)",
"copied to each person using it. You can use probabilities inside the **personRoute**",
"for child in children: routes.remove(child) PersonRouteElement.wrap_elements(children) person_routes = [child for child in children",
"which the flow starts - end : the time at which the flow",
"Probability elements can be nested, so you can have: .. code-block:: xml <probability>",
"alternatives with given probabilities. In XML it looks like: .. code-block:: xml <probability>",
"given for personFlow \" + str(id) + \", quitting\") exit(-1) try: self.per_wave =",
"are spawned in periodic waves with 10 persons pere wave. The route followed",
"the xml elements corresponding to this class (personRoute) \"\"\" return \"personRoute\" @staticmethod def",
"an alternative \"\"\" return self.generate_multiple(self.children) class PersonFlowElement(PersonGenerationElement): \"\"\" This class describes xml elements",
"and PersonGenerationElement objects. The PersonGenerationElement objects are replaced by elements generated from them",
"element.set(\"depart\", str(int(begin))) element.set(\"id\", self.id + \"_\" + str(p_id)) if self.route is not None:",
"p_id += 1 begin += self.period return elements def generate_persons(input_file, output_file): \"\"\" Core",
"elements generated from them The given list is not modified :param elements: A",
"can have: .. code-block:: xml <probability> <probabilityItem probability=\"0.5\"> <probability> ... </probability> ...Possibly other",
"def get_xml_tag(cls): \"\"\" :return: The tag of xml element coresponding to this class",
"persons will be `<id>_<person_index>` where `<person_index>` is the index of the person in",
"starts - end : the time at which the flow ends. Not mandatory,",
"self.default_end try: self.period = int(self.attributes.pop(self.period_attribute_key)) except KeyError: try: self.number = int(self.attributes.pop(self.number_attribute_key)) if self.number",
"self.period = int(self.attributes.pop(self.period_attribute_key)) except KeyError: try: self.number = int(self.attributes.pop(self.number_attribute_key)) if self.number == 1:",
"tag (the one defined in get_xml_tag) with an object of the current class.",
"given list is modified, be careful :param elements: a list of xml elements",
"element = etree.Element(\"person\", self.attributes) element.set(\"depart\", str(int(begin))) element.set(\"id\", self.id + \"_\" + str(p_id)) if",
"for vehicles. For example, this xml code: .. code-block:: xml <personFlow id=\"flow\" begin=\"0\"",
"self.attributes = {item[0]: item[1] for item in self.xml_element.items()} self.children = list(self.xml_element) ProbabilityElement.wrap_elements(self.children) self.id",
"<personRoute id=\"route\"> <walk from=\"edge1\" busStop=\"1\"> <probability> <probabilityItem probability=\"0.5\"> <ride busStop=\"2\" modes=\"public\" /> </probabilityItem>",
"of the sub elements of the original personRoute element probability elements are taken",
":type routes: collections.Iterable \"\"\" super().__init__(xml_element) self.routes = routes self.attributes = {item[0]: item[1] for",
"not modified and the result is written in another file. The resulting file",
"availability set forth in the Eclipse # Public License 2.0 are satisfied: GNU",
"in time between 0 and 3600 The complete attributes list is: - id",
"/> </personRoute> The content of the route is then copied to each person",
"it. You can use probabilities inside the **personRoute** element to have different alternatives.",
"flows of persons for a SUMO simulation which is currently not possible in",
"routes.remove(child) PersonRouteElement.wrap_elements(children) person_routes = [child for child in children if isinstance(child, PersonRouteElement)] PersonFlowElement.wrap_elements(children,",
"return self.generate_multiple(self.children) class PersonFlowElement(PersonGenerationElement): \"\"\" This class describes xml elements that are used",
"... </probability> ...Possibly other stuff </probabilityItem> <probabilityItem probability=\"0.5\"> second alternative </probabilityItem> </probability> This",
"so you can have: .. code-block:: xml <probability> <probabilityItem probability=\"0.5\"> <probability> ... </probability>",
"PersonGenerationElement.generate_multiple(children) person_elements.sort(key=lambda e: int(e.get('depart'))) routes.extend(person_elements) with open(output_file, \"w\") as f: f.write(etree.tostring(routes).decode()) f.close() if",
"in range(len(elements)): if not isinstance(elements[i], PersonGenerationElement) and elements[i].tag == cls.get_xml_tag(): elements[i] = cls(elements[i],",
"from lxml import etree import argparse import random class PersonGenerationElement(object): \"\"\" This class",
"(the one defined in get_xml_tag) with an object of the current class. The",
"of persons in each wave. Not mandatory, default is 1 - route :",
"bash python personGenerator.py pedestrians.pflow.xml pedestrians.rou.xml Note that the output file is overwritten without",
"The route followed by the persons is defined directly under the ``<personFlow>`` How",
"are used to define person routes separately. .. code-block:: xml <personRoute id=\"route\"> <walk",
"& used to generate an alternative \"\"\" return self.generate_multiple(self.children) class PersonFlowElement(PersonGenerationElement): \"\"\" This",
"return the xml tag for elements described by the current class \"\"\" raise",
"containing xml elements and PersonGenerationElement objects. :type elements: list :return: a list of",
"print(\"No id attribute in personFlow, quitting\") exit(-1) try: self.begin = int(self.attributes.pop(self.begin_attribute_key)) except KeyError:",
"== \"__main__\": # Parses the command line arguments parser = argparse.ArgumentParser() parser.add_argument(\"source\") parser.add_argument(\"destination\")",
"bus from stop 3 to stop 1 and then stopping there for 50",
"time. The original file is not modified and the result is written in",
"probability=\"0.5\"> <ride busStop=\"3\" modes=\"public\" /> </probabilityItem> </probability> </personRoute> \"\"\" def __init__(self, xml_element): super().__init__(xml_element)",
"!= self.get_xml_tag(): raise Exception(\"Bad tag\") @classmethod def get_xml_tag(cls): \"\"\" This class method is",
"line \" + str(self.xml_element.sourceline)) except KeyError: pass @classmethod def get_xml_tag(cls): \"\"\" :return: The",
"number given for personFlow \" + str(id) + \", quitting\") exit(-1) try: self.per_wave",
"element is asked to generate, it returns the children of one of its",
"+ \", quitting\") exit(-1) try: self.per_wave = int(self.attributes.pop(self.per_wave_attribute_key)) except KeyError: self.per_wave = 1",
"of the script, parses <personFlow> tags in an XML file and generates <person>",
"a list of xml elements :type elements: list \"\"\" for i in range(len(elements)):",
"generate(self): \"\"\" :return: A copy of the sub elements of the original personRoute",
"</probabilityItem> </probability> </personRoute> <personFlow id=\"forward\" begin=\"0\" end=\"3600\" number=\"7\" perWave=\"10\" departPos=\"0\" route=\"forward\" /> <personFlow",
"wave. Not mandatory, default is 1 - route : the id of the",
"to generate two flows of persons : - The first flow consists of",
"= 3600 id_attribute_key = \"id\" begin_attribute_key = \"begin\" end_attribute_key = \"end\" period_attribute_key =",
"xml file (usually having the ``.pflow.xml`` extension) to a sumo route file containing",
"personFlow \" + str(id) + \", quitting\") exit(-1) try: self.end = int(self.attributes.pop(self.end_attribute_key)) except",
"= PersonGenerationElement.generate_multiple(children) person_elements.sort(key=lambda e: int(e.get('depart'))) routes.extend(person_elements) with open(output_file, \"w\") as f: f.write(etree.tostring(routes).decode()) f.close()",
"We check for the attributes that concern us & we leave the others",
"- perWave : the number of persons in each wave. Not mandatory, default",
"there's a 50% chance they'll stay there during 10 ticks. The route followed",
"generate(self): \"\"\" This method is meant to be implemented by subclasses It should",
"<person> elements are sorted by their depart time. The original file is not",
"if isinstance(route, PersonRouteElement) and route.id == route_id: return route return None def generate(self):",
"of the person in the flow (starting from 0) \"\"\" default_end = 3600",
"2 # or later which is available at # https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html # SPDX-License-Identifier: EPL-2.0",
"float(sub_element.get(\"probability\")) if proba < 0 or proba > 1: raise ValueError(\"\") possibility =",
"0 or proba > 1: raise ValueError(\"\") possibility = (proba, list(sub_element)) ProbabilityElement.wrap_elements(possibility[1]) self.possibilities.append(possibility)",
"PersonRouteElement) and route.id == route_id: return route return None def generate(self): \"\"\" :return:",
"output file is overwritten without asking for permission. In your script ~~~~~~~~~~~~~~ You",
"look for routes :type routes: collections.Iterable \"\"\" super().__init__(xml_element) self.routes = routes self.attributes =",
"list is modified, be careful :param elements: a list of xml elements :type",
"<personFlow id=\"backward\" begin=\"0\" end=\"3600\" period=\"600\" perWave=\"10\" departPos=\"0\"> <walk from=\"e3\" busStop=\"3\" /> <ride busStop=\"1\"",
"@file personGenerator.py # @author <NAME> # @date 2019-03-22 \"\"\" This tool allows to",
"def generate(self): \"\"\" This method is meant to be implemented by subclasses It",
"The source xml element \"\"\" super().__init__(xml_element) self.possibilities = [] for sub_element in list(self.xml_element):",
"not given, number will be used - number : the number of waves.",
"**personRoute** element to have different alternatives. Basically, you can have: .. code-block:: xml",
"probability=\"0.5\"> <ride busStop=\"3\" modes=\"public\"> </probabilityItem> </probability> </personRoute> <personFlow id=\"forward\" begin=\"0\" end=\"3600\" number=\"7\" perWave=\"10\"",
"3 (with a 50% chance for each). The persons of this flow are",
"id=\"route-1\"> <walk from=\"e1\" busStop=\"1\" /> <probability> <probabilityItem probability=\"0.5\"> <ride busStop=\"2\" modes=\"public\" /> <probability>",
": - The first flow consists of persons taking a bus from stop",
"base for person generation elements \"\"\" def __init__(self, xml_element): self.xml_element = xml_element if",
"= self.attributes.pop(self.route_attribute_key) self.route = PersonRouteElement.get_route_by_id(routes, route_id) if self.route is None: raise Exception(\"Route with",
"output_file: The path of the output file \"\"\" # Parse the input file",
"is defined separately in a ``<personRoute>`` element and referenced by its ID. -",
":type routes: collections.Iterable :param route_id: :type route_id: str :return: The PersonRouteElement object having",
"class PersonGenerationElement(object): \"\"\" This class serves as a base for person generation elements",
".. code-block:: xml <personFlow id=\"flow\" begin=\"0\" end=\"3600\" number=\"7\" perWave=\"10\"> <walk /> <ride />",
"(C) 2019-2020 German Aerospace Center (DLR) and others. # This program and the",
"an input `.pflow.xml`` file's path and an output ``.rou.xml`` file's path. .. code-block::",
":return: The PersonRouteElement object having the given id from the given iterable. None",
"sorted by their depart time. The original file is not modified and the",
"taken into account & used to generate an alternative \"\"\" return self.generate_multiple(self.children) class",
"self.attributes.pop(self.route_attribute_key) self.route = PersonRouteElement.get_route_by_id(routes, route_id) if self.route is None: raise Exception(\"Route with id",
"int(self.attributes.pop(self.end_attribute_key)) except KeyError: self.end = self.default_end try: self.period = int(self.attributes.pop(self.period_attribute_key)) except KeyError: try:",
"</probability> </probabilityItem> <probabilityItem probability=\"0.5\"> <ride busStop=\"3\" modes=\"public\"> </probabilityItem> </probability> </personRoute> <personFlow id=\"forward\" begin=\"0\"",
"separately. .. code-block:: xml <personRoute id=\"route\"> <walk /> <stop /> <ride /> </personRoute>",
"and the accompanying materials are made available under the # terms of the",
"code-block:: xml <personRoute id=\"route\"> <walk /> <stop /> <ride /> </personRoute> The content",
"= list() while begin <= self.end: for i in range(self.per_wave): element = etree.Element(\"person\",",
"is meant to be implemented by subclasses It should return a list of",
"given probabilities. In XML it looks like: .. code-block:: xml <probability> <probabilityItem probability=\"0.5\">fist",
": the id of the route that the persons will follow Not mandatory,",
"you can have: .. code-block:: xml <probability> <probabilityItem probability=\"0.5\"> <probability> ... </probability> ...Possibly",
"https://www.eclipse.org/legal/epl-2.0/ # This Source Code may also be made available under the following",
"\" + str(id) + \", quitting\") exit(-1) try: self.end = int(self.attributes.pop(self.end_attribute_key)) except KeyError:",
"ProbabilityElement.wrap_elements(self.children) @classmethod def get_xml_tag(cls): \"\"\" :return: The tag of the xml elements corresponding",
"\"\"\" default_end = 3600 id_attribute_key = \"id\" begin_attribute_key = \"begin\" end_attribute_key = \"end\"",
"elements. The generated <person> elements are sorted by their depart time. The original",
"in range(self.per_wave): element = etree.Element(\"person\", self.attributes) element.set(\"depart\", str(int(begin))) element.set(\"id\", self.id + \"_\" +",
"[] for sub_element in list(self.xml_element): if sub_element.tag != \"probabilityItem\": raise Exception(\"Only probabilityItem elements",
"in children: routes.remove(child) PersonRouteElement.wrap_elements(children) person_routes = [child for child in children if isinstance(child,",
"return \"probability\" def generate(self): \"\"\" :return: One of the alternatives according to the",
"the ``.pflow.xml`` extension) to a sumo route file containing the generated <peron> elements.",
"in self.possibilities]) != 1: raise ValueError(\"Probabilities not summing up to 1 at line",
"stopping there for 50 ticks. The persons of this flow are spawned in",
"1 and then stopping there for 50 ticks. The persons of this flow",
"= \"number\" per_wave_attribute_key = \"perWave\" route_attribute_key = \"route\" def __init__(self, xml_element, routes): \"\"\"",
"corresponding to the current class (personFlow) \"\"\" return \"personFlow\" def generate(self): \"\"\" :return:",
"<walk from=\"edge1\" busStop=\"1\"> <probability> <probabilityItem probability=\"0.5\"> <ride busStop=\"2\" modes=\"public\" /> </probabilityItem> <probabilityItem probability=\"0.5\">",
"children of one of its alternatives according to the probabilities. Probability elements can",
"of persons taking a bus from stop 3 to stop 1 and then",
"== 1: self.period = (self.end - self.begin) * 2 + 1 else: self.period",
"chance for each). The persons of this flow are spawned in 7 waves",
"this module and use them in your own python script. See the documentation",
"\"\"\" :param xml_element: The xml element :param routes: An iterable where to look",
"tool allows to generate flows of persons for a SUMO simulation which is",
"= [child for child in children if isinstance(child, PersonRouteElement)] PersonFlowElement.wrap_elements(children, routes=person_routes) for person_route",
"not isinstance(elements[i], PersonGenerationElement) and elements[i].tag == cls.get_xml_tag(): elements[i] = cls(elements[i], *args, **kwargs) @staticmethod",
"alternative \"\"\" return self.generate_multiple(self.children) class PersonFlowElement(PersonGenerationElement): \"\"\" This class describes xml elements that",
"persons : - The first flow consists of persons taking a bus from",
"according to the probabilities. Probability elements can be nested, so you can have:",
"The original file is not modified and the result is written in another",
"which is available at # https://www.eclipse.org/legal/epl-2.0/ # This Source Code may also be",
"of the route that the persons will follow Not mandatory, if not given,",
"persons. For the persons going to bus stop 2, there's a 50% chance",
"to the given probabilities \"\"\" result = [] cumulated_probability = 0 p =",
"available under the following Secondary # Licenses when the conditions for such availability",
"will be `<id>_<person_index>` where `<person_index>` is the index of the person in the",
"50% chance for each). The persons of this flow are spawned in 7",
"= (proba, list(sub_element)) ProbabilityElement.wrap_elements(possibility[1]) self.possibilities.append(possibility) except (KeyError, ValueError): raise ValueError(\"probabilityItem element requires attribute",
"Code may also be made available under the following Secondary # Licenses when",
"None # We check for the attributes that concern us & we leave",
"(with a 50% chance for each). The persons of this flow are spawned",
"except KeyError: pass @classmethod def get_xml_tag(cls): \"\"\" :return: The tag of the xml",
"modified :param elements: A list containing xml elements and PersonGenerationElement objects. :type elements:",
":param elements: A list containing xml elements and PersonGenerationElement objects. :type elements: list",
"currently not possible in SUMO route files. It does so by converting an",
"proba > 1: raise ValueError(\"\") possibility = (proba, list(sub_element)) ProbabilityElement.wrap_elements(possibility[1]) self.possibilities.append(possibility) except (KeyError,",
"SUMO route files. It does so by converting an xml file (usually having",
"if sub_element.tag != \"probabilityItem\": raise Exception(\"Only probabilityItem elements are allowed inside probability\") try:",
"original personRoute element probability elements are taken into account & used to generate",
"ValueError(\"\") possibility = (proba, list(sub_element)) ProbabilityElement.wrap_elements(possibility[1]) self.possibilities.append(possibility) except (KeyError, ValueError): raise ValueError(\"probabilityItem element",
"for item in self.xml_element.items()} self.children = list(self.xml_element) ProbabilityElement.wrap_elements(self.children) self.id = None self.begin =",
"file and generates <person> elements. The generated <person> elements are sorted by their",
".. code-block:: xml <routes> <personRoute id=\"route-1\"> <walk from=\"e1\" busStop=\"1\" /> <probability> <probabilityItem probability=\"0.5\">",
"busStop=\"3\" modes=\"public\" /> </probabilityItem> </probability> </personRoute> \"\"\" def __init__(self, xml_element): super().__init__(xml_element) self.id =",
"xml elements corresponding to this class (personRoute) \"\"\" return \"personRoute\" @staticmethod def get_route_by_id(routes,",
"The id of generated persons will be `<id>_<person_index>` where `<person_index>` is the index",
"to have different alternatives. Basically, you can have: .. code-block:: xml <personRoute id=\"route\">",
"= {item[0]: item[1] for item in self.xml_element.items()} self.children = list(self.xml_element) ProbabilityElement.wrap_elements(self.children) self.id =",
"attribute in personFlow, quitting\") exit(-1) try: self.begin = int(self.attributes.pop(self.begin_attribute_key)) except KeyError: print(\"No begin",
"is already possible for vehicles. For example, this xml code: .. code-block:: xml",
"list() for element in elements: if isinstance(element, PersonGenerationElement): result.extend(element.generate()) else: result.append(element.__copy__()) return result",
"list containing xml elements and PersonGenerationElement objects. :type elements: list :return: a list",
"use probabilities inside the **personRoute** element to have different alternatives. Basically, you can",
"generate person elements having the same children (walk, ride, stop). The generated persons",
"the xml tag for elements described by the current class \"\"\" raise NotImplementedError",
"if not isinstance(elements[i], PersonGenerationElement) and elements[i].tag == cls.get_xml_tag(): elements[i] = cls(elements[i], *args, **kwargs)",
"generate, it returns the children of one of its alternatives according to the",
"element.extend(self.generate_multiple(self.children)) elements.append(element) p_id += 1 begin += self.period return elements def generate_persons(input_file, output_file):",
"be made available under the following Secondary # Licenses when the conditions for",
"there during 10 ticks. The route followed by the persons of this flow",
"should return a list of elements generated by the element \"\"\" raise NotImplementedError",
"either stop 2 or stop 3 (with a 50% chance for each). The",
"class describes probability elements that are used to generate alternatives with given probabilities.",
"str(self.xml_element.sourceline)) @classmethod def get_xml_tag(cls): \"\"\" :return: The tag of xml element coresponding to",
"\"personRoute\" @staticmethod def get_route_by_id(routes, route_id): \"\"\" :param routes: :type routes: collections.Iterable :param route_id:",
"of the alternatives according to the given probabilities \"\"\" result = [] cumulated_probability",
"a base for person generation elements \"\"\" def __init__(self, xml_element): self.xml_element = xml_element",
"a direct child of <probabilityItem> \"\"\" def __init__(self, xml_element): \"\"\" :param xml_element: The",
"cumulated_probability: result.extend(self.generate_multiple(possibility[1])) break return result class PersonRouteElement(PersonGenerationElement): \"\"\" This class describes xml elements",
"method is meant to be implemented by subclasses It should return the xml",
"to define conditional probabilities. Note that the nested <probability> element should be a",
"time the element is asked to generate, it returns the children of one",
"available at # https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html # SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later # @file personGenerator.py #",
"available at # https://www.eclipse.org/legal/epl-2.0/ # This Source Code may also be made available",
"- The second flow consists of persons taking a bus from stop 3",
"xml <personRoute id=\"route\"> <walk from=\"edge1\" busStop=\"1\"> <probability> <probabilityItem probability=\"0.5\"> <ride busStop=\"2\" modes=\"public\" />",
"seconds) between two consecutive waves. Not mandatory, if not given, number will be",
"elements corresponding to the current class (personFlow) \"\"\" return \"personFlow\" def generate(self): \"\"\"",
"stop 3 (with a 50% chance for each). The persons of this flow",
"\"route\" def __init__(self, xml_element, routes): \"\"\" :param xml_element: The xml element :param routes:",
"end : the time at which the flow ends. Not mandatory, default is",
"import random class PersonGenerationElement(object): \"\"\" This class serves as a base for person",
"of the xml elements corresponding to this class (personRoute) \"\"\" return \"personRoute\" @staticmethod",
"= int(self.attributes.pop(self.period_attribute_key)) except KeyError: try: self.number = int(self.attributes.pop(self.number_attribute_key)) if self.number == 1: self.period",
"The generated persons will be in 7 waves each containing 10 persons. These",
"+= float(possibility[0]) if p <= cumulated_probability: result.extend(self.generate_multiple(possibility[1])) break return result class PersonRouteElement(PersonGenerationElement): \"\"\"",
"probabilities. In XML it looks like: .. code-block:: xml <probability> <probabilityItem probability=\"0.5\">fist alternative</probabilityItem>",
"<probabilityItem probability=\"0.5\"> <ride busStop=\"3\" modes=\"public\" /> </probabilityItem> </probability> </personRoute> \"\"\" def __init__(self, xml_element):",
"General Public License, version 2 # or later which is available at #",
"XML file and generates <person> elements. The generated <person> elements are sorted by",
"<walk from=\"e3\" busStop=\"3\" /> <ride busStop=\"1\" modes=\"public\"/> <stop busStop=\"1\" duration=\"50\"/> </personFlow> </routes> The",
"``.pflow.xml`` : .. code-block:: xml <routes> <personRoute id=\"route-1\"> <walk from=\"e1\" busStop=\"1\" /> <probability>",
"routes: An iterable where to look for routes :type routes: collections.Iterable \"\"\" super().__init__(xml_element)",
"\"\"\" from lxml import etree import argparse import random class PersonGenerationElement(object): \"\"\" This",
"class (personRoute) \"\"\" return \"personRoute\" @staticmethod def get_route_by_id(routes, route_id): \"\"\" :param routes: :type",
"This class describes xml elements that are used to generate flows of persons",
"+ str(p_id)) if self.route is not None: element.extend(self.route.generate()) else: element.extend(self.generate_multiple(self.children)) elements.append(element) p_id +=",
":param xml_element: The xml element :param routes: An iterable where to look for",
"persons is defined directly under the ``<personFlow>`` How to Use ---------- Via Command",
"serves as a base for person generation elements \"\"\" def __init__(self, xml_element): self.xml_element",
"str(id) + \", quitting\") exit(-1) try: self.per_wave = int(self.attributes.pop(self.per_wave_attribute_key)) except KeyError: self.per_wave =",
"that the persons will follow Not mandatory, if not given, uses the children",
"meant to be implemented by subclasses It should return a list of elements",
"exist :param input_file: The path of the input file :param output_file: The path",
"taking a bus from stop 3 to stop 1 and then stopping there",
"f: f.write(etree.tostring(routes).decode()) f.close() if __name__ == \"__main__\": # Parses the command line arguments",
"modified, be careful :param elements: a list of xml elements :type elements: list",
"1 try: route_id = self.attributes.pop(self.route_attribute_key) self.route = PersonRouteElement.get_route_by_id(routes, route_id) if self.route is None:",
"of the xml elements corresponding to the current class (personFlow) \"\"\" return \"personFlow\"",
"flow \"\"\" begin = self.begin p_id = 0 elements = list() while begin",
"check for the attributes that concern us & we leave the others try:",
"in personFlow \" + str(id) + \", quitting\") exit(-1) try: self.end = int(self.attributes.pop(self.end_attribute_key))",
"return \"personRoute\" @staticmethod def get_route_by_id(routes, route_id): \"\"\" :param routes: :type routes: collections.Iterable :param",
"code-block:: xml <routes> <personRoute id=\"route-1\"> <walk from=\"e1\" busStop=\"1\" /> <probability> <probabilityItem probability=\"0.5\"> <ride",
"that are used to generate alternatives with given probabilities. In XML it looks",
"generate an alternative \"\"\" return self.generate_multiple(self.children) class PersonFlowElement(PersonGenerationElement): \"\"\" This class describes xml",
"input file :param output_file: The path of the output file \"\"\" # Parse",
"objects are replaced by elements generated from them The given list is not",
"separated in time) and each wave consists of 10 persons. For the persons",
"except KeyError: print(\"Neither period nor number given for personFlow \" + str(id) +",
"and 1\") if sum([child[0] for child in self.possibilities]) != 1: raise ValueError(\"Probabilities not",
"the original personRoute element probability elements are taken into account & used to",
"open(output_file, \"w\") as f: f.write(etree.tostring(routes).decode()) f.close() if __name__ == \"__main__\": # Parses the",
"number_attribute_key = \"number\" per_wave_attribute_key = \"perWave\" route_attribute_key = \"route\" def __init__(self, xml_element, routes):",
"each wave. Not mandatory, default is 1 - route : the id of",
"list \"\"\" result = list() for element in elements: if isinstance(element, PersonGenerationElement): result.extend(element.generate())",
"<probabilityItem probability=\"0.5\">fist alternative</probabilityItem> <probabilityItem probability=\"0.5\">second alternative</probabilityItem> </probability> Each time the element is asked",
"p = random.random() for possibility in self.possibilities: cumulated_probability += float(possibility[0]) if p <=",
"<NAME> # @date 2019-03-22 \"\"\" This tool allows to generate flows of persons",
"modes=\"public\" /> </probabilityItem> <probabilityItem probability=\"0.5\"> <ride busStop=\"3\" modes=\"public\" /> </probabilityItem> </probability> </personRoute> \"\"\"",
"\"\"\" This class describes probability elements that are used to generate alternatives with",
"PersonRouteElement.get_route_by_id(routes, route_id) if self.route is None: raise Exception(\"Route with id \" + route_id",
"<personFlow> tags in an XML file and generates <person> elements. The generated <person>",
"between two consecutive waves. Not mandatory, if not given, number will be used",
"the current class \"\"\" raise NotImplementedError def generate(self): \"\"\" This method is meant",
"replaced by elements generated from them The given list is not modified :param",
"if sum([child[0] for child in self.possibilities]) != 1: raise ValueError(\"Probabilities not summing up",
"generate two flows of persons : - The first flow consists of persons",
"= [] cumulated_probability = 0 p = random.random() for possibility in self.possibilities: cumulated_probability",
"of persons for a SUMO simulation which is currently not possible in SUMO",
"= xml_element if self.xml_element.tag != self.get_xml_tag(): raise Exception(\"Bad tag\") @classmethod def get_xml_tag(cls): \"\"\"",
"a list containing xml elements and PersonGenerationElement objects. The PersonGenerationElement objects are replaced",
"= routes self.attributes = {item[0]: item[1] for item in self.xml_element.items()} self.children = list(self.xml_element)",
"+ str(self.xml_element.sourceline)) except KeyError: pass @classmethod def get_xml_tag(cls): \"\"\" :return: The tag of",
"for person generation elements \"\"\" def __init__(self, xml_element): self.xml_element = xml_element if self.xml_element.tag",
"at # https://www.eclipse.org/legal/epl-2.0/ # This Source Code may also be made available under",
"elements: list \"\"\" for i in range(len(elements)): if not isinstance(elements[i], PersonGenerationElement) and elements[i].tag",
"generated from them The given list is not modified :param elements: A list",
"define person routes separately. .. code-block:: xml <personRoute id=\"route\"> <walk /> <stop />",
"persons taking a bus from stop 3 to stop 1 and then stopping",
"by its ID. - The second flow consists of persons taking a bus",
"return result class PersonRouteElement(PersonGenerationElement): \"\"\" This class describes xml elements that are used",
"1 - route : the id of the route that the persons will",
"The second flow consists of persons taking a bus from stop 3 to",
"raise ValueError(\"Probabilities not summing up to 1 at line : \" + str(self.xml_element.sourceline))",
"elements and PersonGenerationElement objects. :type elements: list :return: a list of resulting xml",
"containing the generated <peron> elements. Here is an example ``.pflow.xml`` : .. code-block::",
"\"\"\" Core method of the script, parses <personFlow> tags in an XML file",
"by elements generated from them The given list is not modified :param elements:",
"with open(output_file, \"w\") as f: f.write(etree.tostring(routes).decode()) f.close() if __name__ == \"__main__\": # Parses",
"route files. It does so by converting an xml file (usually having the",
"the output file is overwritten if it is already exist :param input_file: The",
"the output file is overwritten without asking for permission. In your script ~~~~~~~~~~~~~~",
"__init__(self, xml_element): super().__init__(xml_element) self.id = self.xml_element.get(\"id\") self.children = list(self.xml_element) ProbabilityElement.wrap_elements(self.children) @classmethod def get_xml_tag(cls):",
"it is already exist :param input_file: The path of the input file :param",
"and elements[i].tag == cls.get_xml_tag(): elements[i] = cls(elements[i], *args, **kwargs) @staticmethod def generate_multiple(elements): \"\"\"",
"It does so by converting an xml file (usually having the ``.pflow.xml`` extension)",
"such availability set forth in the Eclipse # Public License 2.0 are satisfied:",
"An iterable where to look for routes :type routes: collections.Iterable \"\"\" super().__init__(xml_element) self.routes",
"elements. Here is an example ``.pflow.xml`` : .. code-block:: xml <routes> <personRoute id=\"route-1\">",
"with the appropriate tag (the one defined in get_xml_tag) with an object of",
"self.route = None # We check for the attributes that concern us &",
"current class. The given list is modified, be careful :param elements: a list",
"def get_xml_tag(cls): \"\"\" This class method is meant to be implemented by subclasses",
"(DLR) and others. # This program and the accompanying materials are made available",
"@classmethod def wrap_elements(cls, elements, *args, **kwargs): \"\"\" Replaces xml elements with the appropriate",
"persons for a SUMO simulation which is currently not possible in SUMO route",
"made available under the following Secondary # Licenses when the conditions for such",
"return \"personFlow\" def generate(self): \"\"\" :return: The persons of the flow \"\"\" begin",
"them in your own python script. See the documentation below for more details.",
"does so by converting an xml file (usually having the ``.pflow.xml`` extension) to",
"except KeyError: self.end = self.default_end try: self.period = int(self.attributes.pop(self.period_attribute_key)) except KeyError: try: self.number",
":return: A copy of the sub elements of the original personRoute element probability",
"is overwritten if it is already exist :param input_file: The path of the",
"the generated <peron> elements. Here is an example ``.pflow.xml`` : .. code-block:: xml",
"the persons of this flow is defined separately in a ``<personRoute>`` element and",
"/> </probability> </probabilityItem> <probabilityItem probability=\"0.5\"> <ride busStop=\"3\" modes=\"public\"> </probabilityItem> </probability> </personRoute> <personFlow id=\"forward\"",
"random class PersonGenerationElement(object): \"\"\" This class serves as a base for person generation",
"for child in self.possibilities]) != 1: raise ValueError(\"Probabilities not summing up to 1",
"person in the flow (starting from 0) \"\"\" default_end = 3600 id_attribute_key =",
"\"\"\" result = [] cumulated_probability = 0 p = random.random() for possibility in",
"routes self.attributes = {item[0]: item[1] for item in self.xml_element.items()} self.children = list(self.xml_element) ProbabilityElement.wrap_elements(self.children)",
"The xml element :param routes: An iterable where to look for routes :type",
"of the route is then copied to each person using it. You can",
"\"begin\" end_attribute_key = \"end\" period_attribute_key = \"period\" number_attribute_key = \"number\" per_wave_attribute_key = \"perWave\"",
"= None self.begin = None self.period = None self.route = None # We",
"file. The resulting file will not contain the <personFlow> elements. Note that the",
"not possible in SUMO route files. It does so by converting an xml",
"line : \" + str(self.xml_element.sourceline)) @classmethod def get_xml_tag(cls): \"\"\" :return: The tag of",
"routes: :type routes: collections.Iterable :param route_id: :type route_id: str :return: The PersonRouteElement object",
"- route : the id of the route that the persons will follow",
"from 0) \"\"\" default_end = 3600 id_attribute_key = \"id\" begin_attribute_key = \"begin\" end_attribute_key",
"+ str(id) + \", quitting\") exit(-1) try: self.per_wave = int(self.attributes.pop(self.per_wave_attribute_key)) except KeyError: self.per_wave",
"10 persons. For the persons going to bus stop 2, there's a 50%",
"3600. - period : The time (in seconds) between two consecutive waves. Not",
"Not mandatory, if not given, uses the children of the <personFlow> element The",
"when the conditions for such availability set forth in the Eclipse # Public",
"file containing the generated <peron> elements. Here is an example ``.pflow.xml`` : ..",
"10 ticks. The route followed by the persons of this flow is defined",
"personFlow, quitting\") exit(-1) try: self.begin = int(self.attributes.pop(self.begin_attribute_key)) except KeyError: print(\"No begin in personFlow",
"<ride /> </personRoute> The content of the route is then copied to each",
"Exception(\"Only probabilityItem elements are allowed inside probability\") try: proba = float(sub_element.get(\"probability\")) if proba",
"\"\"\" for route in routes: if isinstance(route, PersonRouteElement) and route.id == route_id: return",
"of resulting xml elements :rtype list \"\"\" result = list() for element in",
"nor number given for personFlow \" + str(id) + \", quitting\") exit(-1) try:",
"iterable. None if not found \"\"\" for route in routes: if isinstance(route, PersonRouteElement)",
"second alternative </probabilityItem> </probability> This allows you to define conditional probabilities. Note that",
"possible for vehicles. For example, this xml code: .. code-block:: xml <personFlow id=\"flow\"",
"elements having the same children (walk, ride, stop). The generated persons will be",
"= \"period\" number_attribute_key = \"number\" per_wave_attribute_key = \"perWave\" route_attribute_key = \"route\" def __init__(self,",
"to stop 1 and then stopping there for 50 ticks. The persons of",
"Use ---------- Via Command Line ~~~~~~~~~~~~~~~~ This script can be accessed directly by",
"end=\"3600\" number=\"7\" perWave=\"10\" departPos=\"0\" route=\"forward\" /> <personFlow id=\"backward\" begin=\"0\" end=\"3600\" period=\"600\" perWave=\"10\" departPos=\"0\">",
"is an example ``.pflow.xml`` : .. code-block:: xml <routes> <personRoute id=\"route-1\"> <walk from=\"e1\"",
"the flow \"\"\" begin = self.begin p_id = 0 elements = list() while",
"period : The time (in seconds) between two consecutive waves. Not mandatory, if",
"self.generate_multiple(self.children) class PersonFlowElement(PersonGenerationElement): \"\"\" This class describes xml elements that are used to",
"modes=\"public\"> </probabilityItem> </probability> </personRoute> <personFlow id=\"forward\" begin=\"0\" end=\"3600\" number=\"7\" perWave=\"10\" departPos=\"0\" route=\"forward\" />",
"= (self.end - self.begin) / (self.number - 1) except KeyError: print(\"Neither period nor",
"</probability> Each time the element is asked to generate, it returns the children",
"be equally separated in time between 0 and 3600 The complete attributes list",
"raise ValueError(\"probabilityItem element requires attribute probability between 0 and 1\") if sum([child[0] for",
"are used to generate flows of persons as it is already possible for",
"* 2 + 1 else: self.period = (self.end - self.begin) / (self.number -",
"generate(self): \"\"\" :return: The persons of the flow \"\"\" begin = self.begin p_id",
"in each wave. Not mandatory, default is 1 - route : the id",
"program and the accompanying materials are made available under the # terms of",
"PersonGenerationElement(object): \"\"\" This class serves as a base for person generation elements \"\"\"",
"the input file tree = etree.parse(input_file) routes = tree.getroot() children = list(routes) for",
"# Licenses when the conditions for such availability set forth in the Eclipse",
".. code-block:: xml <probability> <probabilityItem probability=\"0.5\"> <probability> ... </probability> ...Possibly other stuff </probabilityItem>",
"equally separated in time between 0 and 3600 The complete attributes list is:",
"\"perWave\" route_attribute_key = \"route\" def __init__(self, xml_element, routes): \"\"\" :param xml_element: The xml",
"ProbabilityElement.wrap_elements(possibility[1]) self.possibilities.append(possibility) except (KeyError, ValueError): raise ValueError(\"probabilityItem element requires attribute probability between 0",
"<walk /> <stop /> <ride /> </personRoute> The content of the route is",
"with id \" + route_id + \" not found at line \" +",
"file (usually having the ``.pflow.xml`` extension) to a sumo route file containing the",
"NotImplementedError def generate(self): \"\"\" This method is meant to be implemented by subclasses",
"elements = list() while begin <= self.end: for i in range(self.per_wave): element =",
"accessed directly by command line passing an input `.pflow.xml`` file's path and an",
"See the documentation below for more details. \"\"\" from lxml import etree import",
"0 and 1\") if sum([child[0] for child in self.possibilities]) != 1: raise ValueError(\"Probabilities",
"etree.Element(\"person\", self.attributes) element.set(\"depart\", str(int(begin))) element.set(\"id\", self.id + \"_\" + str(p_id)) if self.route is",
"generated <peron> elements. Here is an example ``.pflow.xml`` : .. code-block:: xml <routes>",
"\"probabilityItem\": raise Exception(\"Only probabilityItem elements are allowed inside probability\") try: proba = float(sub_element.get(\"probability\"))",
"the attributes that concern us & we leave the others try: self.id =",
"def get_xml_tag(cls): \"\"\" :return: The tag of the xml elements corresponding to the",
"example, this xml code: .. code-block:: xml <personFlow id=\"flow\" begin=\"0\" end=\"3600\" number=\"7\" perWave=\"10\">",
"GPL-2.0-or-later # @file personGenerator.py # @author <NAME> # @date 2019-03-22 \"\"\" This tool",
"personGenerator.py pedestrians.pflow.xml pedestrians.rou.xml Note that the output file is overwritten without asking for",
"One of the alternatives according to the given probabilities \"\"\" result = []",
"with an object of the current class. The given list is modified, be",
"Source Code may also be made available under the following Secondary # Licenses",
"probability=\"0.5\">fist alternative</probabilityItem> <probabilityItem probability=\"0.5\">second alternative</probabilityItem> </probability> Each time the element is asked to",
"is: - id - begin : the time at which the flow starts",
"\"__main__\": # Parses the command line arguments parser = argparse.ArgumentParser() parser.add_argument(\"source\") parser.add_argument(\"destination\") source,",
"during 10 ticks. The route followed by the persons of this flow is",
"used - number : the number of waves. Only meaningful when period is",
"self.routes = routes self.attributes = {item[0]: item[1] for item in self.xml_element.items()} self.children =",
"try: self.per_wave = int(self.attributes.pop(self.per_wave_attribute_key)) except KeyError: self.per_wave = 1 try: route_id = self.attributes.pop(self.route_attribute_key)",
"KeyError: print(\"No id attribute in personFlow, quitting\") exit(-1) try: self.begin = int(self.attributes.pop(self.begin_attribute_key)) except",
"\"\"\" begin = self.begin p_id = 0 elements = list() while begin <=",
"xml element coresponding to this class (probability) \"\"\" return \"probability\" def generate(self): \"\"\"",
"a 50% chance they'll stay there during 10 ticks. The route followed by",
"(equally separated in time) and each wave consists of 10 persons. For the",
"except KeyError: print(\"No begin in personFlow \" + str(id) + \", quitting\") exit(-1)",
"command line passing an input `.pflow.xml`` file's path and an output ``.rou.xml`` file's",
"str(int(begin))) element.set(\"id\", self.id + \"_\" + str(p_id)) if self.route is not None: element.extend(self.route.generate())",
"used to define person routes separately. .. code-block:: xml <personRoute id=\"route\"> <walk />",
"an output ``.rou.xml`` file's path. .. code-block:: bash python personGenerator.py pedestrians.pflow.xml pedestrians.rou.xml Note",
"concern us & we leave the others try: self.id = self.attributes.pop(self.id_attribute_key) except KeyError:",
"time between 0 and 3600 The complete attributes list is: - id -",
"in the Eclipse # Public License 2.0 are satisfied: GNU General Public License,",
"referenced by its ID. - The second flow consists of persons taking a",
"allows to generate flows of persons for a SUMO simulation which is currently",
"flow consists of persons taking a bus from stop 3 to stop 1",
"The first flow consists of persons taking a bus from stop 1 to",
"by subclasses It should return a list of elements generated by the element",
"element The id of generated persons will be `<id>_<person_index>` where `<person_index>` is the",
"float(possibility[0]) if p <= cumulated_probability: result.extend(self.generate_multiple(possibility[1])) break return result class PersonRouteElement(PersonGenerationElement): \"\"\" This",
"in routes: if isinstance(route, PersonRouteElement) and route.id == route_id: return route return None",
"number=\"7\" perWave=\"10\"> <walk /> <ride /> <stop /> </personFlow> will generate person elements",
"accompanying materials are made available under the # terms of the Eclipse Public",
"\"\"\" :return: A copy of the sub elements of the original personRoute element",
"__init__(self, xml_element, routes): \"\"\" :param xml_element: The xml element :param routes: An iterable",
"self.end = self.default_end try: self.period = int(self.attributes.pop(self.period_attribute_key)) except KeyError: try: self.number = int(self.attributes.pop(self.number_attribute_key))",
"# SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later # @file personGenerator.py # @author <NAME> # @date",
"= \"begin\" end_attribute_key = \"end\" period_attribute_key = \"period\" number_attribute_key = \"number\" per_wave_attribute_key =",
"the xml elements corresponding to the current class (personFlow) \"\"\" return \"personFlow\" def",
"int(self.attributes.pop(self.number_attribute_key)) if self.number == 1: self.period = (self.end - self.begin) * 2 +",
"id=\"route\"> <walk /> <stop /> <ride /> </personRoute> The content of the route",
"xml_element): \"\"\" :param xml_element: The source xml element \"\"\" super().__init__(xml_element) self.possibilities = []",
"1: self.period = (self.end - self.begin) * 2 + 1 else: self.period =",
"describes xml elements that are used to define person routes separately. .. code-block::",
"The time (in seconds) between two consecutive waves. Not mandatory, if not given,",
"self.number = int(self.attributes.pop(self.number_attribute_key)) if self.number == 1: self.period = (self.end - self.begin) *",
"be implemented by subclasses It should return the xml tag for elements described",
"to the probabilities. Probability elements can be nested, so you can have: ..",
"mandatory, if not given, number will be used - number : the number",
"<probability> <probabilityItem probability=\"0.5\"> <stop busStop=\"2\" duration=\"10\" /> </probabilityItem> <probabilityItem probability=\"0.5\" /> </probability> </probabilityItem>",
"time) and each wave consists of 10 persons. For the persons going to",
"#!/usr/bin/env python # Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo # Copyright",
"is then copied to each person using it. You can use probabilities inside",
"the persons will follow Not mandatory, if not given, uses the children of",
"<probabilityItem probability=\"0.5\">second alternative</probabilityItem> </probability> Each time the element is asked to generate, it",
":type elements: list \"\"\" for i in range(len(elements)): if not isinstance(elements[i], PersonGenerationElement) and",
"be used - number : the number of waves. Only meaningful when period",
"in personFlow, quitting\") exit(-1) try: self.begin = int(self.attributes.pop(self.begin_attribute_key)) except KeyError: print(\"No begin in",
"begin = self.begin p_id = 0 elements = list() while begin <= self.end:",
"<= self.end: for i in range(self.per_wave): element = etree.Element(\"person\", self.attributes) element.set(\"depart\", str(int(begin))) element.set(\"id\",",
"or later which is available at # https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html # SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later",
"+ str(id) + \", quitting\") exit(-1) try: self.end = int(self.attributes.pop(self.end_attribute_key)) except KeyError: self.end",
"objects. The PersonGenerationElement objects are replaced by elements generated from them The given",
"not contain the <personFlow> elements. Note that the output file is overwritten if",
"into account & used to generate an alternative \"\"\" return self.generate_multiple(self.children) class PersonFlowElement(PersonGenerationElement):",
"The path of the input file :param output_file: The path of the output",
"used to generate alternatives with given probabilities. In XML it looks like: ..",
"2 + 1 else: self.period = (self.end - self.begin) / (self.number - 1)",
"meant to be implemented by subclasses It should return the xml tag for",
"perWave=\"10\" departPos=\"0\" route=\"forward\" /> <personFlow id=\"backward\" begin=\"0\" end=\"3600\" period=\"600\" perWave=\"10\" departPos=\"0\"> <walk from=\"e3\"",
"in list(self.xml_element): if sub_element.tag != \"probabilityItem\": raise Exception(\"Only probabilityItem elements are allowed inside",
"is None: raise Exception(\"Route with id \" + route_id + \" not found",
"index of the person in the flow (starting from 0) \"\"\" default_end =",
"The given list is modified, be careful :param elements: a list of xml",
"is 1 - route : the id of the route that the persons",
"ID. - The second flow consists of persons taking a bus from stop",
"quitting\") exit(-1) try: self.begin = int(self.attributes.pop(self.begin_attribute_key)) except KeyError: print(\"No begin in personFlow \"",
"generate_persons(input_file, output_file): \"\"\" Core method of the script, parses <personFlow> tags in an",
"the flow ends. Not mandatory, default is 3600. - period : The time",
"elements: if isinstance(element, PersonGenerationElement): result.extend(element.generate()) else: result.append(element.__copy__()) return result class ProbabilityElement(PersonGenerationElement): \"\"\" This",
"alternatives according to the given probabilities \"\"\" result = [] cumulated_probability = 0",
"+= 1 begin += self.period return elements def generate_persons(input_file, output_file): \"\"\" Core method",
"converting an xml file (usually having the ``.pflow.xml`` extension) to a sumo route",
"from them The given list is not modified :param elements: A list containing",
"from=\"e1\" busStop=\"1\" /> <probability> <probabilityItem probability=\"0.5\"> <ride busStop=\"2\" modes=\"public\" /> <probability> <probabilityItem probability=\"0.5\">",
"the appropriate tag (the one defined in get_xml_tag) with an object of the",
"children if isinstance(child, PersonRouteElement)] PersonFlowElement.wrap_elements(children, routes=person_routes) for person_route in person_routes: children.remove(person_route) person_elements =",
"below for more details. \"\"\" from lxml import etree import argparse import random",
"made available under the # terms of the Eclipse Public License 2.0 which",
"flow starts - end : the time at which the flow ends. Not",
"self.id = self.xml_element.get(\"id\") self.children = list(self.xml_element) ProbabilityElement.wrap_elements(self.children) @classmethod def get_xml_tag(cls): \"\"\" :return: The",
"tag of the xml elements corresponding to this class (personRoute) \"\"\" return \"personRoute\"",
"elements: list :return: a list of resulting xml elements :rtype list \"\"\" result",
"def get_route_by_id(routes, route_id): \"\"\" :param routes: :type routes: collections.Iterable :param route_id: :type route_id:",
"mandatory, default is 1 - route : the id of the route that",
"= int(self.attributes.pop(self.begin_attribute_key)) except KeyError: print(\"No begin in personFlow \" + str(id) + \",",
"generate flows of persons as it is already possible for vehicles. For example,",
"number of persons in each wave. Not mandatory, default is 1 - route",
"be a direct child of <probabilityItem> \"\"\" def __init__(self, xml_element): \"\"\" :param xml_element:",
"i in range(self.per_wave): element = etree.Element(\"person\", self.attributes) element.set(\"depart\", str(int(begin))) element.set(\"id\", self.id + \"_\"",
"example above allows to generate two flows of persons : - The first",
"line arguments parser = argparse.ArgumentParser() parser.add_argument(\"source\") parser.add_argument(\"destination\") source, destination = parser.parse_args() generate_persons(source, destination)",
"</personRoute> \"\"\" def __init__(self, xml_element): super().__init__(xml_element) self.id = self.xml_element.get(\"id\") self.children = list(self.xml_element) ProbabilityElement.wrap_elements(self.children)",
"the command line arguments parser = argparse.ArgumentParser() parser.add_argument(\"source\") parser.add_argument(\"destination\") source, destination = parser.parse_args()",
"<probabilityItem probability=\"0.5\" /> </probability> </probabilityItem> <probabilityItem probability=\"0.5\"> <ride busStop=\"3\" modes=\"public\"> </probabilityItem> </probability> </personRoute>",
"to define person routes separately. .. code-block:: xml <personRoute id=\"route\"> <walk /> <stop",
"used to generate an alternative \"\"\" return self.generate_multiple(self.children) class PersonFlowElement(PersonGenerationElement): \"\"\" This class",
"<peron> elements. Here is an example ``.pflow.xml`` : .. code-block:: xml <routes> <personRoute",
"isinstance(route, PersonRouteElement) and route.id == route_id: return route return None def generate(self): \"\"\"",
"the given iterable. None if not found \"\"\" for route in routes: if",
"class method is meant to be implemented by subclasses It should return the",
"to generate flows of persons as it is already possible for vehicles. For",
":param routes: An iterable where to look for routes :type routes: collections.Iterable \"\"\"",
"(usually having the ``.pflow.xml`` extension) to a sumo route file containing the generated",
"persons of this flow is defined separately in a ``<personRoute>`` element and referenced",
"2 or stop 3 (with a 50% chance for each). The persons of",
"The generated <person> elements are sorted by their depart time. The original file",
"etree.parse(input_file) routes = tree.getroot() children = list(routes) for child in children: routes.remove(child) PersonRouteElement.wrap_elements(children)",
"separately in a ``<personRoute>`` element and referenced by its ID. - The second",
"begin += self.period return elements def generate_persons(input_file, output_file): \"\"\" Core method of the",
"to generate alternatives with given probabilities. In XML it looks like: .. code-block::",
": the number of waves. Only meaningful when period is not specified -",
"of one of its alternatives according to the probabilities. Probability elements can be",
"asking for permission. In your script ~~~~~~~~~~~~~~ You can import the classes and",
"route_id): \"\"\" :param routes: :type routes: collections.Iterable :param route_id: :type route_id: str :return:",
"PersonRouteElement object having the given id from the given iterable. None if not",
"begin <= self.end: for i in range(self.per_wave): element = etree.Element(\"person\", self.attributes) element.set(\"depart\", str(int(begin)))",
"This tool allows to generate flows of persons for a SUMO simulation which",
"</personRoute> <personFlow id=\"forward\" begin=\"0\" end=\"3600\" number=\"7\" perWave=\"10\" departPos=\"0\" route=\"forward\" /> <personFlow id=\"backward\" begin=\"0\"",
"at line \" + str(self.xml_element.sourceline)) except KeyError: pass @classmethod def get_xml_tag(cls): \"\"\" :return:",
"xml <probability> <probabilityItem probability=\"0.5\"> <probability> ... </probability> ...Possibly other stuff </probabilityItem> <probabilityItem probability=\"0.5\">",
"following Secondary # Licenses when the conditions for such availability set forth in",
"/> </probabilityItem> <probabilityItem probability=\"0.5\"> <ride busStop=\"3\" modes=\"public\" /> </probabilityItem> </probability> </personRoute> \"\"\" def",
"of generated persons will be `<id>_<person_index>` where `<person_index>` is the index of the",
"elements[i] = cls(elements[i], *args, **kwargs) @staticmethod def generate_multiple(elements): \"\"\" Loops over a list",
"tag of xml element coresponding to this class (probability) \"\"\" return \"probability\" def",
"2.0 are satisfied: GNU General Public License, version 2 # or later which",
"a list of elements generated by the element \"\"\" raise NotImplementedError @classmethod def",
"python script. See the documentation below for more details. \"\"\" from lxml import",
"busStop=\"1\"> <probability> <probabilityItem probability=\"0.5\"> <ride busStop=\"2\" modes=\"public\" /> </probabilityItem> <probabilityItem probability=\"0.5\"> <ride busStop=\"3\"",
"It should return the xml tag for elements described by the current class",
".. code-block:: xml <personRoute id=\"route\"> <walk /> <stop /> <ride /> </personRoute> The",
"self.attributes) element.set(\"depart\", str(int(begin))) element.set(\"id\", self.id + \"_\" + str(p_id)) if self.route is not",
"element :param routes: An iterable where to look for routes :type routes: collections.Iterable",
"result = list() for element in elements: if isinstance(element, PersonGenerationElement): result.extend(element.generate()) else: result.append(element.__copy__())",
"passing an input `.pflow.xml`` file's path and an output ``.rou.xml`` file's path. ..",
"original file is not modified and the result is written in another file.",
"\"end\" period_attribute_key = \"period\" number_attribute_key = \"number\" per_wave_attribute_key = \"perWave\" route_attribute_key = \"route\"",
"Note that the nested <probability> element should be a direct child of <probabilityItem>",
"used to generate flows of persons as it is already possible for vehicles.",
"(personRoute) \"\"\" return \"personRoute\" @staticmethod def get_route_by_id(routes, route_id): \"\"\" :param routes: :type routes:",
"Replaces xml elements with the appropriate tag (the one defined in get_xml_tag) with",
"self.begin) * 2 + 1 else: self.period = (self.end - self.begin) / (self.number",
"available under the # terms of the Eclipse Public License 2.0 which is",
"<probabilityItem> \"\"\" def __init__(self, xml_element): \"\"\" :param xml_element: The source xml element \"\"\"",
"under the ``<personFlow>`` How to Use ---------- Via Command Line ~~~~~~~~~~~~~~~~ This script",
"elements with the appropriate tag (the one defined in get_xml_tag) with an object",
"possible in SUMO route files. It does so by converting an xml file",
"# Copyright (C) 2019-2020 German Aerospace Center (DLR) and others. # This program",
"flow are spawned in 7 waves (equally separated in time) and each wave",
"from stop 3 to stop 1 and then stopping there for 50 ticks.",
"defined directly under the ``<personFlow>`` How to Use ---------- Via Command Line ~~~~~~~~~~~~~~~~",
"<ride busStop=\"1\" modes=\"public\"/> <stop busStop=\"1\" duration=\"50\"/> </personFlow> </routes> The example above allows to",
"/> <ride /> </personRoute> The content of the route is then copied to",
"\"\"\" :return: The persons of the flow \"\"\" begin = self.begin p_id =",
": The time (in seconds) between two consecutive waves. Not mandatory, if not",
"\"\"\" :return: One of the alternatives according to the given probabilities \"\"\" result",
"routes: collections.Iterable :param route_id: :type route_id: str :return: The PersonRouteElement object having the",
"route_attribute_key = \"route\" def __init__(self, xml_element, routes): \"\"\" :param xml_element: The xml element",
"elements.append(element) p_id += 1 begin += self.period return elements def generate_persons(input_file, output_file): \"\"\"",
"try: self.period = int(self.attributes.pop(self.period_attribute_key)) except KeyError: try: self.number = int(self.attributes.pop(self.number_attribute_key)) if self.number ==",
"current class (personFlow) \"\"\" return \"personFlow\" def generate(self): \"\"\" :return: The persons of",
"ends. Not mandatory, default is 3600. - period : The time (in seconds)",
"https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html # SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later # @file personGenerator.py # @author <NAME> #",
"super().__init__(xml_element) self.possibilities = [] for sub_element in list(self.xml_element): if sub_element.tag != \"probabilityItem\": raise",
"else: result.append(element.__copy__()) return result class ProbabilityElement(PersonGenerationElement): \"\"\" This class describes probability elements that",
"summing up to 1 at line : \" + str(self.xml_element.sourceline)) @classmethod def get_xml_tag(cls):",
"the element \"\"\" raise NotImplementedError @classmethod def wrap_elements(cls, elements, *args, **kwargs): \"\"\" Replaces",
"lxml import etree import argparse import random class PersonGenerationElement(object): \"\"\" This class serves",
"consecutive waves. Not mandatory, if not given, number will be used - number",
"id=\"backward\" begin=\"0\" end=\"3600\" period=\"600\" perWave=\"10\" departPos=\"0\"> <walk from=\"e3\" busStop=\"3\" /> <ride busStop=\"1\" modes=\"public\"/>",
"pedestrians.pflow.xml pedestrians.rou.xml Note that the output file is overwritten without asking for permission.",
"output_file): \"\"\" Core method of the script, parses <personFlow> tags in an XML",
"+= self.period return elements def generate_persons(input_file, output_file): \"\"\" Core method of the script,",
"sumo route file containing the generated <peron> elements. Here is an example ``.pflow.xml``",
"SUMO simulation which is currently not possible in SUMO route files. It does",
"path. .. code-block:: bash python personGenerator.py pedestrians.pflow.xml pedestrians.rou.xml Note that the output file",
"exit(-1) try: self.end = int(self.attributes.pop(self.end_attribute_key)) except KeyError: self.end = self.default_end try: self.period =",
"python # Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo # Copyright (C)",
"period is not specified - perWave : the number of persons in each",
"this class (personRoute) \"\"\" return \"personRoute\" @staticmethod def get_route_by_id(routes, route_id): \"\"\" :param routes:",
"set forth in the Eclipse # Public License 2.0 are satisfied: GNU General",
"the result is written in another file. The resulting file will not contain",
"ValueError(\"Probabilities not summing up to 1 at line : \" + str(self.xml_element.sourceline)) @classmethod",
"(KeyError, ValueError): raise ValueError(\"probabilityItem element requires attribute probability between 0 and 1\") if",
"the time at which the flow ends. Not mandatory, default is 3600. -",
"[] cumulated_probability = 0 p = random.random() for possibility in self.possibilities: cumulated_probability +=",
"which is currently not possible in SUMO route files. It does so by",
"xml_element: The source xml element \"\"\" super().__init__(xml_element) self.possibilities = [] for sub_element in",
"cumulated_probability = 0 p = random.random() for possibility in self.possibilities: cumulated_probability += float(possibility[0])",
"personRoute element probability elements are taken into account & used to generate an",
"/> <ride /> <stop /> </personFlow> will generate person elements having the same",
"generate alternatives with given probabilities. In XML it looks like: .. code-block:: xml",
"your own python script. See the documentation below for more details. \"\"\" from",
"generate_multiple(elements): \"\"\" Loops over a list containing xml elements and PersonGenerationElement objects. The",
"---------- Via Command Line ~~~~~~~~~~~~~~~~ This script can be accessed directly by command",
"\"\"\" # Parse the input file tree = etree.parse(input_file) routes = tree.getroot() children",
"and 3600 The complete attributes list is: - id - begin : the",
"</personRoute> The content of the route is then copied to each person using",
".. code-block:: xml <personRoute id=\"route\"> <walk from=\"edge1\" busStop=\"1\"> <probability> <probabilityItem probability=\"0.5\"> <ride busStop=\"2\"",
"class \"\"\" raise NotImplementedError def generate(self): \"\"\" This method is meant to be",
"MObility; see https://eclipse.org/sumo # Copyright (C) 2019-2020 German Aerospace Center (DLR) and others.",
"person routes separately. .. code-block:: xml <personRoute id=\"route\"> <walk /> <stop /> <ride",
"Center (DLR) and others. # This program and the accompanying materials are made",
"two consecutive waves. Not mandatory, if not given, number will be used -",
"</probability> </personRoute> <personFlow id=\"forward\" begin=\"0\" end=\"3600\" number=\"7\" perWave=\"10\" departPos=\"0\" route=\"forward\" /> <personFlow id=\"backward\"",
"# Parse the input file tree = etree.parse(input_file) routes = tree.getroot() children =",
"The content of the route is then copied to each person using it.",
"source xml element \"\"\" super().__init__(xml_element) self.possibilities = [] for sub_element in list(self.xml_element): if",
"children of the <personFlow> element The id of generated persons will be `<id>_<person_index>`",
"default is 3600. - period : The time (in seconds) between two consecutive",
"having the given id from the given iterable. None if not found \"\"\"",
"given, number will be used - number : the number of waves. Only",
"``.rou.xml`` file's path. .. code-block:: bash python personGenerator.py pedestrians.pflow.xml pedestrians.rou.xml Note that the",
"mandatory, default is 3600. - period : The time (in seconds) between two",
"are satisfied: GNU General Public License, version 2 # or later which is",
"person generation elements \"\"\" def __init__(self, xml_element): self.xml_element = xml_element if self.xml_element.tag !=",
"file is overwritten if it is already exist :param input_file: The path of",
"not given, uses the children of the <personFlow> element The id of generated",
"line passing an input `.pflow.xml`` file's path and an output ``.rou.xml`` file's path.",
"xml_element, routes): \"\"\" :param xml_element: The xml element :param routes: An iterable where",
"The persons of this flow are spawned in 7 waves (equally separated in",
"For the persons going to bus stop 2, there's a 50% chance they'll",
"KeyError: print(\"No begin in personFlow \" + str(id) + \", quitting\") exit(-1) try:",
"(self.end - self.begin) / (self.number - 1) except KeyError: print(\"Neither period nor number",
"of the input file :param output_file: The path of the output file \"\"\"",
"alternatives according to the probabilities. Probability elements can be nested, so you can",
"begin : the time at which the flow starts - end : the",
"number : the number of waves. Only meaningful when period is not specified",
"stay there during 10 ticks. The route followed by the persons of this",
"file tree = etree.parse(input_file) routes = tree.getroot() children = list(routes) for child in",
"self.children = list(self.xml_element) ProbabilityElement.wrap_elements(self.children) @classmethod def get_xml_tag(cls): \"\"\" :return: The tag of the",
"begin_attribute_key = \"begin\" end_attribute_key = \"end\" period_attribute_key = \"period\" number_attribute_key = \"number\" per_wave_attribute_key",
"result is written in another file. The resulting file will not contain the",
"routes separately. .. code-block:: xml <personRoute id=\"route\"> <walk /> <stop /> <ride />",
"and the result is written in another file. The resulting file will not",
"/> <stop /> </personFlow> will generate person elements having the same children (walk,",
"2019-2020 German Aerospace Center (DLR) and others. # This program and the accompanying",
"id of generated persons will be `<id>_<person_index>` where `<person_index>` is the index of",
"follow Not mandatory, if not given, uses the children of the <personFlow> element",
"not specified - perWave : the number of persons in each wave. Not",
"the flow starts - end : the time at which the flow ends.",
"<stop /> <ride /> </personRoute> The content of the route is then copied",
"import the classes and methods in this module and use them in your",
"already exist :param input_file: The path of the input file :param output_file: The",
"get_route_by_id(routes, route_id): \"\"\" :param routes: :type routes: collections.Iterable :param route_id: :type route_id: str",
"quitting\") exit(-1) try: self.end = int(self.attributes.pop(self.end_attribute_key)) except KeyError: self.end = self.default_end try: self.period",
"self.xml_element = xml_element if self.xml_element.tag != self.get_xml_tag(): raise Exception(\"Bad tag\") @classmethod def get_xml_tag(cls):",
":return: The persons of the flow \"\"\" begin = self.begin p_id = 0",
"https://eclipse.org/sumo # Copyright (C) 2019-2020 German Aerospace Center (DLR) and others. # This",
"the accompanying materials are made available under the # terms of the Eclipse",
"The complete attributes list is: - id - begin : the time at",
"by the current class \"\"\" raise NotImplementedError def generate(self): \"\"\" This method is",
"the **personRoute** element to have different alternatives. Basically, you can have: .. code-block::",
"collections.Iterable \"\"\" super().__init__(xml_element) self.routes = routes self.attributes = {item[0]: item[1] for item in",
"per_wave_attribute_key = \"perWave\" route_attribute_key = \"route\" def __init__(self, xml_element, routes): \"\"\" :param xml_element:",
"this flow is defined separately in a ``<personRoute>`` element and referenced by its",
"self.id + \"_\" + str(p_id)) if self.route is not None: element.extend(self.route.generate()) else: element.extend(self.generate_multiple(self.children))",
"You can import the classes and methods in this module and use them",
"of waves. Only meaningful when period is not specified - perWave : the",
"one defined in get_xml_tag) with an object of the current class. The given",
"self.id = None self.begin = None self.period = None self.route = None #",
"self.children = list(self.xml_element) ProbabilityElement.wrap_elements(self.children) self.id = None self.begin = None self.period = None",
"objects. :type elements: list :return: a list of resulting xml elements :rtype list",
"inside the **personRoute** element to have different alternatives. Basically, you can have: ..",
"Only meaningful when period is not specified - perWave : the number of",
"f.close() if __name__ == \"__main__\": # Parses the command line arguments parser =",
"followed by the persons is defined directly under the ``<personFlow>`` How to Use",
"careful :param elements: a list of xml elements :type elements: list \"\"\" for",
"\"\"\" return \"personRoute\" @staticmethod def get_route_by_id(routes, route_id): \"\"\" :param routes: :type routes: collections.Iterable",
"you to define conditional probabilities. Note that the nested <probability> element should be",
"may also be made available under the following Secondary # Licenses when the",
"print(\"No begin in personFlow \" + str(id) + \", quitting\") exit(-1) try: self.end",
"method of the script, parses <personFlow> tags in an XML file and generates",
"elements[i].tag == cls.get_xml_tag(): elements[i] = cls(elements[i], *args, **kwargs) @staticmethod def generate_multiple(elements): \"\"\" Loops",
":param input_file: The path of the input file :param output_file: The path of",
"<personRoute id=\"route-1\"> <walk from=\"e1\" busStop=\"1\" /> <probability> <probabilityItem probability=\"0.5\"> <ride busStop=\"2\" modes=\"public\" />",
"proba < 0 or proba > 1: raise ValueError(\"\") possibility = (proba, list(sub_element))",
"- end : the time at which the flow ends. Not mandatory, default",
"None: element.extend(self.route.generate()) else: element.extend(self.generate_multiple(self.children)) elements.append(element) p_id += 1 begin += self.period return elements",
"if isinstance(child, PersonRouteElement)] PersonFlowElement.wrap_elements(children, routes=person_routes) for person_route in person_routes: children.remove(person_route) person_elements = PersonGenerationElement.generate_multiple(children)",
"self.number == 1: self.period = (self.end - self.begin) * 2 + 1 else:",
"children = list(routes) for child in children: routes.remove(child) PersonRouteElement.wrap_elements(children) person_routes = [child for",
"int(self.attributes.pop(self.per_wave_attribute_key)) except KeyError: self.per_wave = 1 try: route_id = self.attributes.pop(self.route_attribute_key) self.route = PersonRouteElement.get_route_by_id(routes,",
"sum([child[0] for child in self.possibilities]) != 1: raise ValueError(\"Probabilities not summing up to",
"class ProbabilityElement(PersonGenerationElement): \"\"\" This class describes probability elements that are used to generate",
"Exception(\"Bad tag\") @classmethod def get_xml_tag(cls): \"\"\" This class method is meant to be",
"pass @classmethod def get_xml_tag(cls): \"\"\" :return: The tag of the xml elements corresponding",
"persons. These waves will be equally separated in time between 0 and 3600",
"an object of the current class. The given list is modified, be careful",
"Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo # Copyright (C) 2019-2020 German",
"10 persons pere wave. The route followed by the persons is defined directly",
"Exception(\"Route with id \" + route_id + \" not found at line \"",
"get_xml_tag(cls): \"\"\" This class method is meant to be implemented by subclasses It",
"isinstance(elements[i], PersonGenerationElement) and elements[i].tag == cls.get_xml_tag(): elements[i] = cls(elements[i], *args, **kwargs) @staticmethod def",
"the classes and methods in this module and use them in your own",
"if self.number == 1: self.period = (self.end - self.begin) * 2 + 1",
"self.per_wave = 1 try: route_id = self.attributes.pop(self.route_attribute_key) self.route = PersonRouteElement.get_route_by_id(routes, route_id) if self.route",
"child in children if isinstance(child, PersonRouteElement)] PersonFlowElement.wrap_elements(children, routes=person_routes) for person_route in person_routes: children.remove(person_route)",
"This class describes xml elements that are used to define person routes separately.",
"in the flow (starting from 0) \"\"\" default_end = 3600 id_attribute_key = \"id\"",
"list :return: a list of resulting xml elements :rtype list \"\"\" result =",
"{item[0]: item[1] for item in self.xml_element.items()} self.children = list(self.xml_element) ProbabilityElement.wrap_elements(self.children) self.id = None",
"the id of the route that the persons will follow Not mandatory, if",
"generated persons will be in 7 waves each containing 10 persons. These waves",
"xml elements and PersonGenerationElement objects. :type elements: list :return: a list of resulting",
"except KeyError: print(\"No id attribute in personFlow, quitting\") exit(-1) try: self.begin = int(self.attributes.pop(self.begin_attribute_key))",
"= etree.Element(\"person\", self.attributes) element.set(\"depart\", str(int(begin))) element.set(\"id\", self.id + \"_\" + str(p_id)) if self.route",
"first flow consists of persons taking a bus from stop 1 to either",
"7 waves each containing 10 persons. These waves will be equally separated in",
"Public License 2.0 are satisfied: GNU General Public License, version 2 # or",
"alternative </probabilityItem> </probability> This allows you to define conditional probabilities. Note that the",
"sub elements of the original personRoute element probability elements are taken into account",
"def generate(self): \"\"\" :return: One of the alternatives according to the given probabilities",
"int(self.attributes.pop(self.period_attribute_key)) except KeyError: try: self.number = int(self.attributes.pop(self.number_attribute_key)) if self.number == 1: self.period =",
"your script ~~~~~~~~~~~~~~ You can import the classes and methods in this module",
"spawned in 7 waves (equally separated in time) and each wave consists of",
"(proba, list(sub_element)) ProbabilityElement.wrap_elements(possibility[1]) self.possibilities.append(possibility) except (KeyError, ValueError): raise ValueError(\"probabilityItem element requires attribute probability",
"pedestrians.rou.xml Note that the output file is overwritten without asking for permission. In",
"(starting from 0) \"\"\" default_end = 3600 id_attribute_key = \"id\" begin_attribute_key = \"begin\"",
"<probabilityItem probability=\"0.5\"> <ride busStop=\"2\" modes=\"public\" /> <probability> <probabilityItem probability=\"0.5\"> <stop busStop=\"2\" duration=\"10\" />",
"XML it looks like: .. code-block:: xml <probability> <probabilityItem probability=\"0.5\">fist alternative</probabilityItem> <probabilityItem probability=\"0.5\">second",
"NotImplementedError @classmethod def wrap_elements(cls, elements, *args, **kwargs): \"\"\" Replaces xml elements with the",
"and others. # This program and the accompanying materials are made available under",
"\"\"\" This tool allows to generate flows of persons for a SUMO simulation",
"xml <personFlow id=\"flow\" begin=\"0\" end=\"3600\" number=\"7\" perWave=\"10\"> <walk /> <ride /> <stop />",
"code: .. code-block:: xml <personFlow id=\"flow\" begin=\"0\" end=\"3600\" number=\"7\" perWave=\"10\"> <walk /> <ride",
"time at which the flow starts - end : the time at which",
"list(self.xml_element) ProbabilityElement.wrap_elements(self.children) self.id = None self.begin = None self.period = None self.route =",
"for more details. \"\"\" from lxml import etree import argparse import random class",
"KeyError: print(\"Neither period nor number given for personFlow \" + str(id) + \",",
"attributes list is: - id - begin : the time at which the",
"Copyright (C) 2019-2020 German Aerospace Center (DLR) and others. # This program and",
"under the following Secondary # Licenses when the conditions for such availability set",
"content of the route is then copied to each person using it. You",
"route file containing the generated <peron> elements. Here is an example ``.pflow.xml`` :",
"code-block:: bash python personGenerator.py pedestrians.pflow.xml pedestrians.rou.xml Note that the output file is overwritten",
"see https://eclipse.org/sumo # Copyright (C) 2019-2020 German Aerospace Center (DLR) and others. #",
"each wave consists of 10 persons. For the persons going to bus stop",
"permission. In your script ~~~~~~~~~~~~~~ You can import the classes and methods in",
"of persons : - The first flow consists of persons taking a bus",
"with 10 persons pere wave. The route followed by the persons is defined",
"ProbabilityElement(PersonGenerationElement): \"\"\" This class describes probability elements that are used to generate alternatives",
"route_id: str :return: The PersonRouteElement object having the given id from the given",
"will follow Not mandatory, if not given, uses the children of the <personFlow>",
"different alternatives. Basically, you can have: .. code-block:: xml <personRoute id=\"route\"> <walk from=\"edge1\"",
"This class describes probability elements that are used to generate alternatives with given",
"and route.id == route_id: return route return None def generate(self): \"\"\" :return: A",
"allows you to define conditional probabilities. Note that the nested <probability> element should",
"50 ticks. The persons of this flow are spawned in periodic waves with",
"# Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo # Copyright (C) 2019-2020",
"\" + str(id) + \", quitting\") exit(-1) try: self.per_wave = int(self.attributes.pop(self.per_wave_attribute_key)) except KeyError:",
"7 waves (equally separated in time) and each wave consists of 10 persons.",
"parses <personFlow> tags in an XML file and generates <person> elements. The generated",
"= (self.end - self.begin) * 2 + 1 else: self.period = (self.end -",
"path of the input file :param output_file: The path of the output file",
"probability elements are taken into account & used to generate an alternative \"\"\"",
"\"\"\" This class method is meant to be implemented by subclasses It should",
":return: a list of resulting xml elements :rtype list \"\"\" result = list()",
":type elements: list :return: a list of resulting xml elements :rtype list \"\"\"",
"persons as it is already possible for vehicles. For example, this xml code:",
"if self.xml_element.tag != self.get_xml_tag(): raise Exception(\"Bad tag\") @classmethod def get_xml_tag(cls): \"\"\" This class",
"of xml elements :type elements: list \"\"\" for i in range(len(elements)): if not",
"this flow are spawned in periodic waves with 10 persons pere wave. The",
"and referenced by its ID. - The second flow consists of persons taking",
"xml element :param routes: An iterable where to look for routes :type routes:",
"try: self.id = self.attributes.pop(self.id_attribute_key) except KeyError: print(\"No id attribute in personFlow, quitting\") exit(-1)",
"A list containing xml elements and PersonGenerationElement objects. :type elements: list :return: a",
"file is not modified and the result is written in another file. The",
"route is then copied to each person using it. You can use probabilities",
"/> <personFlow id=\"backward\" begin=\"0\" end=\"3600\" period=\"600\" perWave=\"10\" departPos=\"0\"> <walk from=\"e3\" busStop=\"3\" /> <ride",
"wrap_elements(cls, elements, *args, **kwargs): \"\"\" Replaces xml elements with the appropriate tag (the",
"flow is defined separately in a ``<personRoute>`` element and referenced by its ID.",
"from=\"edge1\" busStop=\"1\"> <probability> <probabilityItem probability=\"0.5\"> <ride busStop=\"2\" modes=\"public\" /> </probabilityItem> <probabilityItem probability=\"0.5\"> <ride",
"element \"\"\" raise NotImplementedError @classmethod def wrap_elements(cls, elements, *args, **kwargs): \"\"\" Replaces xml",
"should return the xml tag for elements described by the current class \"\"\"",
"The tag of the xml elements corresponding to this class (personRoute) \"\"\" return",
"elements generated by the element \"\"\" raise NotImplementedError @classmethod def wrap_elements(cls, elements, *args,",
"Aerospace Center (DLR) and others. # This program and the accompanying materials are",
"object having the given id from the given iterable. None if not found",
"to generate an alternative \"\"\" return self.generate_multiple(self.children) class PersonFlowElement(PersonGenerationElement): \"\"\" This class describes",
"script can be accessed directly by command line passing an input `.pflow.xml`` file's",
"\"w\") as f: f.write(etree.tostring(routes).decode()) f.close() if __name__ == \"__main__\": # Parses the command",
"self.period = None self.route = None # We check for the attributes that",
"describes xml elements that are used to generate flows of persons as it",
"possibility in self.possibilities: cumulated_probability += float(possibility[0]) if p <= cumulated_probability: result.extend(self.generate_multiple(possibility[1])) break return",
"not found at line \" + str(self.xml_element.sourceline)) except KeyError: pass @classmethod def get_xml_tag(cls):",
"<stop /> </personFlow> will generate person elements having the same children (walk, ride,",
"~~~~~~~~~~~~~~ You can import the classes and methods in this module and use",
"for i in range(len(elements)): if not isinstance(elements[i], PersonGenerationElement) and elements[i].tag == cls.get_xml_tag(): elements[i]",
"in elements: if isinstance(element, PersonGenerationElement): result.extend(element.generate()) else: result.append(element.__copy__()) return result class ProbabilityElement(PersonGenerationElement): \"\"\"",
"id - begin : the time at which the flow starts - end",
"def __init__(self, xml_element): super().__init__(xml_element) self.id = self.xml_element.get(\"id\") self.children = list(self.xml_element) ProbabilityElement.wrap_elements(self.children) @classmethod def",
"result.append(element.__copy__()) return result class ProbabilityElement(PersonGenerationElement): \"\"\" This class describes probability elements that are",
"element to have different alternatives. Basically, you can have: .. code-block:: xml <personRoute",
"elements are allowed inside probability\") try: proba = float(sub_element.get(\"probability\")) if proba < 0",
"*args, **kwargs): \"\"\" Replaces xml elements with the appropriate tag (the one defined",
"departPos=\"0\" route=\"forward\" /> <personFlow id=\"backward\" begin=\"0\" end=\"3600\" period=\"600\" perWave=\"10\" departPos=\"0\"> <walk from=\"e3\" busStop=\"3\"",
"modes=\"public\" /> </probabilityItem> </probability> </personRoute> \"\"\" def __init__(self, xml_element): super().__init__(xml_element) self.id = self.xml_element.get(\"id\")",
"the time at which the flow starts - end : the time at",
"self.route is None: raise Exception(\"Route with id \" + route_id + \" not",
"(self.end - self.begin) * 2 + 1 else: self.period = (self.end - self.begin)",
"conditions for such availability set forth in the Eclipse # Public License 2.0",
"</routes> The example above allows to generate two flows of persons : -",
"\"\"\" Replaces xml elements with the appropriate tag (the one defined in get_xml_tag)",
"child of <probabilityItem> \"\"\" def __init__(self, xml_element): \"\"\" :param xml_element: The source xml",
"uses the children of the <personFlow> element The id of generated persons will",
"not found \"\"\" for route in routes: if isinstance(route, PersonRouteElement) and route.id ==",
"are allowed inside probability\") try: proba = float(sub_element.get(\"probability\")) if proba < 0 or",
"xml elements and PersonGenerationElement objects. The PersonGenerationElement objects are replaced by elements generated",
"probabilities. Probability elements can be nested, so you can have: .. code-block:: xml",
"for the attributes that concern us & we leave the others try: self.id",
"path of the output file \"\"\" # Parse the input file tree =",
"\"\"\" :return: The tag of the xml elements corresponding to this class (personRoute)",
"id of the route that the persons will follow Not mandatory, if not",
"found at line \" + str(self.xml_element.sourceline)) except KeyError: pass @classmethod def get_xml_tag(cls): \"\"\"",
"= self.default_end try: self.period = int(self.attributes.pop(self.period_attribute_key)) except KeyError: try: self.number = int(self.attributes.pop(self.number_attribute_key)) if",
"The PersonRouteElement object having the given id from the given iterable. None if",
"is not None: element.extend(self.route.generate()) else: element.extend(self.generate_multiple(self.children)) elements.append(element) p_id += 1 begin += self.period",
"= 0 p = random.random() for possibility in self.possibilities: cumulated_probability += float(possibility[0]) if",
"returns the children of one of its alternatives according to the probabilities. Probability",
"str(id) + \", quitting\") exit(-1) try: self.end = int(self.attributes.pop(self.end_attribute_key)) except KeyError: self.end =",
"and each wave consists of 10 persons. For the persons going to bus",
"A copy of the sub elements of the original personRoute element probability elements",
"list(sub_element)) ProbabilityElement.wrap_elements(possibility[1]) self.possibilities.append(possibility) except (KeyError, ValueError): raise ValueError(\"probabilityItem element requires attribute probability between",
"leave the others try: self.id = self.attributes.pop(self.id_attribute_key) except KeyError: print(\"No id attribute in",
"be `<id>_<person_index>` where `<person_index>` is the index of the person in the flow",
"# Public License 2.0 are satisfied: GNU General Public License, version 2 #",
"children.remove(person_route) person_elements = PersonGenerationElement.generate_multiple(children) person_elements.sort(key=lambda e: int(e.get('depart'))) routes.extend(person_elements) with open(output_file, \"w\") as f:",
"periodic waves with 10 persons pere wave. The route followed by the persons",
"\"\"\" :return: The tag of xml element coresponding to this class (probability) \"\"\"",
"<personFlow> elements. Note that the output file is overwritten if it is already",
"probabilities. Note that the nested <probability> element should be a direct child of",
"</probabilityItem> <probabilityItem probability=\"0.5\"> <ride busStop=\"3\" modes=\"public\" /> </probabilityItem> </probability> </personRoute> \"\"\" def __init__(self,",
"def __init__(self, xml_element): self.xml_element = xml_element if self.xml_element.tag != self.get_xml_tag(): raise Exception(\"Bad tag\")",
"3 to stop 1 and then stopping there for 50 ticks. The persons",
":type route_id: str :return: The PersonRouteElement object having the given id from the",
"the flow (starting from 0) \"\"\" default_end = 3600 id_attribute_key = \"id\" begin_attribute_key",
"</probability> This allows you to define conditional probabilities. Note that the nested <probability>",
"are sorted by their depart time. The original file is not modified and",
"described by the current class \"\"\" raise NotImplementedError def generate(self): \"\"\" This method",
"# This Source Code may also be made available under the following Secondary",
"to this class (probability) \"\"\" return \"probability\" def generate(self): \"\"\" :return: One of",
"the alternatives according to the given probabilities \"\"\" result = [] cumulated_probability =",
"The path of the output file \"\"\" # Parse the input file tree",
"stop 1 to either stop 2 or stop 3 (with a 50% chance",
"<probability> <probabilityItem probability=\"0.5\"> <ride busStop=\"2\" modes=\"public\" /> <probability> <probabilityItem probability=\"0.5\"> <stop busStop=\"2\" duration=\"10\"",
"= int(self.attributes.pop(self.per_wave_attribute_key)) except KeyError: self.per_wave = 1 try: route_id = self.attributes.pop(self.route_attribute_key) self.route =",
"number will be used - number : the number of waves. Only meaningful",
"at which the flow ends. Not mandatory, default is 3600. - period :",
"given id from the given iterable. None if not found \"\"\" for route",
"of persons taking a bus from stop 1 to either stop 2 or",
"the documentation below for more details. \"\"\" from lxml import etree import argparse",
"# https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html # SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later # @file personGenerator.py # @author <NAME>",
"given probabilities \"\"\" result = [] cumulated_probability = 0 p = random.random() for",
"by the persons is defined directly under the ``<personFlow>`` How to Use ----------",
"of xml element coresponding to this class (probability) \"\"\" return \"probability\" def generate(self):",
"<ride busStop=\"3\" modes=\"public\"> </probabilityItem> </probability> </personRoute> <personFlow id=\"forward\" begin=\"0\" end=\"3600\" number=\"7\" perWave=\"10\" departPos=\"0\"",
"\"id\" begin_attribute_key = \"begin\" end_attribute_key = \"end\" period_attribute_key = \"period\" number_attribute_key = \"number\"",
"possibility = (proba, list(sub_element)) ProbabilityElement.wrap_elements(possibility[1]) self.possibilities.append(possibility) except (KeyError, ValueError): raise ValueError(\"probabilityItem element requires",
"in 7 waves each containing 10 persons. These waves will be equally separated",
"+ route_id + \" not found at line \" + str(self.xml_element.sourceline)) except KeyError:",
"with given probabilities. In XML it looks like: .. code-block:: xml <probability> <probabilityItem",
"<= cumulated_probability: result.extend(self.generate_multiple(possibility[1])) break return result class PersonRouteElement(PersonGenerationElement): \"\"\" This class describes xml",
"<probability> <probabilityItem probability=\"0.5\">fist alternative</probabilityItem> <probabilityItem probability=\"0.5\">second alternative</probabilityItem> </probability> Each time the element is",
"duration=\"10\" /> </probabilityItem> <probabilityItem probability=\"0.5\" /> </probability> </probabilityItem> <probabilityItem probability=\"0.5\"> <ride busStop=\"3\" modes=\"public\">",
"elements :rtype list \"\"\" result = list() for element in elements: if isinstance(element,",
"is already exist :param input_file: The path of the input file :param output_file:",
"\"\"\" This class describes xml elements that are used to generate flows of",
"then copied to each person using it. You can use probabilities inside the",
"route : the id of the route that the persons will follow Not",
"if self.route is not None: element.extend(self.route.generate()) else: element.extend(self.generate_multiple(self.children)) elements.append(element) p_id += 1 begin",
"by subclasses It should return the xml tag for elements described by the",
"__init__(self, xml_element): \"\"\" :param xml_element: The source xml element \"\"\" super().__init__(xml_element) self.possibilities =",
"str(self.xml_element.sourceline)) except KeyError: pass @classmethod def get_xml_tag(cls): \"\"\" :return: The tag of the",
"2, there's a 50% chance they'll stay there during 10 ticks. The route",
":param routes: :type routes: collections.Iterable :param route_id: :type route_id: str :return: The PersonRouteElement",
"/> <probability> <probabilityItem probability=\"0.5\"> <stop busStop=\"2\" duration=\"10\" /> </probabilityItem> <probabilityItem probability=\"0.5\" /> </probability>",
"xml_element): self.xml_element = xml_element if self.xml_element.tag != self.get_xml_tag(): raise Exception(\"Bad tag\") @classmethod def",
"self.xml_element.tag != self.get_xml_tag(): raise Exception(\"Bad tag\") @classmethod def get_xml_tag(cls): \"\"\" This class method",
"others try: self.id = self.attributes.pop(self.id_attribute_key) except KeyError: print(\"No id attribute in personFlow, quitting\")",
"p <= cumulated_probability: result.extend(self.generate_multiple(possibility[1])) break return result class PersonRouteElement(PersonGenerationElement): \"\"\" This class describes",
"person_route in person_routes: children.remove(person_route) person_elements = PersonGenerationElement.generate_multiple(children) person_elements.sort(key=lambda e: int(e.get('depart'))) routes.extend(person_elements) with open(output_file,",
"stop 3 to stop 1 and then stopping there for 50 ticks. The",
"+ \" not found at line \" + str(self.xml_element.sourceline)) except KeyError: pass @classmethod",
"1 begin += self.period return elements def generate_persons(input_file, output_file): \"\"\" Core method of",
"Note that the output file is overwritten without asking for permission. In your",
"def generate(self): \"\"\" :return: A copy of the sub elements of the original",
"# @file personGenerator.py # @author <NAME> # @date 2019-03-22 \"\"\" This tool allows",
"are made available under the # terms of the Eclipse Public License 2.0",
"by their depart time. The original file is not modified and the result",
"above allows to generate two flows of persons : - The first flow",
"is meant to be implemented by subclasses It should return the xml tag",
"get_xml_tag(cls): \"\"\" :return: The tag of the xml elements corresponding to the current",
"This program and the accompanying materials are made available under the # terms",
"generate flows of persons for a SUMO simulation which is currently not possible",
"can be nested, so you can have: .. code-block:: xml <probability> <probabilityItem probability=\"0.5\">",
"its alternatives according to the probabilities. Probability elements can be nested, so you",
"int(self.attributes.pop(self.begin_attribute_key)) except KeyError: print(\"No begin in personFlow \" + str(id) + \", quitting\")",
"elements can be nested, so you can have: .. code-block:: xml <probability> <probabilityItem",
"(in seconds) between two consecutive waves. Not mandatory, if not given, number will",
"children (walk, ride, stop). The generated persons will be in 7 waves each",
"0 and 3600 The complete attributes list is: - id - begin :",
"PersonGenerationElement) and elements[i].tag == cls.get_xml_tag(): elements[i] = cls(elements[i], *args, **kwargs) @staticmethod def generate_multiple(elements):",
"module and use them in your own python script. See the documentation below",
"or proba > 1: raise ValueError(\"\") possibility = (proba, list(sub_element)) ProbabilityElement.wrap_elements(possibility[1]) self.possibilities.append(possibility) except",
"found \"\"\" for route in routes: if isinstance(route, PersonRouteElement) and route.id == route_id:",
"# Parses the command line arguments parser = argparse.ArgumentParser() parser.add_argument(\"source\") parser.add_argument(\"destination\") source, destination",
"a list of resulting xml elements :rtype list \"\"\" result = list() for",
"\"personFlow\" def generate(self): \"\"\" :return: The persons of the flow \"\"\" begin =",
"directly by command line passing an input `.pflow.xml`` file's path and an output",
"# terms of the Eclipse Public License 2.0 which is available at #",
"id=\"forward\" begin=\"0\" end=\"3600\" number=\"7\" perWave=\"10\" departPos=\"0\" route=\"forward\" /> <personFlow id=\"backward\" begin=\"0\" end=\"3600\" period=\"600\"",
"def generate_multiple(elements): \"\"\" Loops over a list containing xml elements and PersonGenerationElement objects.",
"elements that are used to generate flows of persons as it is already",
"are spawned in 7 waves (equally separated in time) and each wave consists",
"persons going to bus stop 2, there's a 50% chance they'll stay there",
"persons in each wave. Not mandatory, default is 1 - route : the",
"nested <probability> element should be a direct child of <probabilityItem> \"\"\" def __init__(self,",
"+ \", quitting\") exit(-1) try: self.end = int(self.attributes.pop(self.end_attribute_key)) except KeyError: self.end = self.default_end",
"busStop=\"1\" modes=\"public\"/> <stop busStop=\"1\" duration=\"50\"/> </personFlow> </routes> The example above allows to generate",
"generated <person> elements are sorted by their depart time. The original file is",
"contain the <personFlow> elements. Note that the output file is overwritten if it",
"is not modified and the result is written in another file. The resulting",
"= None self.route = None # We check for the attributes that concern",
"overwritten without asking for permission. In your script ~~~~~~~~~~~~~~ You can import the",
"will be in 7 waves each containing 10 persons. These waves will be",
"class describes xml elements that are used to define person routes separately. ..",
"begin=\"0\" end=\"3600\" period=\"600\" perWave=\"10\" departPos=\"0\"> <walk from=\"e3\" busStop=\"3\" /> <ride busStop=\"1\" modes=\"public\"/> <stop",
"allows to generate two flows of persons : - The first flow consists",
"proba = float(sub_element.get(\"probability\")) if proba < 0 or proba > 1: raise ValueError(\"\")",
"\", quitting\") exit(-1) try: self.end = int(self.attributes.pop(self.end_attribute_key)) except KeyError: self.end = self.default_end try:",
"range(self.per_wave): element = etree.Element(\"person\", self.attributes) element.set(\"depart\", str(int(begin))) element.set(\"id\", self.id + \"_\" + str(p_id))",
"terms of the Eclipse Public License 2.0 which is available at # https://www.eclipse.org/legal/epl-2.0/",
"having the ``.pflow.xml`` extension) to a sumo route file containing the generated <peron>",
"raise Exception(\"Bad tag\") @classmethod def get_xml_tag(cls): \"\"\" This class method is meant to",
"without asking for permission. In your script ~~~~~~~~~~~~~~ You can import the classes",
"</probabilityItem> <probabilityItem probability=\"0.5\"> <ride busStop=\"3\" modes=\"public\"> </probabilityItem> </probability> </personRoute> <personFlow id=\"forward\" begin=\"0\" end=\"3600\"",
"for child in children if isinstance(child, PersonRouteElement)] PersonFlowElement.wrap_elements(children, routes=person_routes) for person_route in person_routes:",
"us & we leave the others try: self.id = self.attributes.pop(self.id_attribute_key) except KeyError: print(\"No",
"- self.begin) * 2 + 1 else: self.period = (self.end - self.begin) /",
"begin=\"0\" end=\"3600\" number=\"7\" perWave=\"10\" departPos=\"0\" route=\"forward\" /> <personFlow id=\"backward\" begin=\"0\" end=\"3600\" period=\"600\" perWave=\"10\"",
"persons of this flow are spawned in periodic waves with 10 persons pere",
"code-block:: xml <personRoute id=\"route\"> <walk from=\"edge1\" busStop=\"1\"> <probability> <probabilityItem probability=\"0.5\"> <ride busStop=\"2\" modes=\"public\"",
"@date 2019-03-22 \"\"\" This tool allows to generate flows of persons for a",
"class PersonRouteElement(PersonGenerationElement): \"\"\" This class describes xml elements that are used to define",
"try: route_id = self.attributes.pop(self.route_attribute_key) self.route = PersonRouteElement.get_route_by_id(routes, route_id) if self.route is None: raise",
"the person in the flow (starting from 0) \"\"\" default_end = 3600 id_attribute_key",
"personGenerator.py # @author <NAME> # @date 2019-03-22 \"\"\" This tool allows to generate",
"Each time the element is asked to generate, it returns the children of",
"containing 10 persons. These waves will be equally separated in time between 0",
"simulation which is currently not possible in SUMO route files. It does so",
"id from the given iterable. None if not found \"\"\" for route in",
"\"probability\" def generate(self): \"\"\" :return: One of the alternatives according to the given",
"None def generate(self): \"\"\" :return: A copy of the sub elements of the",
"= list(routes) for child in children: routes.remove(child) PersonRouteElement.wrap_elements(children) person_routes = [child for child",
"busStop=\"1\" duration=\"50\"/> </personFlow> </routes> The example above allows to generate two flows of",
"list containing xml elements and PersonGenerationElement objects. The PersonGenerationElement objects are replaced by",
"self.period = (self.end - self.begin) * 2 + 1 else: self.period = (self.end",
"<probability> <probabilityItem probability=\"0.5\"> <probability> ... </probability> ...Possibly other stuff </probabilityItem> <probabilityItem probability=\"0.5\"> second",
"tag of the xml elements corresponding to the current class (personFlow) \"\"\" return",
"to bus stop 2, there's a 50% chance they'll stay there during 10",
"= 1 try: route_id = self.attributes.pop(self.route_attribute_key) self.route = PersonRouteElement.get_route_by_id(routes, route_id) if self.route is",
"import argparse import random class PersonGenerationElement(object): \"\"\" This class serves as a base",
"class serves as a base for person generation elements \"\"\" def __init__(self, xml_element):",
"alternatives. Basically, you can have: .. code-block:: xml <personRoute id=\"route\"> <walk from=\"edge1\" busStop=\"1\">",
"routes :type routes: collections.Iterable \"\"\" super().__init__(xml_element) self.routes = routes self.attributes = {item[0]: item[1]",
"routes: collections.Iterable \"\"\" super().__init__(xml_element) self.routes = routes self.attributes = {item[0]: item[1] for item",
"# or later which is available at # https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html # SPDX-License-Identifier: EPL-2.0 OR",
"- 1) except KeyError: print(\"Neither period nor number given for personFlow \" +",
":param output_file: The path of the output file \"\"\" # Parse the input",
"of the <personFlow> element The id of generated persons will be `<id>_<person_index>` where",
"\"\"\" return self.generate_multiple(self.children) class PersonFlowElement(PersonGenerationElement): \"\"\" This class describes xml elements that are",
"the number of persons in each wave. Not mandatory, default is 1 -",
"them The given list is not modified :param elements: A list containing xml",
"# This program and the accompanying materials are made available under the #",
"# https://www.eclipse.org/legal/epl-2.0/ # This Source Code may also be made available under the",
"elements: a list of xml elements :type elements: list \"\"\" for i in",
"elements and PersonGenerationElement objects. The PersonGenerationElement objects are replaced by elements generated from",
"be accessed directly by command line passing an input `.pflow.xml`` file's path and",
":return: The tag of xml element coresponding to this class (probability) \"\"\" return",
"/> </probabilityItem> <probabilityItem probability=\"0.5\" /> </probability> </probabilityItem> <probabilityItem probability=\"0.5\"> <ride busStop=\"3\" modes=\"public\"> </probabilityItem>",
"German Aerospace Center (DLR) and others. # This program and the accompanying materials",
"then stopping there for 50 ticks. The persons of this flow are spawned",
"xml elements :rtype list \"\"\" result = list() for element in elements: if",
"of Urban MObility; see https://eclipse.org/sumo # Copyright (C) 2019-2020 German Aerospace Center (DLR)",
"modes=\"public\" /> <probability> <probabilityItem probability=\"0.5\"> <stop busStop=\"2\" duration=\"10\" /> </probabilityItem> <probabilityItem probability=\"0.5\" />",
"waves with 10 persons pere wave. The route followed by the persons is",
"route followed by the persons of this flow is defined separately in a",
"It should return a list of elements generated by the element \"\"\" raise",
"in time) and each wave consists of 10 persons. For the persons going",
"route followed by the persons is defined directly under the ``<personFlow>`` How to",
"xml <probability> <probabilityItem probability=\"0.5\">fist alternative</probabilityItem> <probabilityItem probability=\"0.5\">second alternative</probabilityItem> </probability> Each time the element",
"for routes :type routes: collections.Iterable \"\"\" super().__init__(xml_element) self.routes = routes self.attributes = {item[0]:",
"attributes that concern us & we leave the others try: self.id = self.attributes.pop(self.id_attribute_key)",
"try: self.end = int(self.attributes.pop(self.end_attribute_key)) except KeyError: self.end = self.default_end try: self.period = int(self.attributes.pop(self.period_attribute_key))",
"the ``<personFlow>`` How to Use ---------- Via Command Line ~~~~~~~~~~~~~~~~ This script can",
"directly under the ``<personFlow>`` How to Use ---------- Via Command Line ~~~~~~~~~~~~~~~~ This",
"in another file. The resulting file will not contain the <personFlow> elements. Note",
"already possible for vehicles. For example, this xml code: .. code-block:: xml <personFlow",
"= self.xml_element.get(\"id\") self.children = list(self.xml_element) ProbabilityElement.wrap_elements(self.children) @classmethod def get_xml_tag(cls): \"\"\" :return: The tag",
"it looks like: .. code-block:: xml <probability> <probabilityItem probability=\"0.5\">fist alternative</probabilityItem> <probabilityItem probability=\"0.5\">second alternative</probabilityItem>",
"mandatory, if not given, uses the children of the <personFlow> element The id",
"# We check for the attributes that concern us & we leave the",
"self.period return elements def generate_persons(input_file, output_file): \"\"\" Core method of the script, parses",
"this xml code: .. code-block:: xml <personFlow id=\"flow\" begin=\"0\" end=\"3600\" number=\"7\" perWave=\"10\"> <walk",
"a 50% chance for each). The persons of this flow are spawned in",
"classes and methods in this module and use them in your own python",
"busStop=\"2\" modes=\"public\" /> <probability> <probabilityItem probability=\"0.5\"> <stop busStop=\"2\" duration=\"10\" /> </probabilityItem> <probabilityItem probability=\"0.5\"",
"can use probabilities inside the **personRoute** element to have different alternatives. Basically, you",
"ValueError(\"probabilityItem element requires attribute probability between 0 and 1\") if sum([child[0] for child",
": the number of persons in each wave. Not mandatory, default is 1",
"= tree.getroot() children = list(routes) for child in children: routes.remove(child) PersonRouteElement.wrap_elements(children) person_routes =",
"for route in routes: if isinstance(route, PersonRouteElement) and route.id == route_id: return route",
"is the index of the person in the flow (starting from 0) \"\"\"",
"class. The given list is modified, be careful :param elements: a list of",
"and then stopping there for 50 ticks. The persons of this flow are",
"in 7 waves (equally separated in time) and each wave consists of 10",
"by command line passing an input `.pflow.xml`` file's path and an output ``.rou.xml``",
"person_routes = [child for child in children if isinstance(child, PersonRouteElement)] PersonFlowElement.wrap_elements(children, routes=person_routes) for",
"</probabilityItem> <probabilityItem probability=\"0.5\"> second alternative </probabilityItem> </probability> This allows you to define conditional",
"item[1] for item in self.xml_element.items()} self.children = list(self.xml_element) ProbabilityElement.wrap_elements(self.children) self.id = None self.begin",
"class (personFlow) \"\"\" return \"personFlow\" def generate(self): \"\"\" :return: The persons of the",
"person_routes: children.remove(person_route) person_elements = PersonGenerationElement.generate_multiple(children) person_elements.sort(key=lambda e: int(e.get('depart'))) routes.extend(person_elements) with open(output_file, \"w\") as",
"from=\"e3\" busStop=\"3\" /> <ride busStop=\"1\" modes=\"public\"/> <stop busStop=\"1\" duration=\"50\"/> </personFlow> </routes> The example",
"Loops over a list containing xml elements and PersonGenerationElement objects. The PersonGenerationElement objects",
"PersonGenerationElement objects. :type elements: list :return: a list of resulting xml elements :rtype",
"xml_element: The xml element :param routes: An iterable where to look for routes",
"specified - perWave : the number of persons in each wave. Not mandatory,",
"elements, *args, **kwargs): \"\"\" Replaces xml elements with the appropriate tag (the one",
"the given id from the given iterable. None if not found \"\"\" for",
"waves each containing 10 persons. These waves will be equally separated in time",
"= etree.parse(input_file) routes = tree.getroot() children = list(routes) for child in children: routes.remove(child)",
"list() while begin <= self.end: for i in range(self.per_wave): element = etree.Element(\"person\", self.attributes)",
"== cls.get_xml_tag(): elements[i] = cls(elements[i], *args, **kwargs) @staticmethod def generate_multiple(elements): \"\"\" Loops over",
"persons of the flow \"\"\" begin = self.begin p_id = 0 elements =",
"the <personFlow> elements. Note that the output file is overwritten if it is",
"probability=\"0.5\" /> </probability> </probabilityItem> <probabilityItem probability=\"0.5\"> <ride busStop=\"3\" modes=\"public\"> </probabilityItem> </probability> </personRoute> <personFlow",
"code-block:: xml <probability> <probabilityItem probability=\"0.5\"> <probability> ... </probability> ...Possibly other stuff </probabilityItem> <probabilityItem",
"will be used - number : the number of waves. Only meaningful when",
"so by converting an xml file (usually having the ``.pflow.xml`` extension) to a",
"period nor number given for personFlow \" + str(id) + \", quitting\") exit(-1)",
"end=\"3600\" period=\"600\" perWave=\"10\" departPos=\"0\"> <walk from=\"e3\" busStop=\"3\" /> <ride busStop=\"1\" modes=\"public\"/> <stop busStop=\"1\"",
"file :param output_file: The path of the output file \"\"\" # Parse the",
"<probability> <probabilityItem probability=\"0.5\"> <ride busStop=\"2\" modes=\"public\" /> </probabilityItem> <probabilityItem probability=\"0.5\"> <ride busStop=\"3\" modes=\"public\"",
"generated by the element \"\"\" raise NotImplementedError @classmethod def wrap_elements(cls, elements, *args, **kwargs):",
": the time at which the flow starts - end : the time",
"<person> elements. The generated <person> elements are sorted by their depart time. The",
"this flow are spawned in 7 waves (equally separated in time) and each",
"materials are made available under the # terms of the Eclipse Public License",
"Here is an example ``.pflow.xml`` : .. code-block:: xml <routes> <personRoute id=\"route-1\"> <walk",
"chance they'll stay there during 10 ticks. The route followed by the persons",
"result = [] cumulated_probability = 0 p = random.random() for possibility in self.possibilities:",
"files. It does so by converting an xml file (usually having the ``.pflow.xml``",
"you can have: .. code-block:: xml <personRoute id=\"route\"> <walk from=\"edge1\" busStop=\"1\"> <probability> <probabilityItem",
"it returns the children of one of its alternatives according to the probabilities.",
"self.end = int(self.attributes.pop(self.end_attribute_key)) except KeyError: self.end = self.default_end try: self.period = int(self.attributes.pop(self.period_attribute_key)) except",
"xml_element): super().__init__(xml_element) self.id = self.xml_element.get(\"id\") self.children = list(self.xml_element) ProbabilityElement.wrap_elements(self.children) @classmethod def get_xml_tag(cls): \"\"\"",
"script. See the documentation below for more details. \"\"\" from lxml import etree",
"+ 1 else: self.period = (self.end - self.begin) / (self.number - 1) except",
"looks like: .. code-block:: xml <probability> <probabilityItem probability=\"0.5\">fist alternative</probabilityItem> <probabilityItem probability=\"0.5\">second alternative</probabilityItem> </probability>",
"return elements def generate_persons(input_file, output_file): \"\"\" Core method of the script, parses <personFlow>",
"int(e.get('depart'))) routes.extend(person_elements) with open(output_file, \"w\") as f: f.write(etree.tostring(routes).decode()) f.close() if __name__ == \"__main__\":",
"for elements described by the current class \"\"\" raise NotImplementedError def generate(self): \"\"\"",
"\"\"\" for i in range(len(elements)): if not isinstance(elements[i], PersonGenerationElement) and elements[i].tag == cls.get_xml_tag():",
"python personGenerator.py pedestrians.pflow.xml pedestrians.rou.xml Note that the output file is overwritten without asking",
"routes = tree.getroot() children = list(routes) for child in children: routes.remove(child) PersonRouteElement.wrap_elements(children) person_routes",
"\"\"\" :return: The tag of the xml elements corresponding to the current class",
"0 elements = list() while begin <= self.end: for i in range(self.per_wave): element",
"*args, **kwargs) @staticmethod def generate_multiple(elements): \"\"\" Loops over a list containing xml elements",
"elements are sorted by their depart time. The original file is not modified",
"3600 id_attribute_key = \"id\" begin_attribute_key = \"begin\" end_attribute_key = \"end\" period_attribute_key = \"period\"",
"Eclipse # Public License 2.0 are satisfied: GNU General Public License, version 2",
"PersonRouteElement(PersonGenerationElement): \"\"\" This class describes xml elements that are used to define person",
"that the output file is overwritten without asking for permission. In your script",
"flow are spawned in periodic waves with 10 persons pere wave. The route",
"This method is meant to be implemented by subclasses It should return a",
"extension) to a sumo route file containing the generated <peron> elements. Here is",
"/> </probabilityItem> </probability> </personRoute> \"\"\" def __init__(self, xml_element): super().__init__(xml_element) self.id = self.xml_element.get(\"id\") self.children",
"to look for routes :type routes: collections.Iterable \"\"\" super().__init__(xml_element) self.routes = routes self.attributes",
"xml elements with the appropriate tag (the one defined in get_xml_tag) with an",
"end=\"3600\" number=\"7\" perWave=\"10\"> <walk /> <ride /> <stop /> </personFlow> will generate person",
"self.get_xml_tag(): raise Exception(\"Bad tag\") @classmethod def get_xml_tag(cls): \"\"\" This class method is meant",
"self.xml_element.get(\"id\") self.children = list(self.xml_element) ProbabilityElement.wrap_elements(self.children) @classmethod def get_xml_tag(cls): \"\"\" :return: The tag of",
"are replaced by elements generated from them The given list is not modified",
"that the nested <probability> element should be a direct child of <probabilityItem> \"\"\"",
"will generate person elements having the same children (walk, ride, stop). The generated",
"License 2.0 are satisfied: GNU General Public License, version 2 # or later",
"not summing up to 1 at line : \" + str(self.xml_element.sourceline)) @classmethod def",
"route_id = self.attributes.pop(self.route_attribute_key) self.route = PersonRouteElement.get_route_by_id(routes, route_id) if self.route is None: raise Exception(\"Route",
"</personFlow> </routes> The example above allows to generate two flows of persons :",
"the others try: self.id = self.attributes.pop(self.id_attribute_key) except KeyError: print(\"No id attribute in personFlow,",
"input file tree = etree.parse(input_file) routes = tree.getroot() children = list(routes) for child",
"/> <ride busStop=\"1\" modes=\"public\"/> <stop busStop=\"1\" duration=\"50\"/> </personFlow> </routes> The example above allows",
"__init__(self, xml_element): self.xml_element = xml_element if self.xml_element.tag != self.get_xml_tag(): raise Exception(\"Bad tag\") @classmethod",
"ProbabilityElement.wrap_elements(self.children) self.id = None self.begin = None self.period = None self.route = None",
"= PersonRouteElement.get_route_by_id(routes, route_id) if self.route is None: raise Exception(\"Route with id \" +",
"Public License 2.0 which is available at # https://www.eclipse.org/legal/epl-2.0/ # This Source Code",
"Core method of the script, parses <personFlow> tags in an XML file and",
"overwritten if it is already exist :param input_file: The path of the input",
"= self.begin p_id = 0 elements = list() while begin <= self.end: for",
"having the same children (walk, ride, stop). The generated persons will be in",
"tags in an XML file and generates <person> elements. The generated <person> elements",
"path and an output ``.rou.xml`` file's path. .. code-block:: bash python personGenerator.py pedestrians.pflow.xml",
"xml <routes> <personRoute id=\"route-1\"> <walk from=\"e1\" busStop=\"1\" /> <probability> <probabilityItem probability=\"0.5\"> <ride busStop=\"2\"",
"flows of persons : - The first flow consists of persons taking a",
"= int(self.attributes.pop(self.number_attribute_key)) if self.number == 1: self.period = (self.end - self.begin) * 2",
"None: raise Exception(\"Route with id \" + route_id + \" not found at",
"list is: - id - begin : the time at which the flow",
"[child for child in children if isinstance(child, PersonRouteElement)] PersonFlowElement.wrap_elements(children, routes=person_routes) for person_route in",
"have: .. code-block:: xml <personRoute id=\"route\"> <walk from=\"edge1\" busStop=\"1\"> <probability> <probabilityItem probability=\"0.5\"> <ride",
"probability=\"0.5\"> <probability> ... </probability> ...Possibly other stuff </probabilityItem> <probabilityItem probability=\"0.5\"> second alternative </probabilityItem>",
"= \"route\" def __init__(self, xml_element, routes): \"\"\" :param xml_element: The xml element :param",
"You can use probabilities inside the **personRoute** element to have different alternatives. Basically,",
"is defined directly under the ``<personFlow>`` How to Use ---------- Via Command Line",
"end_attribute_key = \"end\" period_attribute_key = \"period\" number_attribute_key = \"number\" per_wave_attribute_key = \"perWave\" route_attribute_key",
"~~~~~~~~~~~~~~~~ This script can be accessed directly by command line passing an input",
"child in self.possibilities]) != 1: raise ValueError(\"Probabilities not summing up to 1 at",
"person_elements.sort(key=lambda e: int(e.get('depart'))) routes.extend(person_elements) with open(output_file, \"w\") as f: f.write(etree.tostring(routes).decode()) f.close() if __name__",
"is not specified - perWave : the number of persons in each wave.",
"by the element \"\"\" raise NotImplementedError @classmethod def wrap_elements(cls, elements, *args, **kwargs): \"\"\"",
"modified and the result is written in another file. The resulting file will",
"element and referenced by its ID. - The second flow consists of persons",
"flow ends. Not mandatory, default is 3600. - period : The time (in",
"element coresponding to this class (probability) \"\"\" return \"probability\" def generate(self): \"\"\" :return:",
":param elements: a list of xml elements :type elements: list \"\"\" for i",
"waves. Only meaningful when period is not specified - perWave : the number",
"ticks. The persons of this flow are spawned in periodic waves with 10",
"probability=\"0.5\"> <stop busStop=\"2\" duration=\"10\" /> </probabilityItem> <probabilityItem probability=\"0.5\" /> </probability> </probabilityItem> <probabilityItem probability=\"0.5\">",
"between 0 and 3600 The complete attributes list is: - id - begin",
"list is not modified :param elements: A list containing xml elements and PersonGenerationElement",
"</probability> </personRoute> \"\"\" def __init__(self, xml_element): super().__init__(xml_element) self.id = self.xml_element.get(\"id\") self.children = list(self.xml_element)",
"return None def generate(self): \"\"\" :return: A copy of the sub elements of",
"This script can be accessed directly by command line passing an input `.pflow.xml``",
"tree = etree.parse(input_file) routes = tree.getroot() children = list(routes) for child in children:",
"generation elements \"\"\" def __init__(self, xml_element): self.xml_element = xml_element if self.xml_element.tag != self.get_xml_tag():",
"!= \"probabilityItem\": raise Exception(\"Only probabilityItem elements are allowed inside probability\") try: proba =",
"forth in the Eclipse # Public License 2.0 are satisfied: GNU General Public",
"an xml file (usually having the ``.pflow.xml`` extension) to a sumo route file",
"The example above allows to generate two flows of persons : - The",
"exit(-1) try: self.begin = int(self.attributes.pop(self.begin_attribute_key)) except KeyError: print(\"No begin in personFlow \" +",
"None self.begin = None self.period = None self.route = None # We check",
"break return result class PersonRouteElement(PersonGenerationElement): \"\"\" This class describes xml elements that are",
"for 50 ticks. The persons of this flow are spawned in periodic waves",
"satisfied: GNU General Public License, version 2 # or later which is available",
"/> <stop /> <ride /> </personRoute> The content of the route is then",
"an example ``.pflow.xml`` : .. code-block:: xml <routes> <personRoute id=\"route-1\"> <walk from=\"e1\" busStop=\"1\"",
"of the output file \"\"\" # Parse the input file tree = etree.parse(input_file)",
"the Eclipse # Public License 2.0 are satisfied: GNU General Public License, version",
"\"number\" per_wave_attribute_key = \"perWave\" route_attribute_key = \"route\" def __init__(self, xml_element, routes): \"\"\" :param",
"\"\"\" :param xml_element: The source xml element \"\"\" super().__init__(xml_element) self.possibilities = [] for",
"Parses the command line arguments parser = argparse.ArgumentParser() parser.add_argument(\"source\") parser.add_argument(\"destination\") source, destination =",
"stop 2 or stop 3 (with a 50% chance for each). The persons",
"result class PersonRouteElement(PersonGenerationElement): \"\"\" This class describes xml elements that are used to",
"This allows you to define conditional probabilities. Note that the nested <probability> element",
"we leave the others try: self.id = self.attributes.pop(self.id_attribute_key) except KeyError: print(\"No id attribute",
"begin in personFlow \" + str(id) + \", quitting\") exit(-1) try: self.end =",
"the children of the <personFlow> element The id of generated persons will be",
"defined in get_xml_tag) with an object of the current class. The given list",
"raise NotImplementedError def generate(self): \"\"\" This method is meant to be implemented by",
"Not mandatory, default is 3600. - period : The time (in seconds) between",
"of elements generated by the element \"\"\" raise NotImplementedError @classmethod def wrap_elements(cls, elements,",
"the route is then copied to each person using it. You can use",
"The persons of this flow are spawned in periodic waves with 10 persons",
"cls.get_xml_tag(): elements[i] = cls(elements[i], *args, **kwargs) @staticmethod def generate_multiple(elements): \"\"\" Loops over a",
"<probabilityItem probability=\"0.5\"> <ride busStop=\"2\" modes=\"public\" /> </probabilityItem> <probabilityItem probability=\"0.5\"> <ride busStop=\"3\" modes=\"public\" />",
"xml elements :type elements: list \"\"\" for i in range(len(elements)): if not isinstance(elements[i],",
"a SUMO simulation which is currently not possible in SUMO route files. It",
":param xml_element: The source xml element \"\"\" super().__init__(xml_element) self.possibilities = [] for sub_element",
"PersonRouteElement)] PersonFlowElement.wrap_elements(children, routes=person_routes) for person_route in person_routes: children.remove(person_route) person_elements = PersonGenerationElement.generate_multiple(children) person_elements.sort(key=lambda e:",
"if self.route is None: raise Exception(\"Route with id \" + route_id + \"",
"flow (starting from 0) \"\"\" default_end = 3600 id_attribute_key = \"id\" begin_attribute_key =",
"\"\"\" Loops over a list containing xml elements and PersonGenerationElement objects. The PersonGenerationElement",
"return result class ProbabilityElement(PersonGenerationElement): \"\"\" This class describes probability elements that are used",
"Command Line ~~~~~~~~~~~~~~~~ This script can be accessed directly by command line passing",
"the nested <probability> element should be a direct child of <probabilityItem> \"\"\" def",
"str(p_id)) if self.route is not None: element.extend(self.route.generate()) else: element.extend(self.generate_multiple(self.children)) elements.append(element) p_id += 1",
"= list() for element in elements: if isinstance(element, PersonGenerationElement): result.extend(element.generate()) else: result.append(element.__copy__()) return",
"xml_element if self.xml_element.tag != self.get_xml_tag(): raise Exception(\"Bad tag\") @classmethod def get_xml_tag(cls): \"\"\" This",
"between 0 and 1\") if sum([child[0] for child in self.possibilities]) != 1: raise",
"in self.xml_element.items()} self.children = list(self.xml_element) ProbabilityElement.wrap_elements(self.children) self.id = None self.begin = None self.period",
"its ID. - The second flow consists of persons taking a bus from",
"probability=\"0.5\"> second alternative </probabilityItem> </probability> This allows you to define conditional probabilities. Note",
"persons will follow Not mandatory, if not given, uses the children of the",
"methods in this module and use them in your own python script. See",
"self.end: for i in range(self.per_wave): element = etree.Element(\"person\", self.attributes) element.set(\"depart\", str(int(begin))) element.set(\"id\", self.id",
"input_file: The path of the input file :param output_file: The path of the",
"route_id) if self.route is None: raise Exception(\"Route with id \" + route_id +",
"Eclipse Public License 2.0 which is available at # https://www.eclipse.org/legal/epl-2.0/ # This Source",
"the persons going to bus stop 2, there's a 50% chance they'll stay",
"code-block:: xml <probability> <probabilityItem probability=\"0.5\">fist alternative</probabilityItem> <probabilityItem probability=\"0.5\">second alternative</probabilityItem> </probability> Each time the",
"\"\"\" raise NotImplementedError @classmethod def wrap_elements(cls, elements, *args, **kwargs): \"\"\" Replaces xml elements",
"self.attributes.pop(self.id_attribute_key) except KeyError: print(\"No id attribute in personFlow, quitting\") exit(-1) try: self.begin =",
"to either stop 2 or stop 3 (with a 50% chance for each).",
"child in children: routes.remove(child) PersonRouteElement.wrap_elements(children) person_routes = [child for child in children if",
"conditional probabilities. Note that the nested <probability> element should be a direct child",
"alternative</probabilityItem> </probability> Each time the element is asked to generate, it returns the",
"the # terms of the Eclipse Public License 2.0 which is available at",
"def __init__(self, xml_element): \"\"\" :param xml_element: The source xml element \"\"\" super().__init__(xml_element) self.possibilities",
"there for 50 ticks. The persons of this flow are spawned in periodic",
"element.extend(self.route.generate()) else: element.extend(self.generate_multiple(self.children)) elements.append(element) p_id += 1 begin += self.period return elements def",
"is asked to generate, it returns the children of one of its alternatives",
"list of resulting xml elements :rtype list \"\"\" result = list() for element",
"can be accessed directly by command line passing an input `.pflow.xml`` file's path",
"stop 1 and then stopping there for 50 ticks. The persons of this",
"be nested, so you can have: .. code-block:: xml <probability> <probabilityItem probability=\"0.5\"> <probability>",
"ticks. The route followed by the persons of this flow is defined separately",
"persons taking a bus from stop 1 to either stop 2 or stop",
"In XML it looks like: .. code-block:: xml <probability> <probabilityItem probability=\"0.5\">fist alternative</probabilityItem> <probabilityItem",
"busStop=\"3\" /> <ride busStop=\"1\" modes=\"public\"/> <stop busStop=\"1\" duration=\"50\"/> </personFlow> </routes> The example above",
"try: proba = float(sub_element.get(\"probability\")) if proba < 0 or proba > 1: raise",
"**kwargs) @staticmethod def generate_multiple(elements): \"\"\" Loops over a list containing xml elements and",
"self.id = self.attributes.pop(self.id_attribute_key) except KeyError: print(\"No id attribute in personFlow, quitting\") exit(-1) try:",
"item in self.xml_element.items()} self.children = list(self.xml_element) ProbabilityElement.wrap_elements(self.children) self.id = None self.begin = None",
"requires attribute probability between 0 and 1\") if sum([child[0] for child in self.possibilities])",
"</personFlow> will generate person elements having the same children (walk, ride, stop). The",
"meaningful when period is not specified - perWave : the number of persons",
"consists of 10 persons. For the persons going to bus stop 2, there's",
"SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later # @file personGenerator.py # @author <NAME> # @date 2019-03-22",
"get_xml_tag) with an object of the current class. The given list is modified,",
"0) \"\"\" default_end = 3600 id_attribute_key = \"id\" begin_attribute_key = \"begin\" end_attribute_key =",
"= self.attributes.pop(self.id_attribute_key) except KeyError: print(\"No id attribute in personFlow, quitting\") exit(-1) try: self.begin",
"__name__ == \"__main__\": # Parses the command line arguments parser = argparse.ArgumentParser() parser.add_argument(\"source\")",
"\"\"\" def __init__(self, xml_element): super().__init__(xml_element) self.id = self.xml_element.get(\"id\") self.children = list(self.xml_element) ProbabilityElement.wrap_elements(self.children) @classmethod",
"wave. The route followed by the persons is defined directly under the ``<personFlow>``",
"if p <= cumulated_probability: result.extend(self.generate_multiple(possibility[1])) break return result class PersonRouteElement(PersonGenerationElement): \"\"\" This class",
"bus from stop 1 to either stop 2 or stop 3 (with a",
"isinstance(element, PersonGenerationElement): result.extend(element.generate()) else: result.append(element.__copy__()) return result class ProbabilityElement(PersonGenerationElement): \"\"\" This class describes",
"be implemented by subclasses It should return a list of elements generated by",
"result.extend(self.generate_multiple(possibility[1])) break return result class PersonRouteElement(PersonGenerationElement): \"\"\" This class describes xml elements that",
"= None self.period = None self.route = None # We check for the",
"in this module and use them in your own python script. See the",
"to be implemented by subclasses It should return a list of elements generated",
"the same children (walk, ride, stop). The generated persons will be in 7",
"PersonGenerationElement objects are replaced by elements generated from them The given list is",
"The tag of the xml elements corresponding to the current class (personFlow) \"\"\"",
"tag for elements described by the current class \"\"\" raise NotImplementedError def generate(self):",
"that are used to generate flows of persons as it is already possible",
"SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo # Copyright (C) 2019-2020 German Aerospace",
"alternative</probabilityItem> <probabilityItem probability=\"0.5\">second alternative</probabilityItem> </probability> Each time the element is asked to generate,",
"\"\"\" def __init__(self, xml_element): self.xml_element = xml_element if self.xml_element.tag != self.get_xml_tag(): raise Exception(\"Bad",
"they'll stay there during 10 ticks. The route followed by the persons of",
"file \"\"\" # Parse the input file tree = etree.parse(input_file) routes = tree.getroot()",
"\" + route_id + \" not found at line \" + str(self.xml_element.sourceline)) except",
"consists of persons taking a bus from stop 3 to stop 1 and",
"of this flow are spawned in 7 waves (equally separated in time) and",
"import etree import argparse import random class PersonGenerationElement(object): \"\"\" This class serves as",
"at # https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html # SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later # @file personGenerator.py # @author",
"waves. Not mandatory, if not given, number will be used - number :",
"2019-03-22 \"\"\" This tool allows to generate flows of persons for a SUMO",
"have different alternatives. Basically, you can have: .. code-block:: xml <personRoute id=\"route\"> <walk",
"the Eclipse Public License 2.0 which is available at # https://www.eclipse.org/legal/epl-2.0/ # This",
"# @author <NAME> # @date 2019-03-22 \"\"\" This tool allows to generate flows",
"another file. The resulting file will not contain the <personFlow> elements. Note that",
"</probabilityItem> </probability> </personRoute> \"\"\" def __init__(self, xml_element): super().__init__(xml_element) self.id = self.xml_element.get(\"id\") self.children =",
"\" not found at line \" + str(self.xml_element.sourceline)) except KeyError: pass @classmethod def",
"<stop busStop=\"1\" duration=\"50\"/> </personFlow> </routes> The example above allows to generate two flows",
".. code-block:: xml <probability> <probabilityItem probability=\"0.5\">fist alternative</probabilityItem> <probabilityItem probability=\"0.5\">second alternative</probabilityItem> </probability> Each time",
"xml elements that are used to generate flows of persons as it is",
"or stop 3 (with a 50% chance for each). The persons of this",
"`.pflow.xml`` file's path and an output ``.rou.xml`` file's path. .. code-block:: bash python",
"output ``.rou.xml`` file's path. .. code-block:: bash python personGenerator.py pedestrians.pflow.xml pedestrians.rou.xml Note that",
"1: raise ValueError(\"\") possibility = (proba, list(sub_element)) ProbabilityElement.wrap_elements(possibility[1]) self.possibilities.append(possibility) except (KeyError, ValueError): raise",
"in self.possibilities: cumulated_probability += float(possibility[0]) if p <= cumulated_probability: result.extend(self.generate_multiple(possibility[1])) break return result",
"vehicles. For example, this xml code: .. code-block:: xml <personFlow id=\"flow\" begin=\"0\" end=\"3600\"",
"def wrap_elements(cls, elements, *args, **kwargs): \"\"\" Replaces xml elements with the appropriate tag",
"random.random() for possibility in self.possibilities: cumulated_probability += float(possibility[0]) if p <= cumulated_probability: result.extend(self.generate_multiple(possibility[1]))",
"This class serves as a base for person generation elements \"\"\" def __init__(self,",
"sub_element.tag != \"probabilityItem\": raise Exception(\"Only probabilityItem elements are allowed inside probability\") try: proba",
"Simulation of Urban MObility; see https://eclipse.org/sumo # Copyright (C) 2019-2020 German Aerospace Center",
"of 10 persons. For the persons going to bus stop 2, there's a",
"etree import argparse import random class PersonGenerationElement(object): \"\"\" This class serves as a",
"elements: A list containing xml elements and PersonGenerationElement objects. :type elements: list :return:",
"depart time. The original file is not modified and the result is written",
"consists of persons taking a bus from stop 1 to either stop 2",
"by the persons of this flow is defined separately in a ``<personRoute>`` element",
"= \"end\" period_attribute_key = \"period\" number_attribute_key = \"number\" per_wave_attribute_key = \"perWave\" route_attribute_key =",
"to this class (personRoute) \"\"\" return \"personRoute\" @staticmethod def get_route_by_id(routes, route_id): \"\"\" :param",
"<walk from=\"e1\" busStop=\"1\" /> <probability> <probabilityItem probability=\"0.5\"> <ride busStop=\"2\" modes=\"public\" /> <probability> <probabilityItem",
"and an output ``.rou.xml`` file's path. .. code-block:: bash python personGenerator.py pedestrians.pflow.xml pedestrians.rou.xml",
"according to the given probabilities \"\"\" result = [] cumulated_probability = 0 p",
"in children if isinstance(child, PersonRouteElement)] PersonFlowElement.wrap_elements(children, routes=person_routes) for person_route in person_routes: children.remove(person_route) person_elements",
"should be a direct child of <probabilityItem> \"\"\" def __init__(self, xml_element): \"\"\" :param",
"route that the persons will follow Not mandatory, if not given, uses the",
"persons of this flow are spawned in 7 waves (equally separated in time)",
"list(self.xml_element) ProbabilityElement.wrap_elements(self.children) @classmethod def get_xml_tag(cls): \"\"\" :return: The tag of the xml elements",
"self.begin = None self.period = None self.route = None # We check for",
"direct child of <probabilityItem> \"\"\" def __init__(self, xml_element): \"\"\" :param xml_element: The source",
"their depart time. The original file is not modified and the result is",
"two flows of persons : - The first flow consists of persons taking",
"perWave : the number of persons in each wave. Not mandatory, default is",
":return: The tag of the xml elements corresponding to this class (personRoute) \"\"\"",
"each person using it. You can use probabilities inside the **personRoute** element to",
"</probabilityItem> <probabilityItem probability=\"0.5\" /> </probability> </probabilityItem> <probabilityItem probability=\"0.5\"> <ride busStop=\"3\" modes=\"public\"> </probabilityItem> </probability>",
"the element is asked to generate, it returns the children of one of",
"elements :type elements: list \"\"\" for i in range(len(elements)): if not isinstance(elements[i], PersonGenerationElement)",
"self.begin) / (self.number - 1) except KeyError: print(\"Neither period nor number given for",
"\"\"\" return \"probability\" def generate(self): \"\"\" :return: One of the alternatives according to",
"cumulated_probability += float(possibility[0]) if p <= cumulated_probability: result.extend(self.generate_multiple(possibility[1])) break return result class PersonRouteElement(PersonGenerationElement):",
"None self.route = None # We check for the attributes that concern us",
"xml code: .. code-block:: xml <personFlow id=\"flow\" begin=\"0\" end=\"3600\" number=\"7\" perWave=\"10\"> <walk />",
"followed by the persons of this flow is defined separately in a ``<personRoute>``",
"for possibility in self.possibilities: cumulated_probability += float(possibility[0]) if p <= cumulated_probability: result.extend(self.generate_multiple(possibility[1])) break",
"example ``.pflow.xml`` : .. code-block:: xml <routes> <personRoute id=\"route-1\"> <walk from=\"e1\" busStop=\"1\" />",
"element probability elements are taken into account & used to generate an alternative",
"The tag of xml element coresponding to this class (probability) \"\"\" return \"probability\"",
"\"\"\" raise NotImplementedError def generate(self): \"\"\" This method is meant to be implemented",
"modes=\"public\"/> <stop busStop=\"1\" duration=\"50\"/> </personFlow> </routes> The example above allows to generate two",
"to each person using it. You can use probabilities inside the **personRoute** element",
":return: One of the alternatives according to the given probabilities \"\"\" result =",
"as it is already possible for vehicles. For example, this xml code: ..",
"< 0 or proba > 1: raise ValueError(\"\") possibility = (proba, list(sub_element)) ProbabilityElement.wrap_elements(possibility[1])",
"None if not found \"\"\" for route in routes: if isinstance(route, PersonRouteElement) and",
"this class (probability) \"\"\" return \"probability\" def generate(self): \"\"\" :return: One of the",
"KeyError: pass @classmethod def get_xml_tag(cls): \"\"\" :return: The tag of the xml elements",
"License, version 2 # or later which is available at # https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html #",
"routes: if isinstance(route, PersonRouteElement) and route.id == route_id: return route return None def",
"if proba < 0 or proba > 1: raise ValueError(\"\") possibility = (proba,",
"probability elements that are used to generate alternatives with given probabilities. In XML",
"id \" + route_id + \" not found at line \" + str(self.xml_element.sourceline))",
"if it is already exist :param input_file: The path of the input file",
"xml <personRoute id=\"route\"> <walk /> <stop /> <ride /> </personRoute> The content of",
"implemented by subclasses It should return the xml tag for elements described by",
"which the flow ends. Not mandatory, default is 3600. - period : The",
"\"_\" + str(p_id)) if self.route is not None: element.extend(self.route.generate()) else: element.extend(self.generate_multiple(self.children)) elements.append(element) p_id",
"current class \"\"\" raise NotImplementedError def generate(self): \"\"\" This method is meant to",
"argparse import random class PersonGenerationElement(object): \"\"\" This class serves as a base for",
"while begin <= self.end: for i in range(self.per_wave): element = etree.Element(\"person\", self.attributes) element.set(\"depart\",",
"probability=\"0.5\">second alternative</probabilityItem> </probability> Each time the element is asked to generate, it returns",
"\"\"\" def __init__(self, xml_element): \"\"\" :param xml_element: The source xml element \"\"\" super().__init__(xml_element)",
"routes=person_routes) for person_route in person_routes: children.remove(person_route) person_elements = PersonGenerationElement.generate_multiple(children) person_elements.sort(key=lambda e: int(e.get('depart'))) routes.extend(person_elements)",
"<probabilityItem probability=\"0.5\"> <stop busStop=\"2\" duration=\"10\" /> </probabilityItem> <probabilityItem probability=\"0.5\" /> </probability> </probabilityItem> <probabilityItem",
"subclasses It should return the xml tag for elements described by the current",
"= 0 elements = list() while begin <= self.end: for i in range(self.per_wave):",
"<probability> element should be a direct child of <probabilityItem> \"\"\" def __init__(self, xml_element):",
"code-block:: xml <personFlow id=\"flow\" begin=\"0\" end=\"3600\" number=\"7\" perWave=\"10\"> <walk /> <ride /> <stop",
"the script, parses <personFlow> tags in an XML file and generates <person> elements.",
"which is available at # https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html # SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later # @file",
"waves will be equally separated in time between 0 and 3600 The complete",
"output file \"\"\" # Parse the input file tree = etree.parse(input_file) routes =",
"subclasses It should return a list of elements generated by the element \"\"\"",
"allowed inside probability\") try: proba = float(sub_element.get(\"probability\")) if proba < 0 or proba",
"(probability) \"\"\" return \"probability\" def generate(self): \"\"\" :return: One of the alternatives according",
"Note that the output file is overwritten if it is already exist :param",
"where to look for routes :type routes: collections.Iterable \"\"\" super().__init__(xml_element) self.routes = routes",
"spawned in periodic waves with 10 persons pere wave. The route followed by",
"except (KeyError, ValueError): raise ValueError(\"probabilityItem element requires attribute probability between 0 and 1\")",
"- period : The time (in seconds) between two consecutive waves. Not mandatory,",
"of the current class. The given list is modified, be careful :param elements:",
"flow consists of persons taking a bus from stop 1 to either stop",
"@classmethod def get_xml_tag(cls): \"\"\" This class method is meant to be implemented by",
"file's path. .. code-block:: bash python personGenerator.py pedestrians.pflow.xml pedestrians.rou.xml Note that the output",
"number=\"7\" perWave=\"10\" departPos=\"0\" route=\"forward\" /> <personFlow id=\"backward\" begin=\"0\" end=\"3600\" period=\"600\" perWave=\"10\" departPos=\"0\"> <walk",
"of its alternatives according to the probabilities. Probability elements can be nested, so",
"busStop=\"3\" modes=\"public\"> </probabilityItem> </probability> </personRoute> <personFlow id=\"forward\" begin=\"0\" end=\"3600\" number=\"7\" perWave=\"10\" departPos=\"0\" route=\"forward\"",
"\"period\" number_attribute_key = \"number\" per_wave_attribute_key = \"perWave\" route_attribute_key = \"route\" def __init__(self, xml_element,",
"10 persons. These waves will be equally separated in time between 0 and",
"the given probabilities \"\"\" result = [] cumulated_probability = 0 p = random.random()",
"return route return None def generate(self): \"\"\" :return: A copy of the sub",
"of the Eclipse Public License 2.0 which is available at # https://www.eclipse.org/legal/epl-2.0/ #",
"``<personRoute>`` element and referenced by its ID. - The second flow consists of",
"are used to generate alternatives with given probabilities. In XML it looks like:",
"</probability> ...Possibly other stuff </probabilityItem> <probabilityItem probability=\"0.5\"> second alternative </probabilityItem> </probability> This allows",
"<personFlow id=\"forward\" begin=\"0\" end=\"3600\" number=\"7\" perWave=\"10\" departPos=\"0\" route=\"forward\" /> <personFlow id=\"backward\" begin=\"0\" end=\"3600\"",
"raise ValueError(\"\") possibility = (proba, list(sub_element)) ProbabilityElement.wrap_elements(possibility[1]) self.possibilities.append(possibility) except (KeyError, ValueError): raise ValueError(\"probabilityItem",
"the input file :param output_file: The path of the output file \"\"\" #",
"as f: f.write(etree.tostring(routes).decode()) f.close() if __name__ == \"__main__\": # Parses the command line",
"stuff </probabilityItem> <probabilityItem probability=\"0.5\"> second alternative </probabilityItem> </probability> This allows you to define",
"list of elements generated by the element \"\"\" raise NotImplementedError @classmethod def wrap_elements(cls,",
"a bus from stop 3 to stop 1 and then stopping there for",
".. code-block:: bash python personGenerator.py pedestrians.pflow.xml pedestrians.rou.xml Note that the output file is",
"route_id + \" not found at line \" + str(self.xml_element.sourceline)) except KeyError: pass",
"GNU General Public License, version 2 # or later which is available at",
"else: self.period = (self.end - self.begin) / (self.number - 1) except KeyError: print(\"Neither",
"at which the flow starts - end : the time at which the",
"person_elements = PersonGenerationElement.generate_multiple(children) person_elements.sort(key=lambda e: int(e.get('depart'))) routes.extend(person_elements) with open(output_file, \"w\") as f: f.write(etree.tostring(routes).decode())",
"is modified, be careful :param elements: a list of xml elements :type elements:",
"and PersonGenerationElement objects. :type elements: list :return: a list of resulting xml elements",
"\", quitting\") exit(-1) try: self.per_wave = int(self.attributes.pop(self.per_wave_attribute_key)) except KeyError: self.per_wave = 1 try:",
"list(routes) for child in children: routes.remove(child) PersonRouteElement.wrap_elements(children) person_routes = [child for child in",
"\"\"\" This class describes xml elements that are used to define person routes",
"xml elements that are used to define person routes separately. .. code-block:: xml",
"stop). The generated persons will be in 7 waves each containing 10 persons.",
"children: routes.remove(child) PersonRouteElement.wrap_elements(children) person_routes = [child for child in children if isinstance(child, PersonRouteElement)]",
"ValueError): raise ValueError(\"probabilityItem element requires attribute probability between 0 and 1\") if sum([child[0]",
"for sub_element in list(self.xml_element): if sub_element.tag != \"probabilityItem\": raise Exception(\"Only probabilityItem elements are",
"waves (equally separated in time) and each wave consists of 10 persons. For",
"result.extend(element.generate()) else: result.append(element.__copy__()) return result class ProbabilityElement(PersonGenerationElement): \"\"\" This class describes probability elements",
"in SUMO route files. It does so by converting an xml file (usually",
"elements described by the current class \"\"\" raise NotImplementedError def generate(self): \"\"\" This",
"default_end = 3600 id_attribute_key = \"id\" begin_attribute_key = \"begin\" end_attribute_key = \"end\" period_attribute_key",
"raise Exception(\"Route with id \" + route_id + \" not found at line",
": .. code-block:: xml <routes> <personRoute id=\"route-1\"> <walk from=\"e1\" busStop=\"1\" /> <probability> <probabilityItem",
"raise Exception(\"Only probabilityItem elements are allowed inside probability\") try: proba = float(sub_element.get(\"probability\")) if",
"probability=\"0.5\"> <ride busStop=\"2\" modes=\"public\" /> <probability> <probabilityItem probability=\"0.5\"> <stop busStop=\"2\" duration=\"10\" /> </probabilityItem>",
"tag\") @classmethod def get_xml_tag(cls): \"\"\" This class method is meant to be implemented",
"`<id>_<person_index>` where `<person_index>` is the index of the person in the flow (starting",
"pere wave. The route followed by the persons is defined directly under the",
"(personFlow) \"\"\" return \"personFlow\" def generate(self): \"\"\" :return: The persons of the flow",
"element should be a direct child of <probabilityItem> \"\"\" def __init__(self, xml_element): \"\"\"",
"collections.Iterable :param route_id: :type route_id: str :return: The PersonRouteElement object having the given",
"documentation below for more details. \"\"\" from lxml import etree import argparse import",
"1 at line : \" + str(self.xml_element.sourceline)) @classmethod def get_xml_tag(cls): \"\"\" :return: The",
"of this flow is defined separately in a ``<personRoute>`` element and referenced by",
"self.possibilities = [] for sub_element in list(self.xml_element): if sub_element.tag != \"probabilityItem\": raise Exception(\"Only",
"xml tag for elements described by the current class \"\"\" raise NotImplementedError def",
"self.xml_element.items()} self.children = list(self.xml_element) ProbabilityElement.wrap_elements(self.children) self.id = None self.begin = None self.period =",
"when period is not specified - perWave : the number of persons in",
"def generate(self): \"\"\" :return: The persons of the flow \"\"\" begin = self.begin",
"1\") if sum([child[0] for child in self.possibilities]) != 1: raise ValueError(\"Probabilities not summing",
"= list(self.xml_element) ProbabilityElement.wrap_elements(self.children) @classmethod def get_xml_tag(cls): \"\"\" :return: The tag of the xml",
"busStop=\"1\" /> <probability> <probabilityItem probability=\"0.5\"> <ride busStop=\"2\" modes=\"public\" /> <probability> <probabilityItem probability=\"0.5\"> <stop",
"of persons as it is already possible for vehicles. For example, this xml",
"exit(-1) try: self.per_wave = int(self.attributes.pop(self.per_wave_attribute_key)) except KeyError: self.per_wave = 1 try: route_id =",
"the output file \"\"\" # Parse the input file tree = etree.parse(input_file) routes",
"Licenses when the conditions for such availability set forth in the Eclipse #",
"define conditional probabilities. Note that the nested <probability> element should be a direct",
"if not given, uses the children of the <personFlow> element The id of",
"get_xml_tag(cls): \"\"\" :return: The tag of xml element coresponding to this class (probability)",
"id attribute in personFlow, quitting\") exit(-1) try: self.begin = int(self.attributes.pop(self.begin_attribute_key)) except KeyError: print(\"No",
":param route_id: :type route_id: str :return: The PersonRouteElement object having the given id",
"cls(elements[i], *args, **kwargs) @staticmethod def generate_multiple(elements): \"\"\" Loops over a list containing xml",
"Not mandatory, default is 1 - route : the id of the route",
"route_id: :type route_id: str :return: The PersonRouteElement object having the given id from",
"route return None def generate(self): \"\"\" :return: A copy of the sub elements",
"Not mandatory, if not given, number will be used - number : the",
"generated persons will be `<id>_<person_index>` where `<person_index>` is the index of the person",
"will not contain the <personFlow> elements. Note that the output file is overwritten",
"License 2.0 which is available at # https://www.eclipse.org/legal/epl-2.0/ # This Source Code may",
"describes probability elements that are used to generate alternatives with given probabilities. In",
"corresponding to this class (personRoute) \"\"\" return \"personRoute\" @staticmethod def get_route_by_id(routes, route_id): \"\"\"",
": \" + str(self.xml_element.sourceline)) @classmethod def get_xml_tag(cls): \"\"\" :return: The tag of xml",
"quitting\") exit(-1) try: self.per_wave = int(self.attributes.pop(self.per_wave_attribute_key)) except KeyError: self.per_wave = 1 try: route_id",
"the current class (personFlow) \"\"\" return \"personFlow\" def generate(self): \"\"\" :return: The persons",
"(self.number - 1) except KeyError: print(\"Neither period nor number given for personFlow \"",
"= int(self.attributes.pop(self.end_attribute_key)) except KeyError: self.end = self.default_end try: self.period = int(self.attributes.pop(self.period_attribute_key)) except KeyError:",
"for such availability set forth in the Eclipse # Public License 2.0 are",
"stop 2, there's a 50% chance they'll stay there during 10 ticks. The",
"input `.pflow.xml`` file's path and an output ``.rou.xml`` file's path. .. code-block:: bash",
"else: element.extend(self.generate_multiple(self.children)) elements.append(element) p_id += 1 begin += self.period return elements def generate_persons(input_file,",
"the current class. The given list is modified, be careful :param elements: a",
"str :return: The PersonRouteElement object having the given id from the given iterable.",
"list of xml elements :type elements: list \"\"\" for i in range(len(elements)): if",
"...Possibly other stuff </probabilityItem> <probabilityItem probability=\"0.5\"> second alternative </probabilityItem> </probability> This allows you",
"None self.period = None self.route = None # We check for the attributes",
"@author <NAME> # @date 2019-03-22 \"\"\" This tool allows to generate flows of",
"the route that the persons will follow Not mandatory, if not given, uses",
"/ (self.number - 1) except KeyError: print(\"Neither period nor number given for personFlow",
"one of its alternatives according to the probabilities. Probability elements can be nested,",
"perWave=\"10\"> <walk /> <ride /> <stop /> </personFlow> will generate person elements having",
"self.period = (self.end - self.begin) / (self.number - 1) except KeyError: print(\"Neither period",
"is overwritten without asking for permission. In your script ~~~~~~~~~~~~~~ You can import",
"<probabilityItem probability=\"0.5\"> <probability> ... </probability> ...Possibly other stuff </probabilityItem> <probabilityItem probability=\"0.5\"> second alternative",
"probabilityItem elements are allowed inside probability\") try: proba = float(sub_element.get(\"probability\")) if proba <",
"generates <person> elements. The generated <person> elements are sorted by their depart time.",
"the probabilities. Probability elements can be nested, so you can have: .. code-block::",
"except KeyError: self.per_wave = 1 try: route_id = self.attributes.pop(self.route_attribute_key) self.route = PersonRouteElement.get_route_by_id(routes, route_id)",
"> 1: raise ValueError(\"\") possibility = (proba, list(sub_element)) ProbabilityElement.wrap_elements(possibility[1]) self.possibilities.append(possibility) except (KeyError, ValueError):",
"from the given iterable. None if not found \"\"\" for route in routes:",
"class describes xml elements that are used to generate flows of persons as",
"1 else: self.period = (self.end - self.begin) / (self.number - 1) except KeyError:",
"route.id == route_id: return route return None def generate(self): \"\"\" :return: A copy",
"persons will be in 7 waves each containing 10 persons. These waves will",
"self.possibilities]) != 1: raise ValueError(\"Probabilities not summing up to 1 at line :",
"- The first flow consists of persons taking a bus from stop 1",
"given list is not modified :param elements: A list containing xml elements and",
"is written in another file. The resulting file will not contain the <personFlow>",
"def __init__(self, xml_element, routes): \"\"\" :param xml_element: The xml element :param routes: An",
"</probabilityItem> </probability> This allows you to define conditional probabilities. Note that the nested",
"<probabilityItem probability=\"0.5\"> second alternative </probabilityItem> </probability> This allows you to define conditional probabilities.",
"``.pflow.xml`` extension) to a sumo route file containing the generated <peron> elements. Here",
"!= 1: raise ValueError(\"Probabilities not summing up to 1 at line : \"",
"xml element \"\"\" super().__init__(xml_element) self.possibilities = [] for sub_element in list(self.xml_element): if sub_element.tag",
"list(self.xml_element): if sub_element.tag != \"probabilityItem\": raise Exception(\"Only probabilityItem elements are allowed inside probability\")",
"range(len(elements)): if not isinstance(elements[i], PersonGenerationElement) and elements[i].tag == cls.get_xml_tag(): elements[i] = cls(elements[i], *args,",
"self.route is not None: element.extend(self.route.generate()) else: element.extend(self.generate_multiple(self.children)) elements.append(element) p_id += 1 begin +=",
"to generate flows of persons for a SUMO simulation which is currently not",
"= random.random() for possibility in self.possibilities: cumulated_probability += float(possibility[0]) if p <= cumulated_probability:",
"PersonFlowElement.wrap_elements(children, routes=person_routes) for person_route in person_routes: children.remove(person_route) person_elements = PersonGenerationElement.generate_multiple(children) person_elements.sort(key=lambda e: int(e.get('depart')))",
"# @date 2019-03-22 \"\"\" This tool allows to generate flows of persons for",
"personFlow \" + str(id) + \", quitting\") exit(-1) try: self.per_wave = int(self.attributes.pop(self.per_wave_attribute_key)) except",
"not None: element.extend(self.route.generate()) else: element.extend(self.generate_multiple(self.children)) elements.append(element) p_id += 1 begin += self.period return",
"file is overwritten without asking for permission. In your script ~~~~~~~~~~~~~~ You can",
"begin=\"0\" end=\"3600\" number=\"7\" perWave=\"10\"> <walk /> <ride /> <stop /> </personFlow> will generate",
"use them in your own python script. See the documentation below for more",
"a ``<personRoute>`` element and referenced by its ID. - The second flow consists",
"bus stop 2, there's a 50% chance they'll stay there during 10 ticks.",
"script, parses <personFlow> tags in an XML file and generates <person> elements. The",
"to Use ---------- Via Command Line ~~~~~~~~~~~~~~~~ This script can be accessed directly",
"KeyError: self.per_wave = 1 try: route_id = self.attributes.pop(self.route_attribute_key) self.route = PersonRouteElement.get_route_by_id(routes, route_id) if",
"e: int(e.get('depart'))) routes.extend(person_elements) with open(output_file, \"w\") as f: f.write(etree.tostring(routes).decode()) f.close() if __name__ ==",
"second flow consists of persons taking a bus from stop 3 to stop",
"like: .. code-block:: xml <probability> <probabilityItem probability=\"0.5\">fist alternative</probabilityItem> <probabilityItem probability=\"0.5\">second alternative</probabilityItem> </probability> Each",
"written in another file. The resulting file will not contain the <personFlow> elements.",
"try: self.begin = int(self.attributes.pop(self.begin_attribute_key)) except KeyError: print(\"No begin in personFlow \" + str(id)",
"given iterable. None if not found \"\"\" for route in routes: if isinstance(route,",
"wave consists of 10 persons. For the persons going to bus stop 2,",
"given, uses the children of the <personFlow> element The id of generated persons",
"1) except KeyError: print(\"Neither period nor number given for personFlow \" + str(id)",
"in your own python script. See the documentation below for more details. \"\"\"",
"inside probability\") try: proba = float(sub_element.get(\"probability\")) if proba < 0 or proba >",
"print(\"Neither period nor number given for personFlow \" + str(id) + \", quitting\")",
"complete attributes list is: - id - begin : the time at which",
"The resulting file will not contain the <personFlow> elements. Note that the output",
"iterable where to look for routes :type routes: collections.Iterable \"\"\" super().__init__(xml_element) self.routes =",
"= float(sub_element.get(\"probability\")) if proba < 0 or proba > 1: raise ValueError(\"\") possibility",
"the number of waves. Only meaningful when period is not specified - perWave",
"method is meant to be implemented by subclasses It should return a list",
"elements. Note that the output file is overwritten if it is already exist",
"an XML file and generates <person> elements. The generated <person> elements are sorted",
"- begin : the time at which the flow starts - end :",
"& we leave the others try: self.id = self.attributes.pop(self.id_attribute_key) except KeyError: print(\"No id",
"self.possibilities: cumulated_probability += float(possibility[0]) if p <= cumulated_probability: result.extend(self.generate_multiple(possibility[1])) break return result class",
"if isinstance(element, PersonGenerationElement): result.extend(element.generate()) else: result.append(element.__copy__()) return result class ProbabilityElement(PersonGenerationElement): \"\"\" This class",
"containing xml elements and PersonGenerationElement objects. The PersonGenerationElement objects are replaced by elements",
"in person_routes: children.remove(person_route) person_elements = PersonGenerationElement.generate_multiple(children) person_elements.sort(key=lambda e: int(e.get('depart'))) routes.extend(person_elements) with open(output_file, \"w\")",
"command line arguments parser = argparse.ArgumentParser() parser.add_argument(\"source\") parser.add_argument(\"destination\") source, destination = parser.parse_args() generate_persons(source,",
"<probabilityItem probability=\"0.5\"> <ride busStop=\"3\" modes=\"public\"> </probabilityItem> </probability> </personRoute> <personFlow id=\"forward\" begin=\"0\" end=\"3600\" number=\"7\"",
"if not given, number will be used - number : the number of",
"departPos=\"0\"> <walk from=\"e3\" busStop=\"3\" /> <ride busStop=\"1\" modes=\"public\"/> <stop busStop=\"1\" duration=\"50\"/> </personFlow> </routes>",
"PersonGenerationElement objects. The PersonGenerationElement objects are replaced by elements generated from them The",
"<ride busStop=\"2\" modes=\"public\" /> <probability> <probabilityItem probability=\"0.5\"> <stop busStop=\"2\" duration=\"10\" /> </probabilityItem> <probabilityItem",
"<ride busStop=\"2\" modes=\"public\" /> </probabilityItem> <probabilityItem probability=\"0.5\"> <ride busStop=\"3\" modes=\"public\" /> </probabilityItem> </probability>",
"the sub elements of the original personRoute element probability elements are taken into",
"the persons is defined directly under the ``<personFlow>`` How to Use ---------- Via",
"later which is available at # https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html # SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later #",
"copy of the sub elements of the original personRoute element probability elements are",
"generate(self): \"\"\" :return: One of the alternatives according to the given probabilities \"\"\"",
"<ride busStop=\"3\" modes=\"public\" /> </probabilityItem> </probability> </personRoute> \"\"\" def __init__(self, xml_element): super().__init__(xml_element) self.id",
"= [] for sub_element in list(self.xml_element): if sub_element.tag != \"probabilityItem\": raise Exception(\"Only probabilityItem",
"not modified :param elements: A list containing xml elements and PersonGenerationElement objects. :type",
"elements corresponding to this class (personRoute) \"\"\" return \"personRoute\" @staticmethod def get_route_by_id(routes, route_id):",
"for element in elements: if isinstance(element, PersonGenerationElement): result.extend(element.generate()) else: result.append(element.__copy__()) return result class",
"script ~~~~~~~~~~~~~~ You can import the classes and methods in this module and",
"2.0 which is available at # https://www.eclipse.org/legal/epl-2.0/ # This Source Code may also",
"\"\"\" super().__init__(xml_element) self.possibilities = [] for sub_element in list(self.xml_element): if sub_element.tag != \"probabilityItem\":",
"The route followed by the persons of this flow is defined separately in",
"a bus from stop 1 to either stop 2 or stop 3 (with",
"= cls(elements[i], *args, **kwargs) @staticmethod def generate_multiple(elements): \"\"\" Loops over a list containing",
"taking a bus from stop 1 to either stop 2 or stop 3",
"probability between 0 and 1\") if sum([child[0] for child in self.possibilities]) != 1:",
"elements \"\"\" def __init__(self, xml_element): self.xml_element = xml_element if self.xml_element.tag != self.get_xml_tag(): raise",
"element requires attribute probability between 0 and 1\") if sum([child[0] for child in",
"ride, stop). The generated persons will be in 7 waves each containing 10",
"self.possibilities.append(possibility) except (KeyError, ValueError): raise ValueError(\"probabilityItem element requires attribute probability between 0 and",
"persons pere wave. The route followed by the persons is defined directly under",
"can have: .. code-block:: xml <personRoute id=\"route\"> <walk from=\"edge1\" busStop=\"1\"> <probability> <probabilityItem probability=\"0.5\">",
"\"\"\" This class serves as a base for person generation elements \"\"\" def",
"period_attribute_key = \"period\" number_attribute_key = \"number\" per_wave_attribute_key = \"perWave\" route_attribute_key = \"route\" def",
"at line : \" + str(self.xml_element.sourceline)) @classmethod def get_xml_tag(cls): \"\"\" :return: The tag",
"raise NotImplementedError @classmethod def wrap_elements(cls, elements, *args, **kwargs): \"\"\" Replaces xml elements with",
"also be made available under the following Secondary # Licenses when the conditions",
"PersonRouteElement.wrap_elements(children) person_routes = [child for child in children if isinstance(child, PersonRouteElement)] PersonFlowElement.wrap_elements(children, routes=person_routes)",
"to generate, it returns the children of one of its alternatives according to",
"@classmethod def get_xml_tag(cls): \"\"\" :return: The tag of the xml elements corresponding to",
"the children of one of its alternatives according to the probabilities. Probability elements",
"that are used to define person routes separately. .. code-block:: xml <personRoute id=\"route\">",
"and generates <person> elements. The generated <person> elements are sorted by their depart",
"from stop 1 to either stop 2 or stop 3 (with a 50%",
"of this flow are spawned in periodic waves with 10 persons pere wave.",
"going to bus stop 2, there's a 50% chance they'll stay there during",
"for permission. In your script ~~~~~~~~~~~~~~ You can import the classes and methods",
"over a list containing xml elements and PersonGenerationElement objects. The PersonGenerationElement objects are",
"same children (walk, ride, stop). The generated persons will be in 7 waves",
"details. \"\"\" from lxml import etree import argparse import random class PersonGenerationElement(object): \"\"\"",
"def generate_persons(input_file, output_file): \"\"\" Core method of the script, parses <personFlow> tags in",
"Public License, version 2 # or later which is available at # https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html",
"the index of the person in the flow (starting from 0) \"\"\" default_end",
"resulting file will not contain the <personFlow> elements. Note that the output file",
"file's path and an output ``.rou.xml`` file's path. .. code-block:: bash python personGenerator.py",
"coresponding to this class (probability) \"\"\" return \"probability\" def generate(self): \"\"\" :return: One",
"routes): \"\"\" :param xml_element: The xml element :param routes: An iterable where to",
"in get_xml_tag) with an object of the current class. The given list is",
"How to Use ---------- Via Command Line ~~~~~~~~~~~~~~~~ This script can be accessed",
"Secondary # Licenses when the conditions for such availability set forth in the",
"in periodic waves with 10 persons pere wave. The route followed by the",
"In your script ~~~~~~~~~~~~~~ You can import the classes and methods in this",
"- id - begin : the time at which the flow starts -",
":rtype list \"\"\" result = list() for element in elements: if isinstance(element, PersonGenerationElement):",
"1 to either stop 2 or stop 3 (with a 50% chance for",
"This Source Code may also be made available under the following Secondary #",
"class PersonFlowElement(PersonGenerationElement): \"\"\" This class describes xml elements that are used to generate",
"Line ~~~~~~~~~~~~~~~~ This script can be accessed directly by command line passing an",
"perWave=\"10\" departPos=\"0\"> <walk from=\"e3\" busStop=\"3\" /> <ride busStop=\"1\" modes=\"public\"/> <stop busStop=\"1\" duration=\"50\"/> </personFlow>",
"element.set(\"id\", self.id + \"_\" + str(p_id)) if self.route is not None: element.extend(self.route.generate()) else:",
"other stuff </probabilityItem> <probabilityItem probability=\"0.5\"> second alternative </probabilityItem> </probability> This allows you to",
"for person_route in person_routes: children.remove(person_route) person_elements = PersonGenerationElement.generate_multiple(children) person_elements.sort(key=lambda e: int(e.get('depart'))) routes.extend(person_elements) with",
"probability=\"0.5\"> <ride busStop=\"2\" modes=\"public\" /> </probabilityItem> <probabilityItem probability=\"0.5\"> <ride busStop=\"3\" modes=\"public\" /> </probabilityItem>",
"each containing 10 persons. These waves will be equally separated in time between",
"3600 The complete attributes list is: - id - begin : the time",
"\"\"\" This method is meant to be implemented by subclasses It should return",
"element in elements: if isinstance(element, PersonGenerationElement): result.extend(element.generate()) else: result.append(element.__copy__()) return result class ProbabilityElement(PersonGenerationElement):",
"number of waves. Only meaningful when period is not specified - perWave :",
"where `<person_index>` is the index of the person in the flow (starting from",
"of the flow \"\"\" begin = self.begin p_id = 0 elements = list()",
"**kwargs): \"\"\" Replaces xml elements with the appropriate tag (the one defined in",
"probabilities \"\"\" result = [] cumulated_probability = 0 p = random.random() for possibility",
"under the # terms of the Eclipse Public License 2.0 which is available",
"super().__init__(xml_element) self.id = self.xml_element.get(\"id\") self.children = list(self.xml_element) ProbabilityElement.wrap_elements(self.children) @classmethod def get_xml_tag(cls): \"\"\" :return:",
"to 1 at line : \" + str(self.xml_element.sourceline)) @classmethod def get_xml_tag(cls): \"\"\" :return:",
"return a list of elements generated by the element \"\"\" raise NotImplementedError @classmethod",
"<walk /> <ride /> <stop /> </personFlow> will generate person elements having the",
"elements that are used to define person routes separately. .. code-block:: xml <personRoute",
"is currently not possible in SUMO route files. It does so by converting",
"Parse the input file tree = etree.parse(input_file) routes = tree.getroot() children = list(routes)",
"route_id: return route return None def generate(self): \"\"\" :return: A copy of the",
"<routes> <personRoute id=\"route-1\"> <walk from=\"e1\" busStop=\"1\" /> <probability> <probabilityItem probability=\"0.5\"> <ride busStop=\"2\" modes=\"public\"",
"route in routes: if isinstance(route, PersonRouteElement) and route.id == route_id: return route return",
"self.begin p_id = 0 elements = list() while begin <= self.end: for i",
"= None # We check for the attributes that concern us & we",
"the conditions for such availability set forth in the Eclipse # Public License",
"EPL-2.0 OR GPL-2.0-or-later # @file personGenerator.py # @author <NAME> # @date 2019-03-22 \"\"\"",
"if not found \"\"\" for route in routes: if isinstance(route, PersonRouteElement) and route.id",
"``<personFlow>`` How to Use ---------- Via Command Line ~~~~~~~~~~~~~~~~ This script can be",
"tree.getroot() children = list(routes) for child in children: routes.remove(child) PersonRouteElement.wrap_elements(children) person_routes = [child",
"= \"perWave\" route_attribute_key = \"route\" def __init__(self, xml_element, routes): \"\"\" :param xml_element: The",
"i in range(len(elements)): if not isinstance(elements[i], PersonGenerationElement) and elements[i].tag == cls.get_xml_tag(): elements[i] =",
"- number : the number of waves. Only meaningful when period is not",
"@classmethod def get_xml_tag(cls): \"\"\" :return: The tag of xml element coresponding to this",
"of the original personRoute element probability elements are taken into account & used",
"is available at # https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html # SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later # @file personGenerator.py",
"OR GPL-2.0-or-later # @file personGenerator.py # @author <NAME> # @date 2019-03-22 \"\"\" This",
"probabilities inside the **personRoute** element to have different alternatives. Basically, you can have:",
"route=\"forward\" /> <personFlow id=\"backward\" begin=\"0\" end=\"3600\" period=\"600\" perWave=\"10\" departPos=\"0\"> <walk from=\"e3\" busStop=\"3\" />",
"busStop=\"2\" duration=\"10\" /> </probabilityItem> <probabilityItem probability=\"0.5\" /> </probability> </probabilityItem> <probabilityItem probability=\"0.5\"> <ride busStop=\"3\"",
": the time at which the flow ends. Not mandatory, default is 3600.",
"self.route = PersonRouteElement.get_route_by_id(routes, route_id) if self.route is None: raise Exception(\"Route with id \"",
"the following Secondary # Licenses when the conditions for such availability set forth",
"+ str(self.xml_element.sourceline)) @classmethod def get_xml_tag(cls): \"\"\" :return: The tag of xml element coresponding",
"super().__init__(xml_element) self.routes = routes self.attributes = {item[0]: item[1] for item in self.xml_element.items()} self.children",
"self.begin = int(self.attributes.pop(self.begin_attribute_key)) except KeyError: print(\"No begin in personFlow \" + str(id) +",
"/> </personFlow> will generate person elements having the same children (walk, ride, stop).",
"get_xml_tag(cls): \"\"\" :return: The tag of the xml elements corresponding to this class",
"duration=\"50\"/> </personFlow> </routes> The example above allows to generate two flows of persons",
"version 2 # or later which is available at # https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html # SPDX-License-Identifier:",
"- self.begin) / (self.number - 1) except KeyError: print(\"Neither period nor number given",
"The PersonGenerationElement objects are replaced by elements generated from them The given list",
"probability\") try: proba = float(sub_element.get(\"probability\")) if proba < 0 or proba > 1:",
"for a SUMO simulation which is currently not possible in SUMO route files.",
"can import the classes and methods in this module and use them in",
"for i in range(self.per_wave): element = etree.Element(\"person\", self.attributes) element.set(\"depart\", str(int(begin))) element.set(\"id\", self.id +",
"others. # This program and the accompanying materials are made available under the",
"it is already possible for vehicles. For example, this xml code: .. code-block::",
"routes.extend(person_elements) with open(output_file, \"w\") as f: f.write(etree.tostring(routes).decode()) f.close() if __name__ == \"__main__\": #",
"= \"id\" begin_attribute_key = \"begin\" end_attribute_key = \"end\" period_attribute_key = \"period\" number_attribute_key =",
"time at which the flow ends. Not mandatory, default is 3600. - period",
"KeyError: try: self.number = int(self.attributes.pop(self.number_attribute_key)) if self.number == 1: self.period = (self.end -",
"to be implemented by subclasses It should return the xml tag for elements",
"have: .. code-block:: xml <probability> <probabilityItem probability=\"0.5\"> <probability> ... </probability> ...Possibly other stuff",
"for each). The persons of this flow are spawned in 7 waves (equally",
"= list(self.xml_element) ProbabilityElement.wrap_elements(self.children) self.id = None self.begin = None self.period = None self.route",
"1: raise ValueError(\"Probabilities not summing up to 1 at line : \" +",
"f.write(etree.tostring(routes).decode()) f.close() if __name__ == \"__main__\": # Parses the command line arguments parser",
"0 p = random.random() for possibility in self.possibilities: cumulated_probability += float(possibility[0]) if p",
"account & used to generate an alternative \"\"\" return self.generate_multiple(self.children) class PersonFlowElement(PersonGenerationElement): \"\"\"",
"elements of the original personRoute element probability elements are taken into account &",
"nested, so you can have: .. code-block:: xml <probability> <probabilityItem probability=\"0.5\"> <probability> ...",
"is available at # https://www.eclipse.org/legal/epl-2.0/ # This Source Code may also be made",
"that the output file is overwritten if it is already exist :param input_file:",
"The given list is not modified :param elements: A list containing xml elements",
"<probability> ... </probability> ...Possibly other stuff </probabilityItem> <probabilityItem probability=\"0.5\"> second alternative </probabilityItem> </probability>",
"to a sumo route file containing the generated <peron> elements. Here is an",
"for personFlow \" + str(id) + \", quitting\") exit(-1) try: self.per_wave = int(self.attributes.pop(self.per_wave_attribute_key))",
"will be equally separated in time between 0 and 3600 The complete attributes",
"a sumo route file containing the generated <peron> elements. Here is an example",
"is 3600. - period : The time (in seconds) between two consecutive waves.",
"period=\"600\" perWave=\"10\" departPos=\"0\"> <walk from=\"e3\" busStop=\"3\" /> <ride busStop=\"1\" modes=\"public\"/> <stop busStop=\"1\" duration=\"50\"/>",
"separated in time between 0 and 3600 The complete attributes list is: -",
"\" + str(self.xml_element.sourceline)) except KeyError: pass @classmethod def get_xml_tag(cls): \"\"\" :return: The tag",
"elements are taken into account & used to generate an alternative \"\"\" return",
"<personRoute id=\"route\"> <walk /> <stop /> <ride /> </personRoute> The content of the",
"\"\"\" result = list() for element in elements: if isinstance(element, PersonGenerationElement): result.extend(element.generate()) else:",
"time (in seconds) between two consecutive waves. Not mandatory, if not given, number",
"<stop busStop=\"2\" duration=\"10\" /> </probabilityItem> <probabilityItem probability=\"0.5\" /> </probability> </probabilityItem> <probabilityItem probability=\"0.5\"> <ride",
"KeyError: self.end = self.default_end try: self.period = int(self.attributes.pop(self.period_attribute_key)) except KeyError: try: self.number =",
"<personFlow> element The id of generated persons will be `<id>_<person_index>` where `<person_index>` is",
"elements def generate_persons(input_file, output_file): \"\"\" Core method of the script, parses <personFlow> tags",
"each). The persons of this flow are spawned in 7 waves (equally separated",
"For example, this xml code: .. code-block:: xml <personFlow id=\"flow\" begin=\"0\" end=\"3600\" number=\"7\"",
":return: The tag of the xml elements corresponding to the current class (personFlow)",
"+ \"_\" + str(p_id)) if self.route is not None: element.extend(self.route.generate()) else: element.extend(self.generate_multiple(self.children)) elements.append(element)",
"Urban MObility; see https://eclipse.org/sumo # Copyright (C) 2019-2020 German Aerospace Center (DLR) and",
"\" + str(self.xml_element.sourceline)) @classmethod def get_xml_tag(cls): \"\"\" :return: The tag of xml element",
"xml elements corresponding to the current class (personFlow) \"\"\" return \"personFlow\" def generate(self):",
"object of the current class. The given list is modified, be careful :param",
"up to 1 at line : \" + str(self.xml_element.sourceline)) @classmethod def get_xml_tag(cls): \"\"\"",
"== route_id: return route return None def generate(self): \"\"\" :return: A copy of",
"self.per_wave = int(self.attributes.pop(self.per_wave_attribute_key)) except KeyError: self.per_wave = 1 try: route_id = self.attributes.pop(self.route_attribute_key) self.route",
"in an XML file and generates <person> elements. The generated <person> elements are",
"\"\"\" return \"personFlow\" def generate(self): \"\"\" :return: The persons of the flow \"\"\"",
"except KeyError: try: self.number = int(self.attributes.pop(self.number_attribute_key)) if self.number == 1: self.period = (self.end",
"person elements having the same children (walk, ride, stop). The generated persons will",
"output file is overwritten if it is already exist :param input_file: The path",
"file will not contain the <personFlow> elements. Note that the output file is",
"asked to generate, it returns the children of one of its alternatives according",
"be careful :param elements: a list of xml elements :type elements: list \"\"\"",
"isinstance(child, PersonRouteElement)] PersonFlowElement.wrap_elements(children, routes=person_routes) for person_route in person_routes: children.remove(person_route) person_elements = PersonGenerationElement.generate_multiple(children) person_elements.sort(key=lambda",
"using it. You can use probabilities inside the **personRoute** element to have different",
"of <probabilityItem> \"\"\" def __init__(self, xml_element): \"\"\" :param xml_element: The source xml element",
"in a ``<personRoute>`` element and referenced by its ID. - The second flow",
"defined separately in a ``<personRoute>`` element and referenced by its ID. - The",
"@staticmethod def get_route_by_id(routes, route_id): \"\"\" :param routes: :type routes: collections.Iterable :param route_id: :type",
"<personFlow id=\"flow\" begin=\"0\" end=\"3600\" number=\"7\" perWave=\"10\"> <walk /> <ride /> <stop /> </personFlow>",
"resulting xml elements :rtype list \"\"\" result = list() for element in elements:",
"This class method is meant to be implemented by subclasses It should return",
"These waves will be equally separated in time between 0 and 3600 The",
"The persons of the flow \"\"\" begin = self.begin p_id = 0 elements",
"(walk, ride, stop). The generated persons will be in 7 waves each containing",
"implemented by subclasses It should return a list of elements generated by the",
"Via Command Line ~~~~~~~~~~~~~~~~ This script can be accessed directly by command line",
"more details. \"\"\" from lxml import etree import argparse import random class PersonGenerationElement(object):",
"PersonFlowElement(PersonGenerationElement): \"\"\" This class describes xml elements that are used to generate flows",
"elements that are used to generate alternatives with given probabilities. In XML it",
"sub_element in list(self.xml_element): if sub_element.tag != \"probabilityItem\": raise Exception(\"Only probabilityItem elements are allowed",
"`<person_index>` is the index of the person in the flow (starting from 0)",
"list \"\"\" for i in range(len(elements)): if not isinstance(elements[i], PersonGenerationElement) and elements[i].tag ==",
"\"\"\" :param routes: :type routes: collections.Iterable :param route_id: :type route_id: str :return: The",
"try: self.number = int(self.attributes.pop(self.number_attribute_key)) if self.number == 1: self.period = (self.end - self.begin)",
"busStop=\"2\" modes=\"public\" /> </probabilityItem> <probabilityItem probability=\"0.5\"> <ride busStop=\"3\" modes=\"public\" /> </probabilityItem> </probability> </personRoute>",
"element \"\"\" super().__init__(xml_element) self.possibilities = [] for sub_element in list(self.xml_element): if sub_element.tag !=",
"flows of persons as it is already possible for vehicles. For example, this",
"and use them in your own python script. See the documentation below for",
"class (probability) \"\"\" return \"probability\" def generate(self): \"\"\" :return: One of the alternatives",
"the <personFlow> element The id of generated persons will be `<id>_<person_index>` where `<person_index>`",
"to the current class (personFlow) \"\"\" return \"personFlow\" def generate(self): \"\"\" :return: The",
"person using it. You can use probabilities inside the **personRoute** element to have",
"PersonGenerationElement): result.extend(element.generate()) else: result.append(element.__copy__()) return result class ProbabilityElement(PersonGenerationElement): \"\"\" This class describes probability",
"@staticmethod def generate_multiple(elements): \"\"\" Loops over a list containing xml elements and PersonGenerationElement",
"that concern us & we leave the others try: self.id = self.attributes.pop(self.id_attribute_key) except",
"def get_xml_tag(cls): \"\"\" :return: The tag of the xml elements corresponding to this",
"own python script. See the documentation below for more details. \"\"\" from lxml",
"result class ProbabilityElement(PersonGenerationElement): \"\"\" This class describes probability elements that are used to",
"as a base for person generation elements \"\"\" def __init__(self, xml_element): self.xml_element =",
"be in 7 waves each containing 10 persons. These waves will be equally",
"id=\"flow\" begin=\"0\" end=\"3600\" number=\"7\" perWave=\"10\"> <walk /> <ride /> <stop /> </personFlow> will",
"and methods in this module and use them in your own python script."
] |
[
"views from students.views import StudentsView,StudentViewusingID router = routers.DefaultRouter() router.register('',views.StudentsView) urlpatterns = [ #path('<int:pk>/',",
"students.views import StudentsView,StudentViewusingID router = routers.DefaultRouter() router.register('',views.StudentsView) urlpatterns = [ #path('<int:pk>/', StudentViewusingID.as_view()), path('',",
"from django.urls import path,include from rest_framework import routers from . import views from",
"import routers from . import views from students.views import StudentsView,StudentViewusingID router = routers.DefaultRouter()",
"rest_framework import routers from . import views from students.views import StudentsView,StudentViewusingID router =",
"<filename>4_SC_project/students/urls.py from django.urls import path,include from rest_framework import routers from . import views",
"import views from students.views import StudentsView,StudentViewusingID router = routers.DefaultRouter() router.register('',views.StudentsView) urlpatterns = [",
"from rest_framework import routers from . import views from students.views import StudentsView,StudentViewusingID router",
"from students.views import StudentsView,StudentViewusingID router = routers.DefaultRouter() router.register('',views.StudentsView) urlpatterns = [ #path('<int:pk>/', StudentViewusingID.as_view()),",
"path,include from rest_framework import routers from . import views from students.views import StudentsView,StudentViewusingID",
"import StudentsView,StudentViewusingID router = routers.DefaultRouter() router.register('',views.StudentsView) urlpatterns = [ #path('<int:pk>/', StudentViewusingID.as_view()), path('', include(router.urls)),",
". import views from students.views import StudentsView,StudentViewusingID router = routers.DefaultRouter() router.register('',views.StudentsView) urlpatterns =",
"import path,include from rest_framework import routers from . import views from students.views import",
"StudentsView,StudentViewusingID router = routers.DefaultRouter() router.register('',views.StudentsView) urlpatterns = [ #path('<int:pk>/', StudentViewusingID.as_view()), path('', include(router.urls)), ]",
"routers from . import views from students.views import StudentsView,StudentViewusingID router = routers.DefaultRouter() router.register('',views.StudentsView)",
"from . import views from students.views import StudentsView,StudentViewusingID router = routers.DefaultRouter() router.register('',views.StudentsView) urlpatterns",
"django.urls import path,include from rest_framework import routers from . import views from students.views"
] |
[
"fc(*fs): return functools.reduce( lambda fa, fb: lambda x: fa(fb(x)), *fs) a = 1",
"f2(x): return x * 6 def f3(x): return x - 9 def fc(*fs):",
"utf-8 -*- from __future__ import unicode_literals import functools def f1(x): return x +",
"lambda fa, fb: lambda x: fa(fb(x)), *fs) a = 1 b = f3(f2(f1(a)))",
"*fs) a = 1 b = f3(f2(f1(a))) print(b) c = functools.reduce( lambda fa,",
"def fc(*fs): return functools.reduce( lambda fa, fb: lambda x: fa(fb(x)), *fs) a =",
"6 def f3(x): return x - 9 def fc(*fs): return functools.reduce( lambda fa,",
"unicode_literals import functools def f1(x): return x + 3 def f2(x): return x",
"import functools def f1(x): return x + 3 def f2(x): return x *",
"f3(f2(f1(a))) print(b) c = functools.reduce( lambda fa, fb: lambda x: fa(fb(x)), [f3, f2,",
"3 def f2(x): return x * 6 def f3(x): return x - 9",
"def f2(x): return x * 6 def f3(x): return x - 9 def",
"fa, fb: lambda x: fa(fb(x)), *fs) a = 1 b = f3(f2(f1(a))) print(b)",
"+ 3 def f2(x): return x * 6 def f3(x): return x -",
"* 6 def f3(x): return x - 9 def fc(*fs): return functools.reduce( lambda",
"-*- coding: utf-8 -*- from __future__ import unicode_literals import functools def f1(x): return",
"__future__ import unicode_literals import functools def f1(x): return x + 3 def f2(x):",
"= f3(f2(f1(a))) print(b) c = functools.reduce( lambda fa, fb: lambda x: fa(fb(x)), [f3,",
"return x - 9 def fc(*fs): return functools.reduce( lambda fa, fb: lambda x:",
"<reponame>mheanng/PythonNote<filename>docs/02.AI_ML/code-1805/Day05all/cc1.py # -*- coding: utf-8 -*- from __future__ import unicode_literals import functools def",
"import unicode_literals import functools def f1(x): return x + 3 def f2(x): return",
"x: fa(fb(x)), *fs) a = 1 b = f3(f2(f1(a))) print(b) c = functools.reduce(",
"def f1(x): return x + 3 def f2(x): return x * 6 def",
"a = 1 b = f3(f2(f1(a))) print(b) c = functools.reduce( lambda fa, fb:",
"f1(x): return x + 3 def f2(x): return x * 6 def f3(x):",
"return x * 6 def f3(x): return x - 9 def fc(*fs): return",
"9 def fc(*fs): return functools.reduce( lambda fa, fb: lambda x: fa(fb(x)), *fs) a",
"= 1 b = f3(f2(f1(a))) print(b) c = functools.reduce( lambda fa, fb: lambda",
"x + 3 def f2(x): return x * 6 def f3(x): return x",
"fa, fb: lambda x: fa(fb(x)), [f3, f2, f1])(a) print(c) d = fc([f3, f2,",
"# -*- coding: utf-8 -*- from __future__ import unicode_literals import functools def f1(x):",
"f3(x): return x - 9 def fc(*fs): return functools.reduce( lambda fa, fb: lambda",
"fb: lambda x: fa(fb(x)), *fs) a = 1 b = f3(f2(f1(a))) print(b) c",
"lambda x: fa(fb(x)), *fs) a = 1 b = f3(f2(f1(a))) print(b) c =",
"c = functools.reduce( lambda fa, fb: lambda x: fa(fb(x)), [f3, f2, f1])(a) print(c)",
"return x + 3 def f2(x): return x * 6 def f3(x): return",
"functools.reduce( lambda fa, fb: lambda x: fa(fb(x)), *fs) a = 1 b =",
"b = f3(f2(f1(a))) print(b) c = functools.reduce( lambda fa, fb: lambda x: fa(fb(x)),",
"def f3(x): return x - 9 def fc(*fs): return functools.reduce( lambda fa, fb:",
"from __future__ import unicode_literals import functools def f1(x): return x + 3 def",
"lambda fa, fb: lambda x: fa(fb(x)), [f3, f2, f1])(a) print(c) d = fc([f3,",
"lambda x: fa(fb(x)), [f3, f2, f1])(a) print(c) d = fc([f3, f2, f1])(a) print(d)",
"- 9 def fc(*fs): return functools.reduce( lambda fa, fb: lambda x: fa(fb(x)), *fs)",
"coding: utf-8 -*- from __future__ import unicode_literals import functools def f1(x): return x",
"print(b) c = functools.reduce( lambda fa, fb: lambda x: fa(fb(x)), [f3, f2, f1])(a)",
"functools def f1(x): return x + 3 def f2(x): return x * 6",
"return functools.reduce( lambda fa, fb: lambda x: fa(fb(x)), *fs) a = 1 b",
"functools.reduce( lambda fa, fb: lambda x: fa(fb(x)), [f3, f2, f1])(a) print(c) d =",
"fa(fb(x)), *fs) a = 1 b = f3(f2(f1(a))) print(b) c = functools.reduce( lambda",
"1 b = f3(f2(f1(a))) print(b) c = functools.reduce( lambda fa, fb: lambda x:",
"fb: lambda x: fa(fb(x)), [f3, f2, f1])(a) print(c) d = fc([f3, f2, f1])(a)",
"= functools.reduce( lambda fa, fb: lambda x: fa(fb(x)), [f3, f2, f1])(a) print(c) d",
"x - 9 def fc(*fs): return functools.reduce( lambda fa, fb: lambda x: fa(fb(x)),",
"x * 6 def f3(x): return x - 9 def fc(*fs): return functools.reduce(",
"-*- from __future__ import unicode_literals import functools def f1(x): return x + 3"
] |
[
"TrainingData = [] TrainingResult = [] TestSampleData = [] TestActualResult = [] def",
"for row in datas: if row is None or len(row) == 0: continue",
"pickle TrainingData = [] TrainingResult = [] TestSampleData = [] TestActualResult = []",
"\"\"\" Created on Wed Oct 25 17:14:19 2017 @author: Student \"\"\" from sklearn.naive_bayes",
"csv import pickle TrainingData = [] TrainingResult = [] TestSampleData = [] TestActualResult",
"None or len(row) == 0: continue i = i + 1 if i",
"= [] TestActualResult = [] def __loadData(dataFile): data = [] i = 0",
"[] TestSampleData = [] TestActualResult = [] def __loadData(dataFile): data = [] i",
"on Wed Oct 25 17:14:19 2017 @author: Student \"\"\" from sklearn.naive_bayes import GaussianNB",
"open('TCGA-predict-log.txt', 'w') TestData = __loadData('tcga_data.csv') model = pickle.load( open( \"gtex_TrainingResult.pkl\", \"rb\" ) )",
"TestSampleData = [] TestActualResult = [] def __loadData(dataFile): data = [] i =",
"= open('TCGA-predict-log.txt', 'w') TestData = __loadData('tcga_data.csv') model = pickle.load( open( \"gtex_TrainingResult.pkl\", \"rb\" )",
"i = 0 with open(dataFile, 'rt') as csvfile: datas = csv.reader(csvfile, delimiter =",
"is None or len(row) == 0: continue i = i + 1 if",
"',') for row in datas: if row is None or len(row) == 0:",
"= pickle.load( open( \"gtex_TrainingResult.pkl\", \"rb\" ) ) me = np.array(TestData).astype(np.float) del(TestData) log.write(model.predict(me)) log.write('\\n')",
"# -*- coding: utf-8 -*- \"\"\" Created on Wed Oct 25 17:14:19 2017",
"csv.reader(csvfile, delimiter = ',') for row in datas: if row is None or",
"as csvfile: datas = csv.reader(csvfile, delimiter = ',') for row in datas: if",
"<= 5000: continue data.append(row) return data log = open('TCGA-predict-log.txt', 'w') TestData = __loadData('tcga_data.csv')",
"continue data.append(row) return data log = open('TCGA-predict-log.txt', 'w') TestData = __loadData('tcga_data.csv') model =",
"i + 1 if i <= 5000: continue data.append(row) return data log =",
"GaussianNB import numpy as np import csv import pickle TrainingData = [] TrainingResult",
"= ',') for row in datas: if row is None or len(row) ==",
"i = i + 1 if i <= 5000: continue data.append(row) return data",
"log = open('TCGA-predict-log.txt', 'w') TestData = __loadData('tcga_data.csv') model = pickle.load( open( \"gtex_TrainingResult.pkl\", \"rb\"",
"delimiter = ',') for row in datas: if row is None or len(row)",
"TestData = __loadData('tcga_data.csv') model = pickle.load( open( \"gtex_TrainingResult.pkl\", \"rb\" ) ) me =",
"__loadData('tcga_data.csv') model = pickle.load( open( \"gtex_TrainingResult.pkl\", \"rb\" ) ) me = np.array(TestData).astype(np.float) del(TestData)",
"5000: continue data.append(row) return data log = open('TCGA-predict-log.txt', 'w') TestData = __loadData('tcga_data.csv') model",
"with open(dataFile, 'rt') as csvfile: datas = csv.reader(csvfile, delimiter = ',') for row",
"Created on Wed Oct 25 17:14:19 2017 @author: Student \"\"\" from sklearn.naive_bayes import",
"data.append(row) return data log = open('TCGA-predict-log.txt', 'w') TestData = __loadData('tcga_data.csv') model = pickle.load(",
"model = pickle.load( open( \"gtex_TrainingResult.pkl\", \"rb\" ) ) me = np.array(TestData).astype(np.float) del(TestData) log.write(model.predict(me))",
"-*- coding: utf-8 -*- \"\"\" Created on Wed Oct 25 17:14:19 2017 @author:",
"continue i = i + 1 if i <= 5000: continue data.append(row) return",
"= csv.reader(csvfile, delimiter = ',') for row in datas: if row is None",
"@author: Student \"\"\" from sklearn.naive_bayes import GaussianNB import numpy as np import csv",
"\"\"\" from sklearn.naive_bayes import GaussianNB import numpy as np import csv import pickle",
"<gh_stars>0 # -*- coding: utf-8 -*- \"\"\" Created on Wed Oct 25 17:14:19",
"= i + 1 if i <= 5000: continue data.append(row) return data log",
"coding: utf-8 -*- \"\"\" Created on Wed Oct 25 17:14:19 2017 @author: Student",
"== 0: continue i = i + 1 if i <= 5000: continue",
"= [] TrainingResult = [] TestSampleData = [] TestActualResult = [] def __loadData(dataFile):",
"= [] TestSampleData = [] TestActualResult = [] def __loadData(dataFile): data = []",
"= 0 with open(dataFile, 'rt') as csvfile: datas = csv.reader(csvfile, delimiter = ',')",
"0: continue i = i + 1 if i <= 5000: continue data.append(row)",
"open(dataFile, 'rt') as csvfile: datas = csv.reader(csvfile, delimiter = ',') for row in",
"row is None or len(row) == 0: continue i = i + 1",
"sklearn.naive_bayes import GaussianNB import numpy as np import csv import pickle TrainingData =",
"datas = csv.reader(csvfile, delimiter = ',') for row in datas: if row is",
"[] TrainingResult = [] TestSampleData = [] TestActualResult = [] def __loadData(dataFile): data",
"numpy as np import csv import pickle TrainingData = [] TrainingResult = []",
"__loadData(dataFile): data = [] i = 0 with open(dataFile, 'rt') as csvfile: datas",
"[] i = 0 with open(dataFile, 'rt') as csvfile: datas = csv.reader(csvfile, delimiter",
"+ 1 if i <= 5000: continue data.append(row) return data log = open('TCGA-predict-log.txt',",
"TestActualResult = [] def __loadData(dataFile): data = [] i = 0 with open(dataFile,",
"= [] i = 0 with open(dataFile, 'rt') as csvfile: datas = csv.reader(csvfile,",
"import GaussianNB import numpy as np import csv import pickle TrainingData = []",
"= __loadData('tcga_data.csv') model = pickle.load( open( \"gtex_TrainingResult.pkl\", \"rb\" ) ) me = np.array(TestData).astype(np.float)",
"[] TestActualResult = [] def __loadData(dataFile): data = [] i = 0 with",
"return data log = open('TCGA-predict-log.txt', 'w') TestData = __loadData('tcga_data.csv') model = pickle.load( open(",
"2017 @author: Student \"\"\" from sklearn.naive_bayes import GaussianNB import numpy as np import",
"len(row) == 0: continue i = i + 1 if i <= 5000:",
"Wed Oct 25 17:14:19 2017 @author: Student \"\"\" from sklearn.naive_bayes import GaussianNB import",
"row in datas: if row is None or len(row) == 0: continue i",
"TrainingResult = [] TestSampleData = [] TestActualResult = [] def __loadData(dataFile): data =",
"or len(row) == 0: continue i = i + 1 if i <=",
"Oct 25 17:14:19 2017 @author: Student \"\"\" from sklearn.naive_bayes import GaussianNB import numpy",
"25 17:14:19 2017 @author: Student \"\"\" from sklearn.naive_bayes import GaussianNB import numpy as",
"-*- \"\"\" Created on Wed Oct 25 17:14:19 2017 @author: Student \"\"\" from",
"1 if i <= 5000: continue data.append(row) return data log = open('TCGA-predict-log.txt', 'w')",
"import pickle TrainingData = [] TrainingResult = [] TestSampleData = [] TestActualResult =",
"import numpy as np import csv import pickle TrainingData = [] TrainingResult =",
"from sklearn.naive_bayes import GaussianNB import numpy as np import csv import pickle TrainingData",
"data = [] i = 0 with open(dataFile, 'rt') as csvfile: datas =",
"def __loadData(dataFile): data = [] i = 0 with open(dataFile, 'rt') as csvfile:",
"if i <= 5000: continue data.append(row) return data log = open('TCGA-predict-log.txt', 'w') TestData",
"np import csv import pickle TrainingData = [] TrainingResult = [] TestSampleData =",
"data log = open('TCGA-predict-log.txt', 'w') TestData = __loadData('tcga_data.csv') model = pickle.load( open( \"gtex_TrainingResult.pkl\",",
"as np import csv import pickle TrainingData = [] TrainingResult = [] TestSampleData",
"0 with open(dataFile, 'rt') as csvfile: datas = csv.reader(csvfile, delimiter = ',') for",
"i <= 5000: continue data.append(row) return data log = open('TCGA-predict-log.txt', 'w') TestData =",
"[] def __loadData(dataFile): data = [] i = 0 with open(dataFile, 'rt') as",
"17:14:19 2017 @author: Student \"\"\" from sklearn.naive_bayes import GaussianNB import numpy as np",
"Student \"\"\" from sklearn.naive_bayes import GaussianNB import numpy as np import csv import",
"'w') TestData = __loadData('tcga_data.csv') model = pickle.load( open( \"gtex_TrainingResult.pkl\", \"rb\" ) ) me",
"in datas: if row is None or len(row) == 0: continue i =",
"if row is None or len(row) == 0: continue i = i +",
"utf-8 -*- \"\"\" Created on Wed Oct 25 17:14:19 2017 @author: Student \"\"\"",
"import csv import pickle TrainingData = [] TrainingResult = [] TestSampleData = []",
"datas: if row is None or len(row) == 0: continue i = i",
"csvfile: datas = csv.reader(csvfile, delimiter = ',') for row in datas: if row",
"= [] def __loadData(dataFile): data = [] i = 0 with open(dataFile, 'rt')",
"'rt') as csvfile: datas = csv.reader(csvfile, delimiter = ',') for row in datas:"
] |
[
"('sources', '0023_add_person_owned_by_field_for_dive_relationship'), ] operations = [ migrations.RemoveField( model_name='person', name='owned_by', ), migrations.AddField( model_name='person', name='exportable_by',",
"import migrations, models class Migration(migrations.Migration): dependencies = [ ('sources', '0023_add_person_owned_by_field_for_dive_relationship'), ] operations =",
"models class Migration(migrations.Migration): dependencies = [ ('sources', '0023_add_person_owned_by_field_for_dive_relationship'), ] operations = [ migrations.RemoveField(",
"] operations = [ migrations.RemoveField( model_name='person', name='owned_by', ), migrations.AddField( model_name='person', name='exportable_by', field=models.ManyToManyField(blank=True, help_text='These",
"from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sources', '0023_add_person_owned_by_field_for_dive_relationship'), ]",
"migrations.AddField( model_name='person', name='exportable_by', field=models.ManyToManyField(blank=True, help_text='These are the dives that can export this source.',",
"<reponame>industrydive/sourcedive<gh_stars>0 # Generated by Django 2.2.10 on 2020-02-24 21:54 from django.db import migrations,",
"migrations.RemoveField( model_name='person', name='owned_by', ), migrations.AddField( model_name='person', name='exportable_by', field=models.ManyToManyField(blank=True, help_text='These are the dives that",
"dependencies = [ ('sources', '0023_add_person_owned_by_field_for_dive_relationship'), ] operations = [ migrations.RemoveField( model_name='person', name='owned_by', ),",
"Generated by Django 2.2.10 on 2020-02-24 21:54 from django.db import migrations, models class",
"2.2.10 on 2020-02-24 21:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies =",
"field=models.ManyToManyField(blank=True, help_text='These are the dives that can export this source.', related_name='dive_owner', to='sources.Dive'), ),",
"class Migration(migrations.Migration): dependencies = [ ('sources', '0023_add_person_owned_by_field_for_dive_relationship'), ] operations = [ migrations.RemoveField( model_name='person',",
"model_name='person', name='owned_by', ), migrations.AddField( model_name='person', name='exportable_by', field=models.ManyToManyField(blank=True, help_text='These are the dives that can",
"21:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sources', '0023_add_person_owned_by_field_for_dive_relationship'),",
"migrations, models class Migration(migrations.Migration): dependencies = [ ('sources', '0023_add_person_owned_by_field_for_dive_relationship'), ] operations = [",
"= [ migrations.RemoveField( model_name='person', name='owned_by', ), migrations.AddField( model_name='person', name='exportable_by', field=models.ManyToManyField(blank=True, help_text='These are the",
"Django 2.2.10 on 2020-02-24 21:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies",
"by Django 2.2.10 on 2020-02-24 21:54 from django.db import migrations, models class Migration(migrations.Migration):",
"django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sources', '0023_add_person_owned_by_field_for_dive_relationship'), ] operations",
"help_text='These are the dives that can export this source.', related_name='dive_owner', to='sources.Dive'), ), ]",
"'0023_add_person_owned_by_field_for_dive_relationship'), ] operations = [ migrations.RemoveField( model_name='person', name='owned_by', ), migrations.AddField( model_name='person', name='exportable_by', field=models.ManyToManyField(blank=True,",
"2020-02-24 21:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sources',",
"name='exportable_by', field=models.ManyToManyField(blank=True, help_text='These are the dives that can export this source.', related_name='dive_owner', to='sources.Dive'),",
"), migrations.AddField( model_name='person', name='exportable_by', field=models.ManyToManyField(blank=True, help_text='These are the dives that can export this",
"# Generated by Django 2.2.10 on 2020-02-24 21:54 from django.db import migrations, models",
"name='owned_by', ), migrations.AddField( model_name='person', name='exportable_by', field=models.ManyToManyField(blank=True, help_text='These are the dives that can export",
"= [ ('sources', '0023_add_person_owned_by_field_for_dive_relationship'), ] operations = [ migrations.RemoveField( model_name='person', name='owned_by', ), migrations.AddField(",
"[ migrations.RemoveField( model_name='person', name='owned_by', ), migrations.AddField( model_name='person', name='exportable_by', field=models.ManyToManyField(blank=True, help_text='These are the dives",
"model_name='person', name='exportable_by', field=models.ManyToManyField(blank=True, help_text='These are the dives that can export this source.', related_name='dive_owner',",
"on 2020-02-24 21:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [",
"operations = [ migrations.RemoveField( model_name='person', name='owned_by', ), migrations.AddField( model_name='person', name='exportable_by', field=models.ManyToManyField(blank=True, help_text='These are",
"[ ('sources', '0023_add_person_owned_by_field_for_dive_relationship'), ] operations = [ migrations.RemoveField( model_name='person', name='owned_by', ), migrations.AddField( model_name='person',",
"Migration(migrations.Migration): dependencies = [ ('sources', '0023_add_person_owned_by_field_for_dive_relationship'), ] operations = [ migrations.RemoveField( model_name='person', name='owned_by',"
] |
[
"product in category.values(): for website in product.values(): website[\"info\"] = {\"id\": \"\", \"url\": \"\",",
"\"\", \"currency\": \"\"} website[\"datapoints\"] = [] Filemanager.save_record_data(data) def hard_reset(): print(\"Hard resetting data...\") logging.getLogger(__name__).info(\"Hard",
"for product in category.values(): for website in product.values(): website[\"info\"] = {\"id\": \"\", \"url\":",
"logging.getLogger(__name__).info(\"Resetting data\") data = Filemanager.get_record_data() for category in data.values(): for product in category.values():",
"logging from scraper import Filemanager def reset(): print(\"Resetting data...\") logging.getLogger(__name__).info(\"Resetting data\") data =",
"data.values(): for product in category.values(): for website in product.values(): website[\"info\"] = {\"id\": \"\",",
"website[\"datapoints\"] = [] Filemanager.save_record_data(data) def hard_reset(): print(\"Hard resetting data...\") logging.getLogger(__name__).info(\"Hard resetting data\") data",
"\"\"} website[\"datapoints\"] = [] Filemanager.save_record_data(data) def hard_reset(): print(\"Hard resetting data...\") logging.getLogger(__name__).info(\"Hard resetting data\")",
"<reponame>Ignis-Altum/scraper import logging from scraper import Filemanager def reset(): print(\"Resetting data...\") logging.getLogger(__name__).info(\"Resetting data\")",
"for website in product.values(): website[\"info\"] = {\"id\": \"\", \"url\": \"\", \"currency\": \"\"} website[\"datapoints\"]",
"Filemanager def reset(): print(\"Resetting data...\") logging.getLogger(__name__).info(\"Resetting data\") data = Filemanager.get_record_data() for category in",
"\"\", \"url\": \"\", \"currency\": \"\"} website[\"datapoints\"] = [] Filemanager.save_record_data(data) def hard_reset(): print(\"Hard resetting",
"import logging from scraper import Filemanager def reset(): print(\"Resetting data...\") logging.getLogger(__name__).info(\"Resetting data\") data",
"= [] Filemanager.save_record_data(data) def hard_reset(): print(\"Hard resetting data...\") logging.getLogger(__name__).info(\"Hard resetting data\") data =",
"category in data.values(): for product in category.values(): for website in product.values(): website[\"info\"] =",
"Filemanager.save_record_data(data) def hard_reset(): print(\"Hard resetting data...\") logging.getLogger(__name__).info(\"Hard resetting data\") data = {} Filemanager.save_record_data(data)",
"= Filemanager.get_record_data() for category in data.values(): for product in category.values(): for website in",
"= {\"id\": \"\", \"url\": \"\", \"currency\": \"\"} website[\"datapoints\"] = [] Filemanager.save_record_data(data) def hard_reset():",
"{\"id\": \"\", \"url\": \"\", \"currency\": \"\"} website[\"datapoints\"] = [] Filemanager.save_record_data(data) def hard_reset(): print(\"Hard",
"category.values(): for website in product.values(): website[\"info\"] = {\"id\": \"\", \"url\": \"\", \"currency\": \"\"}",
"Filemanager.get_record_data() for category in data.values(): for product in category.values(): for website in product.values():",
"in category.values(): for website in product.values(): website[\"info\"] = {\"id\": \"\", \"url\": \"\", \"currency\":",
"in data.values(): for product in category.values(): for website in product.values(): website[\"info\"] = {\"id\":",
"def hard_reset(): print(\"Hard resetting data...\") logging.getLogger(__name__).info(\"Hard resetting data\") data = {} Filemanager.save_record_data(data) Filemanager.clear_product_csv()",
"data\") data = Filemanager.get_record_data() for category in data.values(): for product in category.values(): for",
"scraper import Filemanager def reset(): print(\"Resetting data...\") logging.getLogger(__name__).info(\"Resetting data\") data = Filemanager.get_record_data() for",
"\"url\": \"\", \"currency\": \"\"} website[\"datapoints\"] = [] Filemanager.save_record_data(data) def hard_reset(): print(\"Hard resetting data...\")",
"for category in data.values(): for product in category.values(): for website in product.values(): website[\"info\"]",
"website in product.values(): website[\"info\"] = {\"id\": \"\", \"url\": \"\", \"currency\": \"\"} website[\"datapoints\"] =",
"website[\"info\"] = {\"id\": \"\", \"url\": \"\", \"currency\": \"\"} website[\"datapoints\"] = [] Filemanager.save_record_data(data) def",
"\"currency\": \"\"} website[\"datapoints\"] = [] Filemanager.save_record_data(data) def hard_reset(): print(\"Hard resetting data...\") logging.getLogger(__name__).info(\"Hard resetting",
"def reset(): print(\"Resetting data...\") logging.getLogger(__name__).info(\"Resetting data\") data = Filemanager.get_record_data() for category in data.values():",
"in product.values(): website[\"info\"] = {\"id\": \"\", \"url\": \"\", \"currency\": \"\"} website[\"datapoints\"] = []",
"from scraper import Filemanager def reset(): print(\"Resetting data...\") logging.getLogger(__name__).info(\"Resetting data\") data = Filemanager.get_record_data()",
"import Filemanager def reset(): print(\"Resetting data...\") logging.getLogger(__name__).info(\"Resetting data\") data = Filemanager.get_record_data() for category",
"[] Filemanager.save_record_data(data) def hard_reset(): print(\"Hard resetting data...\") logging.getLogger(__name__).info(\"Hard resetting data\") data = {}",
"product.values(): website[\"info\"] = {\"id\": \"\", \"url\": \"\", \"currency\": \"\"} website[\"datapoints\"] = [] Filemanager.save_record_data(data)",
"data...\") logging.getLogger(__name__).info(\"Resetting data\") data = Filemanager.get_record_data() for category in data.values(): for product in",
"print(\"Resetting data...\") logging.getLogger(__name__).info(\"Resetting data\") data = Filemanager.get_record_data() for category in data.values(): for product",
"reset(): print(\"Resetting data...\") logging.getLogger(__name__).info(\"Resetting data\") data = Filemanager.get_record_data() for category in data.values(): for",
"data = Filemanager.get_record_data() for category in data.values(): for product in category.values(): for website"
] |